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?
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With