Skip to content
Advertisement

Pass argument to Django form

There are several questions on stackoverflow related to this topic but none of them explains whats happening neither provides working solution.

I need to pass user’s first name as an argument to Django ModelForm when rendering template with this form.

I have some basic form:

JavaScript

Here’s my sample class-based view:

JavaScript

What do I pass to MyForm when initialising it and how do I access this value inside the __init__ method?

I want to use ‘first_name’ value as a value for one of the fields in template by updating self.fields[***].widget.attrs.update({'value': self.first_name}).

Advertisement

Answer

The solution is as simple as passing initial data dictionary to MyForm for fields you need to set initial value.

This parameter, if given, should be a dictionary mapping field names to initial values. So if MyModel class has a field my_field and you want to set its initial value to foo_bar then you should create MyForm object with initial parameters as follows:

JavaScript

A link to Django documentation on this topic.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement