Django how to make form fields optional

2020-07-10 05:56发布

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()

标签: python django
5条回答
对你真心纯属浪费
2楼-- · 2020-07-10 06:20

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

email = models.EmailField(required=False)

查看更多
Anthone
3楼-- · 2020-07-10 06:25
class StudentForm(ModelForm):
    class Meta:
        model = Student
        exclude = ['first_name', ...]
查看更多
叼着烟拽天下
4楼-- · 2020-07-10 06:27

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.

查看更多
ゆ 、 Hurt°
5楼-- · 2020-07-10 06:35

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

查看更多
6楼-- · 2020-07-10 06:46

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.

查看更多
登录 后发表回答