In django how to make form field optional ?
在django中如何使表单字段可选?
my model,
class Student(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()
5 个解决方案
#1
5
Presuming you want to make last_name
optional, you can use the blank
attribute:
假设您要使last_name可选,您可以使用blank属性:
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.
请注意,在CharField和TextField上,您可能不希望设置null(有关原因的讨论,请参阅此答案),但是对于其他字段类型,您需要,或者您将无法将实例保存在哪里可选值被省略。
#2
2
You use the required
argument, sent in with a False
value:
您使用必需参数,使用False值发送:
email = models.EmailField(required=False)
email = models.EmailField(required = False)
#3
1
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
.
如果要在日期字段(例如,DateField,TimeField,DateTimeField)或数字字段(例如,IntegerField,DecimalField,FloatField)中允许空值,则需要同时使用null = True和blank = True。
#4
0
Use null=True
and blank=True
in your model.
在模型中使用null = True和blank = True。
#5
-1
class StudentForm(ModelForm):
class Meta:
model = Student
exclude = ['first_name', ...]
#1
5
Presuming you want to make last_name
optional, you can use the blank
attribute:
假设您要使last_name可选,您可以使用blank属性:
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.
请注意,在CharField和TextField上,您可能不希望设置null(有关原因的讨论,请参阅此答案),但是对于其他字段类型,您需要,或者您将无法将实例保存在哪里可选值被省略。
#2
2
You use the required
argument, sent in with a False
value:
您使用必需参数,使用False值发送:
email = models.EmailField(required=False)
email = models.EmailField(required = False)
#3
1
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
.
如果要在日期字段(例如,DateField,TimeField,DateTimeField)或数字字段(例如,IntegerField,DecimalField,FloatField)中允许空值,则需要同时使用null = True和blank = True。
#4
0
Use null=True
and blank=True
in your model.
在模型中使用null = True和blank = True。
#5
-1
class StudentForm(ModelForm):
class Meta:
model = Student
exclude = ['first_name', ...]