Django - 从url <pk>填充createview输入

时间:2016-02-23 10:23:58

标签: python django

我正在尝试自动填充我的Createview的隐藏输入。

我的网址格式:

url(r'^user/add/(?P<pk>[0-9]+)/$',', UserCreateView.as_view(), name='user-create'),

我的观点:

class UserCreateView(CreateView):
    model = UserMeta
    fields = [
        'auth', # This is the hidden input that I want to autofill
        'email',
        'city',
    ]
    template_name = 'forms/user_create.html'

问题

我想在我的网址中使用<pk>自动填充“auth”字段,怎么做?

1 个答案:

答案 0 :(得分:2)

您可以从get_initial

覆盖FormMixin
class UserCreateView(CreateView):
    model = UserMeta
    fields = [
        'auth', # This is the hidden input that I want to autofill
        'email',
        'city',
    ]
    template_name = 'forms/user_create.html'

    def get_initial(self):
        return {"auth": self.kwargs.get("pk")}