问题
How can I pass an object into a model form to pre-populate the field when the page is rendered? I want to do something similar to the build in Django UpdateView class based view but with a function based view.
回答1:
Just get the object from model and pass that object as instance to the form. Then pass the form to the template. Write your view like below example.
def func(request, id):
object = Model.objects.get(id=id)
form = ModelForm(instance=object)
return render(request, 'my_template.html', {'form':form})
回答2:
Here, I tried something....
def approveform(request, pk):
if pk:
form = Admission.objects.get(pk=pk)
p = Admission.objects.get(pk=pk)
form = ApproveForm(instance=form)
return render(
request,
'Automation/formapprove.html',
{
'year': datetime.now().year,
'form': form,
'test': p,
}
)
来源:https://stackoverflow.com/questions/47842708/update-view-using-function-based-view