How to set success url as the previous page after updating an instance in django

Viewed 1381

I am trying to redirect the user to the previous page after they have updated an instance in the Model Class. So, here is the view for the update:

class ClassStatusDetailView(OrganisorAndLoginRequiredMixin, generic.UpdateView):
    model = Class
    template_name = "agents/class_status_detail.html"
    context_object_name = "class"
    fields = ['status']

    def get_success_url(self):
        return reverse("agents:agent-list")

Right now, as you can see, the get_success_url is set to "agents:agent-list", which is not the previous page. Also, here is the template for the update view in case you need it:

{% extends "base.html" %}
{% load tailwind_filters %}

{% block content %}

<div class="max-w-lg mx-auto">
    <a class="hover:text-blue-500" href="#">Something</a>
    <div class="py-5 border-t border-gray-200">
        <h1 class="text-4xl text-gray-800">{{ class.student }}</h1>
    </div>
    <form method="post" class="mt-5">
        {% csrf_token %}
        {{ form|crispy }}
        <button type='submit' class="w-full text-white bg-blue-500 hover:bg-blue-600 px-3 py-2 rounded-md">
            Update
        </button>
    </form>
</div>
{% endblock content %}

However, there is a catch. The previous page I want to return to is a function view with a primary key. So, not only do I have to go back to this function view, but I also have to go to the correct primary key. Please tell me if you guys need any other information. Thank you!

1 Answers

When user successfully update their data then he/she redirect to class_list.html page..

urls.py(I assume):

 path('class_list/<int:pk>/', class_list,name = 'class_list'),
 path('edit_class/<int:pk>/', ClassStatusDetailView.as_view(),name = 'edit_class')

models.py:

    class ClassStatusDetailView(OrganisorAndLoginRequiredMixin, generic.UpdateView):
            model = Class
            template_name = "agents/class_status_detail.html"
            context_object_name = "class"
            fields = ['status']
        
            def get_success_url(self):
                agent_id = self.object.teacher.id
                return reverse_lazy('class_list', kwargs={'pk': agent_id})

Use reverse_lazy

Related