Can I make an admin field not required in Django without creating a form?

PythonDjangoDjango ModelsDjango AdminDjango Forms

Python Problem Overview


Every time I enter in a new player in the Admin portion of Django I get an error message that says "This field is required.".

Is there a way to make a field not required without having to create a custom form? Can I do this within models.py or admin.py?

Here's what my class in models.py looks like.

class PlayerStat(models.Model):
    player = models.ForeignKey(Player)
    
    rushing_attempts = models.CharField(
        max_length = 100,
        verbose_name = "Rushing Attempts"
        )
    rushing_yards = models.CharField(
        max_length = 100,
        verbose_name = "Rushing Yards"
        )
    rushing_touchdowns = models.CharField(
        max_length = 100,
        verbose_name = "Rushing Touchdowns"
        )
    passing_attempts = models.CharField(
        max_length = 100,
        verbose_name = "Passing Attempts"
        )

Thanks

Python Solutions


Solution 1 - Python

Just Put

blank=True

in your model i.e.:

rushing_attempts = models.CharField(
        max_length = 100,
        verbose_name = "Rushing Attempts",
        blank=True
        )

Solution 2 - Python

Use blank=True, null=True

class PlayerStat(models.Model):
    player = models.ForeignKey(Player)

    rushing_attempts = models.CharField(
        max_length = 100,
        verbose_name = "Rushing Attempts",
        blank=True,
        null=True
        )
    rushing_yards = models.CharField(
        max_length = 100,
        verbose_name = "Rushing Yards",
        blank=True,
        null=True
        )
    rushing_touchdowns = models.CharField(
        max_length = 100,
        verbose_name = "Rushing Touchdowns",
        blank=True,
        null=True
        )
    passing_attempts = models.CharField(
        max_length = 100,
        verbose_name = "Passing Attempts",
        blank=True,
        null=True
        )

Solution 3 - Python

If the field is set blankable in model level, it really means empty string are allowed. An empty string and a null really aren't the same thing. Don't break your data integrity only because the framework has set some bad default features.

Instead of setting the blank, override the get_form -method:

    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        form.base_fields["rushing_attempts"].required = False

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionbigmike7801View Question on Stackoverflow
Solution 1 - PythonfabrizioMView Answer on Stackoverflow
Solution 2 - PythonDawn T CherianView Answer on Stackoverflow
Solution 3 - Pythonniko.makelaView Answer on Stackoverflow