Reputation: 1056
I'm learning Django and I'm struggling with the Class Based View of Django.
I would like to access the object attributes before the update in order to show the user what was the previous attributes.
Here my class view :
class GroupUpdateView(LoginRequiredMixin, UpdateView):
model = GroupName
fields = ['name', 'description']
template_name = 'dashboard/groups/group_update_form.html'
group_name_before_editing ="" #I wanted to write model.name here
#Overrive
def form_valid(self, form):
return super().form_valid(form)
def get_success_url(self):
messages.success(self.request, "The group %s was updated successfully" % (
self.group_name_before_editing))
return reverse_lazy('dashboard:group-update', args=(self.object.pk,))
In get_success_url()
, I would like to show the user the previous name of the group that has been updated.
I tried also with the get_context_data()
but was not able to obtain the result.
Could you help please ? How to get the current model attributes ?
Upvotes: 0
Views: 194
Reputation: 309089
class GroupUpdateView(LoginRequiredMixin, UpdateView):
...
group_name_before_editing ="" #I wanted to write model.name here
You can't put the code there, because it runs when the server starts and loads the module. You need to put the code inside a method that runs when Django handles the request.
I would suggest overriding the get_object
method and setting the value at that point.
class GroupUpdateView(LoginRequiredMixin, UpdateView):
def get_object(self, queryset=None):
obj = super().get_object(queryset)
self.group_name_before_editing = obj.name
return obj
Upvotes: 1