Created
May 11, 2015 12:13
-
-
Save 0xKD/51f65fc355fb6179d794 to your computer and use it in GitHub Desktop.
Django code snippet that will treat a save button click (when URL has ?_popup=1) as 'Save and continue'. This is useful when you need to save the object before allowing some changes to be made on it
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyAdmin(admin.ModelAdmin): | |
def response_add(self, request, obj, post_url_continue=None): | |
# If object is added in popup, treat as continue | |
if '_popup' in request.POST: | |
opts = obj._meta | |
pk_value = obj._get_pk_val() | |
preserved_filters = self.get_preserved_filters(request) | |
msg_dict = {'name': force_text(opts.verbose_name), 'obj': force_text(obj)} | |
msg = _('The %(name)s "%(obj)s" was added successfully. You may edit it again below.') % msg_dict | |
self.message_user(request, msg, messages.SUCCESS) | |
if post_url_continue is None: | |
post_url_continue = reverse('admin:%s_%s_change' % | |
(opts.app_label, opts.model_name), | |
args=(quote(pk_value),), | |
current_app=self.admin_site.name) | |
post_url_continue = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, post_url_continue) | |
return HttpResponseRedirect(post_url_continue + '?_popup=1') | |
return super(MyAdmin, self).response_add(request, obj, post_url_continue) | |
def response_change(self, request, obj): | |
if '_popup' in request.POST: | |
pk_value = obj._get_pk_val() | |
to_field = request.POST.get('_to_field') | |
if to_field: | |
attr = str(to_field) | |
else: | |
attr = obj._meta.pk.attname | |
value = obj.serializable_value(attr) | |
return SimpleTemplateResponse('admin/popup_response.html', { | |
'pk_value': escape(pk_value), | |
'value': escape(value), | |
'obj': escapejs(obj) | |
}) | |
return super(MyAdmin, self).response_change(request, obj) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment