2013-06-06 58 views
0

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) 

我能夠保存數據,表單處於更新模式。

如果我刪除字段中的所有數據並點擊保存,該字段沒有被保存,意味着它沒有使用空值。

保存空白區域,但空值不保存。我希望它也接受空值。

+0

兩個答案都是正確的 –

回答

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'})) 
1

如果我理解正確的話,在你LocationNotes形式,你需要做other_locationlocation_description也是可選:

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