2013-02-20 22 views
2

我正在使用Userena,我试图捕获URL参数并将它们呈现给我的表单,但我迷失了如何做到这一点。捕获的URL参数形式

我想在我的模板做的是:

<a href="/accounts/signup/freeplan">Free Plan</a><br/> 
<a href="/accounts/signup/proplan">Pro Plan</a><br/> 
<a href="/accounts/signup/enterpriseplan">Enterprise Plan</a><br/> 

然后在我的urls.py

url(r'^accounts/signup/(?P<planslug>.*)/$','userena.views.signup',{'signup_form':SignupFormExtra}), 

然后,理想情况下,我想使用planslug在我forms.py在配置文件中设置用户计划。

我迷失了如何获取捕获的URL参数到自定义窗体中。我可以使用extra_context,是否必须重写Userena注册视图?

回答

1

您可以通过访问网址在你的模板 -

{% request.get_full_path %} 

(见docs更多信息)。

但是,如果你只是想获得planslug变量然后从视图模板传递和访问它在模板(它在视图中可用,因为它是一个命名参数中的URL) -

def signup(request, planslug=None): 
    # 
    render(request, 'your_template.html', {'planslug':planslug} 

,然后在模板中你得到它 -

{% planslug %} 

如果您正在使用基于类的观点,那么你将它传递给模板 - 之前,你需要override get_context_dataplanslug变量添加到您的上下文

def get_context_data(self, *args, **kwargs): 
    context = super(get_context_data, self).get_context_data(*args, **kwargs) 
    context['planslug'] = self.kwargs['planslug'] 
    return context 
6

如果您使用基于类的视图,则可以覆盖FormMixin类的def get_form_kwargs()方法。在这里,您可以将您需要的任何参数传递给表单类。

在urls.py

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

在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 

在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 

希望这有助于:-)

+0

而如果你不使用基于类的视图? – 2017-08-27 20:23:22