[SOLVED] django autofil with the pk page

Issue

This Content is from Stack Overflow. Question asked by Robin Langlois

I would like to add documents to an employee’s profile in a form but I would like the form to automatically select the id or the (pk) of the employee’s page, anyone have the solution?

view.py

def createDocument(request):
forms = documentForm()

if request.method == 'POST':
    forms = documentForm(request.POST, request.FILES)
    if forms.is_valid():
        forms.save()
        return redirect('/employe')

context = {'forms':forms}
return render(request, 'accounts/document_form.html', context)

add document
form



Solution

Please, read how to work with Django-GCBV, more here:
https://docs.djangoproject.com/en/4.1/ref/class-based-views/generic-editing/#django.views.generic.edit.UpdateView

in your case:

# views.py
def createDocument(UpdateView):
    model = Employer
    form_class = documentForm
    sucsess_url = '/employe'
    template_name = 'accounts/document_form.html'

If you named template like employe_form.html you can avoid template_name attribute.

don’t forget to setup urls.py:

urlpatterns = [
    ... # other urls
    path('add_document_to_employe/<pk>', createDocument.as_view(), name='create_document'),
    ... # other urls
]


This Question was asked in StackOverflow by Robin Langlois and Answered by Maxim Danilov It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?