Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding a `next` url to django admin change link

In my django project I create a link to the admin interface so that users can edit the object:

<a href="{% url admin:mode_change object.id %}">modify object</a>

this works fine, but after the user finished editing the object in the admin interface, I would love to automatically bring the user back to the original URL (or some other URL). Currently, after the user modified the object, she / he ends up in the admin interface looking at all model entries.

Is there a way to provide a return url to an admin link?

like image 833
memyself Avatar asked Sep 05 '12 11:09

memyself


2 Answers

this seems to work:

admin.py:
class ModelAdmin(admin.ModelAdmin):
    form = ModelForm

    def response_change(self, request, obj):
        res = super(ModelAdmin, self).response_change(request, obj)
        if "next" in request.GET:
            return HttpResponseRedirect(request.GET['next'])
        else:
            return res

and in the template (where currentUrl is a variable generated in the view):

<a href="{% url admin:mode_change object.id %}?next={{ currentUrl }}">modify object</a>
like image 194
memyself Avatar answered Nov 10 '22 00:11

memyself


The method "response_post_save_change" would be better for this question, because it is called only after successful save. On Django 3.1 this worked for me:

def response_post_save_change(self, request, obj):
    res = super().response_post_save_change(request, obj)
    if "next" in request.GET:
        return HttpResponseRedirect(reverse(...))
    else:
        return res
like image 44
limugob Avatar answered Nov 10 '22 00:11

limugob