v25
v25

Reputation: 7621

Django: setting initial in get_context_data doesn't work as expected

I am trying to set initial within a class based view, to pre-populate a text input with name=description

The following code seems to accept an integer input in the url as specified, and puts this where I want it in the template.

#urls.py
urlpatterns += (
    path('repair/', views.RepairListView.as_view(), name='app_name_repair_list'),
    path('repair/create/<int:pk>', views.RepairCreateView.as_view(), name='app_name_repair_create'),
)

# views.py
class RepairCreateView(CreateView):
    model = Repair
    form_class = RepairForm

    def get_context_data(self, **kwargs):
        context = super(RepairCreateView , self).get_context_data(**kwargs)
        self.initial['description'] = self.kwargs['pk']
return context

However when accessing in the browser...

access: /repair/create/1 text input contains: 1

access: /repair/create/2 text input contains: 1 (again)

access: /repair/create/3 text input contains: 2

(and so forth)

Have I done something blatantly wrong here or is this some kind of weird bug? I'm basically plan to have a URL somewhere else on the site, that the user would click to load this form, thus populating the form with already known information which would be in said URL.

Upvotes: 0

Views: 195

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599490

initial is a class attribute, shared by all instances. You shouldn't modify it.

Instead, you should define the get_initial method, returning a new dictionary:

def get_initial(self):
    return {'description': self.kwargs['pk']}

Upvotes: 2

Related Questions