gpt4 book ai didi

python - Django 表单 : could not convert string to float

转载 作者:行者123 更新时间:2023-12-01 05:20:24 25 4
gpt4 key购买 nike

我正在尝试使用 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

调试该行时,formprice 的值似乎没有更新(它似乎是 '') .

当传递''时,如何将表单中的价格值更改为0?执行此操作的最佳方法是什么?

我花了 3 个小时寻找解决这个问题的方法,但没有成功。这是我第一次在 django 中使用表单,所以我很可能会遗漏一些完全明显的东西。

任何帮助将不胜感激。

最佳答案

form.cleaned_data 中获取值,而不是使用 form['fieldname'].data

例如:

date = form.cleaned_data['date']

请参阅 processing the data from a form 上的文档了解更多详情。

关于python - Django 表单 : could not convert string to float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22519738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com