i able update height
attribute of mylittlemodel
using mymodelform
(onetoonefield(mylittlemodel)
) follows:
models.py
class mylittlemodel(models.model): height = models.integerfield() has_color = models.nullbooleanfield(null=true, blank=true) class mymodel(models.model): my_little_model = models.onetoonefield(mylittlemodel) age = models.integerfield() is_male = models.booleanfield(default=false)
forms.py
class mymodelform(forms.modelform): height = forms.integerfield(max_length=30) class meta: model = mymodel fields = ("height", "age")
views.py
class myupdateview(updateview): form_class = mymodelform model = mymodel template_name = 'my_template.html' def form_valid(self, form): my_little_model = mylittlemodel.objects.create(form.cleaned_data["height"]) form.instance.my_little_model = my_little_model form.instance.save() return super(myupdateview, self).form_valid(form) def get_success_url(self): return reverse("my_list_view")
urls.py
urlpatterns = patterns('', url(regex=r'^update/(?p<pk>\d+)/$', view=myupdateview.as_view(), name="my_update_view"), )
i think not coding style because forces modify code in modelform in view, preferable happen in 1 location.
so possible set value my_little_model.height
without modifying views code did?
note: don't title question, if has suggestion renaming more readable please let me know.
i overriding mymodelform
's save method, so:
class mymodelform(forms.modelform): height = forms.charfield(max_length=30) class meta: model = mymodel fields = ("height", "age") def save(self, *args, **kwargs): my_little_model = mylittlemodel.objects.create(height=self.cleaned_data["height"]) self.instance.my_little_model = my_little_model self.instance.save() return super(mymodelform2, self).save(*args, **kwargs)
then view becomes:
class myupdateview(updateview): template_name = "my_template.html" form_class = mymodelform model = mymodel def get_success_url(self): return reverse("my_list_view")
this way, logic updating model information lives in form - if want change what's being updated, can in 1 place.
Comments
Post a Comment