django - 表单中捕获的 URL 参数

标签 django django-users

我正在使用 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/

相关文章:

python - Django - 通过排序合并两个查询集

django - 在管理员中显示模型 URL

python - 当 Django `User` 的主键是 `CharField` 时登录时出错

python - Django:向 UserCreationForm 添加其他字段

django - 如何过滤使用扩展模型类字段连接的事件用户

django - 使用 UserPassesTestMixin(基于类的 View )和重定向

带有文件错误的 Django REST Framework POST 数据(使用 ModelResource)

django - 在docker-compose break run中使用network_mode ='host':主机类型网络不能与链接一起使用

django-forms - 以Django形式获取当前用户

python - seetings.py 或 docker 中的数据库配置错误