1

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.
1
  • If you're looking for the logged in user you can use self.request.user but I may be missing something Commented Sep 14, 2016 at 19:35

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Why so long for this answer to get a +1? Thanks, wasted hours until I stumbled on this answer.
2

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.

2 Comments

But am I able to reference tot this context_data in other functions?
If you assign it to an instance attribute, yes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.