我正在使用Userena,我正在尝试捕获网址参数并将其转到我的表单中,但我失去了如何执行此操作。
我想在模板中做的是:
<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}),
然后,理想情况下,我想在forms.py中使用该计划程序在配置文件中设置用户计划。
我失去了如何将捕获的URL参数放入自定义表单中。我可以使用extra_context,是否必须覆盖Userena注册视图?
答案 0 :(得分:7)
如果使用基于类的视图,则可以覆盖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
form.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
希望这会有所帮助: - )
答案 1 :(得分:1)
您可以使用 -
访问模板中的网址{% request.get_full_path %}
(有关详情,请参阅docs)。
但是,如果您只想获取planslug
变量,则将其从视图传递到模板并在模板中访问它(它在视图中可用,因为它是URL中的命名参数) -
def signup(request, planslug=None):
#
render(request, 'your_template.html', {'planslug':planslug}
然后在你的模板中,你得到它 -
{% planslug %}
如果您使用的是基于类的视图,那么在将planslug
变量传递给模板之前,您需要override get_context_data添加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
变量 -
{{1}}