Reputation: 3915
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:
Upvotes: 1
Views: 2227
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
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