如何允许在 Django 表单中提交空字符串?
How to allow submission of empty string in django forms?
我的模型是这样设置的:
class Example(models.Model):
user = models.ForeignKey(User)
comment = models.CharField(max_length=200)
我的表格是这样的:
class ExampleForm(forms.ModelForm):
comment = forms.CharField(required=False)
class Meta:
model = Example
fields = ("comment")
现在可以在评论栏为空的时候提交表单,在不同的页面显示时,会显示为空字符串。我希望在提交该字段为空的表单时将评论保存为空字符串。
例如:我在评论区保存了"example comment"的表格。 "example comment" 然后保存到那个 Example 对象。然后我返回到表单,其中实例作为先前的 Example 对象。最初评论字段填写为"example comment"。我想删除该评论并保存,以便评论现在保存为“”。
您可能需要做一些手工工作,例如:
# in the views.py
if form.is_valid():
new_example = form.save(commit=False)
if not form.cleaned_data['comment']:
new_example.comment = ""
new_example.save()
我的模型是这样设置的:
class Example(models.Model):
user = models.ForeignKey(User)
comment = models.CharField(max_length=200)
我的表格是这样的:
class ExampleForm(forms.ModelForm):
comment = forms.CharField(required=False)
class Meta:
model = Example
fields = ("comment")
现在可以在评论栏为空的时候提交表单,在不同的页面显示时,会显示为空字符串。我希望在提交该字段为空的表单时将评论保存为空字符串。
例如:我在评论区保存了"example comment"的表格。 "example comment" 然后保存到那个 Example 对象。然后我返回到表单,其中实例作为先前的 Example 对象。最初评论字段填写为"example comment"。我想删除该评论并保存,以便评论现在保存为“”。
您可能需要做一些手工工作,例如:
# in the views.py
if form.is_valid():
new_example = form.save(commit=False)
if not form.cleaned_data['comment']:
new_example.comment = ""
new_example.save()