Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Django's DateTimeField optional?

Tags:

python

django

I am trying to implement a to-do-list website to practice using Django. In models.py, I have a class called Item to represent a to-do item. In it, I have the following line:

due_date = models.DateTimeField(required=False)

due_date is meant to be an optional field in case the user has a deadline for some to-do item. The problem is that the line above gives me a TypeError due to unexpected keyword argument 'required'.

So, it seems that I cannot use the keyword argument 'required' for DateTimeField. Is there any way I can make a DateTimeField optional? Or is there a standard implementation for the problem I am having?

like image 453
Kiet Tran Avatar asked Jul 05 '12 19:07

Kiet Tran


People also ask

How do you make a field optional in Django?

You would have to add blank=True as well in field definition. If the model field has blank=True, then required is set to False on the form field. Otherwise, required=True. Don't forget to reset and sync DB again after changing this.

How do you make a field non mandatory in Django?

The simplest way is by using the field option blank=True (docs.djangoproject.com/en/dev/ref/models/fields/#blank).

Can DateTimeField be null Django?

Model fields use blank=True , which must be combined with null=True for a DateTimeField in order to allow a NULL value to be stored for the column in the database. Otherwise, you'd get an IntegrityError .


2 Answers

"required" is a valid argument for Django forms. For models, you want the keyword args blank=True (for the admin) and null=True (for the database).

like image 118
bruno desthuilliers Avatar answered Oct 09 '22 16:10

bruno desthuilliers


Use due_date = models.DateTimeField(null=True, blank=True)

Check Field Options for more information.

like image 39
machaku Avatar answered Oct 09 '22 16:10

machaku