Mirko Brombin
Mirko Brombin

Reputation: 1012

Django - fill createview input from url <pk>

I'm trying to autofill a hidden input of my Createview.

My url pattern:

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

My view:

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'

The problem

I want to autofill the 'auth' charfield with the <pk> in my url, how?

Upvotes: 2

Views: 461

Answers (1)

bigblind
bigblind

Reputation: 12867

You can override get_initial from the 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")}

Upvotes: 2

Related Questions