[Answered ]-How do I initiate values for fields in a form for editing in a template

2👍

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.

👤bento

Leave a comment