问题
This is a continuation of this question in which I am trying to figure out how to construct a PointField composed of lat / lon FloatFields. I have taken @Simon's advice and restructured my model to look like this:
class Point(models.Model):
lat = models.FloatField()
lon = models.FloatField()
class Thing(models.Model):
point = models.ForeignKey(Point)
My form has two fields corresponding to values from google maps' longitude and latitude coordinates:
class StepThreeForm(forms.Form):
lat = forms.FloatField()
lon = forms.FloatField()
...
However, this does not work for obvious reasons, but I am not sure how to fix it. To clarify, I am trying to have two form fields corresponding to the foreign key values of lat
and lon
. Here is the supplementary information (I am using a FormWizard and forms.Form):
url(r'^mapform/$', login_required(MyWizard.as_view([StepOneForm, StepTwoForm, StepThreeForm])), name='create'),
class MyWizard(SessionWizardView): ## this view also serves to edit existing objects and provide their instances
def done(self, form_list, **kwargs):
id = form_list[0].cleaned_data['id']
try:
thing = Thing.objects.get(pk=id)
instance = thing
except:
thing = None
instance = None
if thing and thing.user != self.request.user:
raise HttpResponseForbidden()
if not thing:
instance = Thing()
for form in form_list:
for field, value in form.cleaned_data.iteritems():
setattr(instance, field, value)
instance.user = self.request.user
instance.save()
return render_to_response('wizard-done.html', {
'form_data': [form.cleaned_data for form in form_list],})
I appreciate any and all advice and help!
EDIT: Update based on Yuji Tomita's input. Most of it made a lot of sense (Thank you!), but I'm not sure why it results in a ValueError.
class MyWizard(SessionWizardView):
....
for form in form_list:
form.save(instance)
...
class StepOneForm(forms.Form):
...
def save(self, thing):
for field, value in self.cleaned_data.items():
setattr(thing, field, value)
class StepTwoForm(forms.Form):
...
def save(self, thing):
for field, value in self.cleaned_data.items():
setattr(thing, field, value)
I believe that I should keep the form fields as lat and lon, because I am using a google map in my form and taking the lat and lon from a selected input, then constructing a point fields from those values:
class StepThreeForm(forms.Form):
lat = forms.FloatField()
lon = forms.FloatField()
def save(self, thing):
thing.point = Point.objects.get_or_create(lat=self.cleaned_data.get('lat'), lon=self.cleaned_data.get('lon'))
This yields a ValueError: Cannot assign "(<Point: Point object>, False)": "Thing.point" must be a "Point" instance.
Traceback:
File "/lib/python2.7/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/lib/python2.7/django/contrib/auth/decorators.py" in _wrapped_view
20. return view_func(request, *args, **kwargs)
File "/lib/python2.7/django/views/generic/base.py" in view
48. return self.dispatch(request, *args, **kwargs)
File "/lib/python2.7/django/contrib/formtools/wizard/views.py" in dispatch
223. response = super(WizardView, self).dispatch(request, *args, **kwargs)
File "/lib/python2.7/django/views/generic/base.py" in dispatch
69. return handler(request, *args, **kwargs)
File "/lib/python2.7/django/contrib/formtools/wizard/views.py" in post
286. return self.render_done(form, **kwargs)
File "/lib/python2.7/django/contrib/formtools/wizard/views.py" in render_done
328. done_response = self.done(final_form_list, **kwargs)
File "/myproject/myapp/forms.py" in done
93. form.save(instance)
File "/myproject/myapp/forms.py" in save
67. thing.point = Thing.objects.get_or_create(lat=self.cleaned_data.get('lat'), lon=self.cleaned_data.get('lon'))
File "/lib/python2.7/django/db/models/fields/related.py" in __set__
366. self.field.name, self.field.rel.to._meta.object_name))
回答1:
I'd recommend building a save
method on each of your forms which knows how to save itself to the database. It follows a general pattern that "the form performs its action via form.save()" so it should be intuitive to follow.
The bottom line is that right now you have a blanket: "for every field in all forms, set the Thing attribute to those fields".
Since in reality you have per-form save behavior, I think it makes sense to require passing the instance to each form so that each form has a chance to save data in the way appropriate for its fields.
class Form1(...):
def save(self, thing):
for field, value in self.cleaned_data.items():
setattr(thing, field, value)
class Form2(...):
def save(self, thing):
thing.point = Point.objects.get_or_create(lat=self.cleaned_data.get('lat'), long=...)
# note, you may not want get_or_create if you don't want to share points.
Your view would then become:
for form in form_list:
form.save(instance)
Just an idea.
If you want to be more DRY about it and like the automation of your other forms, I'd build a base form which has a save method already defined:
class BaseSaveBehaviorForm(forms.Form):
def save(self, thing):
for field, value in self.cleaned_data.items():
setattr(thing, field, value)
class NormalBehaviorForm(BaseSaveBehaviorForm):
# your forms as usual
class SpecialSaveBehaviorForm(forms.Form):
def save(self, instance):
# do something unusual
来源:https://stackoverflow.com/questions/19188908/django-saving-foreign-key-from-form