Captured URL parameters in form

前端 未结 2 788
一整个雨季
一整个雨季 2021-01-15 01:09

I am using Userena and I am trying to capture URL parameters and get them to my form but I\'m lost how to do this.

What I would like to do in my template is:

2条回答
  •  广开言路
    2021-01-15 02:08

    If you use class based views, you can overwrite the def get_form_kwargs() method of the FormMixin class. Here you can pass any parameters you need to your form class.

    in urls.py:

    url(r'^create/something/(?P.*)/$', MyCreateView.as_view(), name='my_create_view'),
    

    in views.py:

    class MyCreateView(CreateView):
        form_class = MyForm
        model = MyModel
    
        def get_form_kwargs(self):
            kwargs = super( MyCreateView, self).get_form_kwargs()
            # update the kwargs for the form init method with yours
            kwargs.update(self.kwargs)  # self.kwargs contains all url conf params
            return kwargs
    

    in forms.py:

    class MyForm(forms.ModelForm):
    
        def __init__(self, foo=None, *args, **kwargs)
            # we explicit define the foo keyword argument, cause otherwise kwargs will 
            # contain it and passes it on to the super class, who fails cause it's not
            # aware of a foo keyword argument.
            super(MyForm, self).__init__(*args, **kwargs)
            print foo  # prints the value of the foo url conf param
    

    hope this helps :-)

提交回复
热议问题