14

In django how to make form field optional ?

my model,

class Student(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()
Nishant
  • 153
  • 1
  • 1
  • 8
  • Here is the answer: [http://stackoverflow.com/questions/5940308/how-to-make-filefield-in-django-optional][1] [1]: http://stackoverflow.com/questions/5940308/how-to-make-filefield-in-django-optional – KamilD Apr 24 '14 at 12:28
  • @KamilDębowski - that is for manually created forms, not for forms created automatically from models. – Dominic Rodger Apr 24 '14 at 15:02

5 Answers5

18

Presuming you want to make last_name optional, you can use the blank attribute:

class Student(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40, blank=True)
    email = models.EmailField()

Note that on CharField and TextField, you probably don't want to set null (see this answer for a discussion as to why), but on other field types, you'll need to, or you'll be unable to save instances where optional values are omitted.

Community
  • 1
  • 1
Dominic Rodger
  • 97,747
  • 36
  • 197
  • 212
18

You use the required argument, sent in with a False value:

email = models.EmailField(required=False)

stevieb
  • 9,065
  • 3
  • 26
  • 36
Marshall X
  • 784
  • 1
  • 5
  • 17
5

If you want to allow blank values in a date field (e.g., DateField, TimeField, DateTimeField) or numeric field (e.g., IntegerField, DecimalField, FloatField), you’ll need to use both null=True and blank=True.

Nishant Nawarkhede
  • 8,234
  • 12
  • 59
  • 81
0

Use null=True and blank=True in your model.

sdamashek
  • 636
  • 1
  • 4
  • 13
-5
class StudentForm(ModelForm):
    class Meta:
        model = Student
        exclude = ['first_name', ...]