pynovice
pynovice

Reputation: 7752

Django Create View parameters on form

I have a Django generic create view

class TestCreateView(CreateView):
    form_class = TestCreateForm

##forms.py
class TestCreateForm(forms.ModelForm):
    class Meta:
        model = Test

    def __init__(self, user, *args, **kwargs):
        super(TestCreateForm).__init__(*args, **kwargs)
        self.fields['test_field'] = Testing.objects.filter(user=user)

In function based views I would do like this:

form = TestCreateForm(request.user)

Now on the generic class based view do I have to overwrite, get and post method just for this?

Upvotes: 1

Views: 3194

Answers (2)

Viktor eXe
Viktor eXe

Reputation: 640

Since you need to add the argument in the init (every time you instanciate the form) what you can do is override the get_form_kwargs from the CreateView class:

class TestCreateView(CreateView):
form_class = TestCreateForm

    def get_form_kwargs(self):
        kwargs = {
            'initial': self.get_initial(),
            'prefix': self.get_prefix(),
            'user': self.request.user
        }

        if self.request.method in ('POST', 'PUT'):
            kwargs.update({
                'data': self.request.POST,
                'files': self.request.FILES,
            })
        return kwargs

Upvotes: 0

SunnySydeUp
SunnySydeUp

Reputation: 6790

class TestCreateView(CreateView):
    form_class = TestCreateForm

    def get_form_kwargs(self, **kwargs):
        form_kwargs = super(TestCreateView, self).get_form_kwargs(**kwargs)
        form_kwargs["user"] = self.request.user
        return form_kwargs

Upvotes: 7

Related Questions