mercredi 13 août 2014

python - django formes : pas pu convertir string en float - Stack Overflow


I am trying to validate a form using django forms. I have the following model:


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)

and the following form:


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

There is some frontend validation but I want to use the is_valid() funtionality as well. I have the following piece of code in 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) + '/')

Everything is working fine, except when the price I receive is ''. I want to allow this and default to 0. However, I receive the following error on the line marked with >>>:


could not convert string to float

When debugging that line, it appears that the value of price in form does not get updated (it appears to be '').


How could I change the value of price in the form to 0 when '' is passed? What would be the best way to go about doing this?


I have been searching for a way to fix this for 3 hours now without success. This is the first time I am using forms in django so I may very well be missing something completely obvious.


Any help will be greatly appreciated.




Fetch the values from form.cleaned_data, instead of using form['fieldname'].data


For example:


date = form.cleaned_data['date']

See the docs on processing the data from a form for further details.




There might be more than one problem, but the most obvious one that stands out is this:


price = modes.FloatField(..., blank=False, ...)

in your Session model.


Set blank=True to allow the form field to be blank. The ORM will then use your default=0 when saving if the form field was blank.



I am trying to validate a form using django forms. I have the following model:


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)

and the following form:


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

There is some frontend validation but I want to use the is_valid() funtionality as well. I have the following piece of code in 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) + '/')

Everything is working fine, except when the price I receive is ''. I want to allow this and default to 0. However, I receive the following error on the line marked with >>>:


could not convert string to float

When debugging that line, it appears that the value of price in form does not get updated (it appears to be '').


How could I change the value of price in the form to 0 when '' is passed? What would be the best way to go about doing this?


I have been searching for a way to fix this for 3 hours now without success. This is the first time I am using forms in django so I may very well be missing something completely obvious.


Any help will be greatly appreciated.



Fetch the values from form.cleaned_data, instead of using form['fieldname'].data


For example:


date = form.cleaned_data['date']

See the docs on processing the data from a form for further details.



There might be more than one problem, but the most obvious one that stands out is this:


price = modes.FloatField(..., blank=False, ...)

in your Session model.


Set blank=True to allow the form field to be blank. The ORM will then use your default=0 when saving if the form field was blank.


0 commentaires:

Enregistrer un commentaire