2013-02-20 25 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