hY8vVpf3tyR57Xib
hY8vVpf3tyR57Xib

Reputation: 3915

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.

Upvotes: 1

Views: 2227

Answers (2)

Arnaud
Arnaud

Reputation: 101

The way I managed to do this is to use a FormView.

In my urls.py i have

regex=r'^my/path/(?P<pk>\d+)$',

In my views

class MyCreateView(LoginRequiredMixin, FormView):
    def form_valid(self, form):
        data = self.kwargs['pk']

It works well.

Upvotes: 3

Daniel Roseman
Daniel Roseman

Reputation: 600026

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.

Upvotes: 2

Related Questions