Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify Django "save and add another" button to set initial value of field based on value of field on object just saved

I have a basic blog app with models Entry and Category. One of the fields in Entry is a ForeignKey to Category. When a user is adding an Entry and chooses to "save and add another', I'd like it if the Category of the new form is set to be equal to the Category of the object that was just saved.

How can I accomplish that?

like image 421
KrisF Avatar asked Dec 28 '12 09:12

KrisF


1 Answers

Figured it out with some help from this question. The trick was to modify response_add and response_change methods of the ModelAdmin

class EntryAdmin(admin.ModelAdmin):
    ...
    def response_add(self, request, obj, post_url_continue=None):
        if request.POST.has_key('_addanother'):
            url = reverse("admin:blog_entry_add")
            category_id = request.POST['category']
            qs = '?category=%s' % category_id
            return HttpResponseRedirect(''.join((url, qs)))
        else:
            return HttpResponseRedirect(reverse("admin:blog_entry_changelist"))

    def response_change(self, request, obj, post_url_continue=None):
        if request.POST.has_key('_addanother'):
            url = reverse("admin:blog_entry_add")
            category_id = request.POST['category']
            qs = '?category=%s' % category_id
            return HttpResponseRedirect(''.join((url, qs)))
        else:
            return HttpResponseRedirect(reverse("admin:blog_entry_changelist"))

For Python 3, replace

if request.POST.has_key('_addanother'):

with

if '_addanother' in request.POST:
like image 97
KrisF Avatar answered Dec 18 '22 02:12

KrisF