Alfons Ingomar Alfons Ingomar - 2 months ago 9
Python Question

Use url parameter in class based view Django

I have a view (CreateWorkRelationView) that makes use of the CreateView CBV. In the URL, a parameter is passed (user) that I need to refer to a lot. Is it possible to set the object user outside the functions in my class? So are you able to access kwargs from outside a function?

So I basically just want to add the following line to my class

user = get_object_or_404(Contact.pk=kwargs['user'])


At the moment however, that returns


NameError: name 'kwargs' is not defined


This is my class

class CreateWorkRelationView(LoginRequiredMixin, SuccessMessageMixin, CreateView):
template_name = 'groups/group_form.html'
form_class = WorkRelationForm
model = WorkRelation
title = "Add a work relation"
success_message = "Workrelation was successfully created."


def form_valid(self, form):
user = get_object_or_404(Contact, pk=self.kwargs['user'])
form.instance.contact = user
return super(CreateWorkRelationView, self).form_valid(form)

def get_success_url(self):
return reverse_lazy('contacts:contact_detail', self.kwargs['user'])


The reason why I would like to do this, is:


  1. I want to use this object in my title string.

  2. I am going to add a couple of more functions, and they all need this object.


Answer

No, that can't possibly work; you don't have a user, or kwargs, or even a request at the time the class is defined. You need to do this inside one of the methods called at request time; probably get_context_data or get_object.