null =模型中的True不接受空值

时间:2013-06-06 08:13:50

标签: django django-models django-forms django-views

views.py

report = Report.objects.get(user=user.id)
reportnotesform=ReportNotes(instance=report)
if request.method == 'POST':
    locationnotesform=LocationNotes(request.POST,instance=report)
    if locationnotesform.is_valid():
        locationnotesform.save() 

forms.py

class LocationNotes(forms.ModelForm):
    other_location = forms.CharField(widget=forms.TextInput(attrs={'class':'ir-textbox'}))
    location_description = forms.CharField(widget=forms.Textarea(attrs={'style':'width:20em'}))

models.py

class Report(models.Model):
    user = models.ForeignKey(User, null=False)
    location_description = models.TextField('Location description', null=True, blank=True)
    other_location = models.CharField('Other', max_length=100, null=True, blank=True)

我可以保存数据,表单处于更新模式。

如果我删除字段中的所有数据并单击“保存”,则表示该字段未保存,表示它未采用空值。

保存空格,但null不保存。我希望它也接受空值。

2 个答案:

答案 0 :(得分:1)

如果我理解正确,请在LocationNotes表格中other_locationlocation_description选择:

other_location = forms.CharField(
    widget=forms.TextInput(attrs={'class':'ir-textbox'}),
    required=False)

答案 1 :(得分:1)

你的模型很好,但形式会给你错误。 将required=False传递给表单中的字段定义。

class LocationNotes(forms.ModelForm):
    other_location = forms.CharField(required=False, widget=forms.TextInput(attrs={'class':'ir-textbox'}))
    location_description = forms.CharField(required=False, widget=forms.Textarea(attrs={'style':'width:20em'}))