【问题标题】:Captured URL parameters in form表单中捕获的 URL 参数
【发布时间】:2013-02-06 02:12:49
【问题描述】:

我正在使用 Userena,我正在尝试捕获 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 注册视图?

【问题讨论】:

    标签: django django-users


    【解决方案1】:

    如果你使用基于类的视图,你可以覆盖 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
    

    希望这会有所帮助:-)

    【讨论】:

    • 如果你不使用基于类的视图?
    【解决方案2】:

    您可以使用 -

    访问模板中的 url
    {% 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-14
      • 1970-01-01
      • 1970-01-01
      • 2012-02-21
      • 2015-12-01
      • 1970-01-01
      • 2014-09-05
      相关资源
      最近更新 更多