5

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?

KrisF
  • 1,371
  • 13
  • 27

1 Answers1

10

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:
xnx
  • 24,509
  • 11
  • 70
  • 109
KrisF
  • 1,371
  • 13
  • 27