How do I initiate values for fields in a form for editing in a template

谁说我不能喝 提交于 2019-12-06 15:08:27

Assuming you are using a ModelForm, it's actually fairly simple. The task is something like this: retrieve the object of the model that you want to populate your 'edit' for with, create a new form based on your ModelForm, and populate it with the object using 'instance'.

Here's the skeleton of your view:

def view(request): 
  obj = Model.objects.get(pk = objectpk)
  form = MyModelForm(instance = obj)

  return render (request, "template", {'form' = form})

You can access the 'initial' values by using something like:

form.fields['fieldname'].initial = somevalue

And then you'd return the form like above.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!