我正在使用 Userena,我正在 try catch 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}),
然后,理想情况下,我想在我的 forms.py 中使用那个 planslug 来在配置文件中设置用户计划。
我不知道如何将捕获的 URL 参数放入自定义表单中。我可以使用 extra_context,我是否必须覆盖 Userena 注册 View ?
最佳答案
如果您使用基于类的 View ,您可以覆盖 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
在表单.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
希望这有帮助:-)
关于django - 表单中捕获的 URL 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14990659/