I'm currently constructing a create layout page for users to input values and use within a template. My problem right now is in my view function I can't get the field data out of the model and repopulate it into a django form. I want only 1 data entry for the Layout model that is always grabbed and put into the form so the user can edit then resave it. This issue will reside in the View.py. Here is what i have:
View.py:
def create_layoutform(request, template_name='layout/create.html'):
if len(Layout.objects.all()) > 0:
# if you have a form, load it
MyLayout = Layout.objects.get(pk=1)
LayoutUpdateForm = LayoutForm(MyLayout)
tmpl_vars = {
'layoutupdateform':LayoutUpdateForm,
}
return render(request, template_name, tmpl_vars)
else:
layout_form = LayoutForm(request.POST or None)
layout = layout_form.save(commit=False)
layout.save()
tmpl_vars = {
'layoutform':layout_form,
}
return render(request, template_name, tmpl_vars)
My print output for the view: Layout.objects.get(pk=1)
Grabs just the name of the model (Layout object)
I believe it is because of this line; LayoutUpdateForm = LayoutForm(MyLayout)
. The first argument to a Django Form is data
, but you want to use the instance
arguments [1]. Try changing it to LayoutUpdateForm = LayoutForm(instance=MyLayout)
.
NOTE: This assumes your LayoutForm
is inherited from forms.ModelForm
.
[1] https://github.com/django/django/blob/master/django/forms/models.py#L313
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.