Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

This field is required error in django

Tags:

python

django

In the model I set:

class Task(models.Model):
    EstimateEffort = models.PositiveIntegerField('Estimate hours',max_length=200)
    Finished = models.IntegerField('Finished percentage',blank=True)

But in the web page, if I didn't set a value for the Finished field, it is showing an error This field is required. I tried null=True and blank=True. But none of them worked. So could you please tell me how can I make a field allowed to be empty.

I have found that there is a attribute empty_strings_allowed, i set it to True, but still the same, and i subclass the models.IntegerField. It still can not work

class IntegerNullField(models.IntegerField):
    description = "Stores NULL but returns empty string"
    empty_strings_allowed =True
    log.getlog().debug("asas")
    def to_python(self, value):
        log.getlog().debug("asas")
        # this may be the value right out of the db, or an instance
        if isinstance(value, models.IntegerField):
            # if an instance, return the instance
            return value
        if value == None:
            # if db has NULL (==None in Python), return empty string
            return ""
        try:
            return int(value)
        except (TypeError, ValueError):
            msg = self.error_messages['invalid'] % str(value)
            raise exceptions.ValidationError(msg)

    def get_prep_value(self, value):
        # catches value right before sending to db
        if value == "":
            # if Django tries to save an empty string, send to db None (NULL)
            return None
        else:
            return int(value) # otherwise, just pass the value
like image 535
jimwan Avatar asked Dec 14 '12 06:12

jimwan


People also ask

How do you remove this field is required Django?

If yes try to disable this behavior, set the novalidate attribute on the form tag As <form action="{% url 'new_page' %}", method="POST" novalidate> in your html file.

How do you make a field required in Django?

Let's try to use required via Django Web application we created, visit http://localhost:8000/ and try to input the value based on option or validation applied on the Field. Hit submit. Hence Field is accepting the form even without any data in the geeks_field. This makes required=False implemented successfully.

What is field in Django?

Fields in Django are the data types to store a particular type of data. For example, to store an integer, IntegerField would be used. These fields have in-built validation for a particular data type, that is you can not store “abc” in an IntegerField.

What is CharField in Django?

CharField in Django Forms is a string field, for small- to large-sized strings. It is used for taking text inputs from the user. The default widget for this input is TextInput.


2 Answers

Use

Finished = models.IntegerField('Finished percentage', blank=True, null=True)

Read https://docs.djangoproject.com/en/1.4/ref/models/fields/#blank:

null is purely database-related, whereas blank is validation-related.

You might have defined the field without null=True first. Changing that in the code now won't change the initial layout of the database. Use South for database migrations or change the database manually.

like image 142
Matthias Avatar answered Oct 24 '22 07:10

Matthias


On a form you could set required=False on the field:

Finished = forms.IntegerField(required=False)

Or to avoid redefining the field on a ModelForm,

def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    self.fields['Finished'].required = False
    #self.fields['Finished'].empty_label = 'Nothing' #optionally change the name
like image 24
CJ4 Avatar answered Oct 24 '22 07:10

CJ4