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:

class MyForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.first_name = ???
        super(MyForm, self).__init__(*args, **kwargs)
    class Meta:
        model = MyModel
        fields = [***other fields***, 'first_name']

Here’s my sample class-based view:

class SomeClassBasedView(View):
def get(self, request):
    user_first_name = request.user.first_name
    form = MyForm(user_first_name)
    return render(request, 'my_template.html', {'form': form})

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:

form = MyForm(initial={'my_field': 'foo_bar'})

A link to Django documentation on this topic.

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