Stan Reduta
Stan Reduta

Reputation: 3492

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}).

Upvotes: 2

Views: 4232

Answers (2)

Stan Reduta
Stan Reduta

Reputation: 3492

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.

Upvotes: 2

Gregory
Gregory

Reputation: 7242

You can pass the parameter instance to your form like this:

obj = MyModel(...)   
form = MyForm(instance=obj)

If obj has a user first name it will be attached to your form.

Upvotes: 1

Related Questions