[Answer]-Django – ModelForm display the item but insert the foreignkey

1👍

Rather than displaying the user as read only form field, it would probably be better to exclude the field from your form, and display the user’s name in the template, wherever you wish, as follows: {{ request.user.get_full_name }}

Then, after you check that the form is valid, you would set the User as follows:

project_contact = form.save(commit=False)  # This initializes the object with form data without saving, so you can edit or alter fields before the model is created
project_contact.project_contact_defined_by = request.user
project_contact.save()

You would also want to check that the user exists (and is not anonymous):

if user.is_authenticated():
    # Check that form is valid, then create model

Note that if you are using a generic FormView, then you will be overriding form_valid() (which already checks that the form is valid) and use self.request.user to access the user.

👤Johndt

Leave a comment