我正在尝试使用django表单验证表单。我有以下型号:
class Session(models.Model):
# id = AutoField(primary_key=True) added automatically.
sport = models.ForeignKey('Sport', unique=False, blank=False, null=False, to_field='sport', on_delete=models.CASCADE, )
hostplayer = models.ForeignKey(User, unique=False, blank=False, null=False, on_delete=models.CASCADE, related_name='member_host', )
guestplayer = models.ForeignKey(User, unique=False, blank=True, null=True, on_delete=models.CASCADE, related_name='member_guest', )
date = models.DateField(blank=False, null=False, )
time = models.TimeField(blank=False, null=False, )
city = models.ForeignKey('City', unique=False, blank=False, null=False, to_field='city', on_delete=models.CASCADE, )
location = models.CharField(max_length=64, unique=False, blank=False, null=False, )
price = models.FloatField(unique=False, blank=False, null=False, default=0, )
details = models.TextField(unique=False, blank=True, null=True, )
def __unicode__(self):
return unicode(self.id)
以下表格:
class CreateSessionForm(forms.Form):
sport = forms.CharField()
date = forms.DateTimeField()
time = forms.TimeField()
city = forms.CharField()
location = forms.CharField()
price = forms.FloatField(required=False, initial=0, )
details = forms.CharField(required=False, )
def clean_price(self):
prc = self.cleaned_data['price']
if prc is None:
return 0
return prc
有一些前端验证,但我也想使用is_valid()
功能。我在views.py
中有以下代码:
if request.method == "POST":
form = CreateSessionForm(data = request.POST)
if form.is_valid():
# Create session object.
session = Session.objects.create(sport=Sport.objects.get(sport = form['sport'].data), hostplayer = request.user, guestplayer = None,
date = form['date'].data, time = form['time'].data, city = City.objects.get(city=form['city'].data),
>>> location = form['location'].data, price = form['price'].data, details = form['details'].data)
session.save()
# Return to the session page if successful.
return HttpResponseRedirect('/session/' + str(session.id) + '/')
除非我收到的价格为''
,否则一切正常。我想允许这个,默认为0
。但是,我在标有>>>
的行上收到以下错误:
could not convert string to float
调试该行时,price
中的form
值似乎未更新(似乎为''
)。
当0
通过时,如何将表单中的价格值更改为''
?这样做最好的方法是什么?
我一直在寻找一种方法来解决这个问题3个小时,但没有成功。这是我第一次在django中使用表单,所以我很可能会遗漏一些完全明显的表单。
非常感谢任何帮助。
答案 0 :(得分:2)
从form.cleaned_data
获取值,而不是使用form['fieldname'].data
例如:
date = form.cleaned_data['date']
有关详细信息,请参阅processing the data from a form上的文档。
答案 1 :(得分:0)
可能存在多个问题,但最明显的问题是:
price = modes.FloatField(..., blank=False, ...)
在你的会话模型中。
设置blank = True以允许表单字段为空。如果表单字段为空,则ORM将在保存时使用默认值= 0.