NOTE: this is for newforms-admin
I need edit links for items on my site, outside of the django admin -- however, I'm lazy, and don't want to build my own edit forms when there's a perfectly nice admin already there.
Trick is, I need to be able to click a link to the django admin edit page for an item, and have it return to the calling page after saving.
This chunk of code does the trick (the "real" version extra cruft, naturally) -- the links will bring up the django admin editor, then return to the calling page after saving.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | ### urls.py:
urlpatterns = patterns('',
(r'^admin/(.*?)/(.*?)/edit/(.*?)/$', 'myproj.myapp.views.admin_edit_callback'),
# note -- the pattern for the overall admin must come after
(r'^admin/(.*)', admin.site.root),
)
### views.py:
from django.contrib import admin
from django.http import HttpResponseRedirect
from django.contrib.admin.views.decorators import staff_member_required
CALLBACK_URL_VAR = 'callback_url'
@staff_member_required
def admin_edit_callback(request, app, model, id):
# GET == the initial request -- save the referer in the session,
# then call admin.site.model_page to render the form
if request.method == 'GET':
request.session[CALLBACK_URL_VAR] = request.META['HTTP_REFERER']
# force it into "popup" mode to hide breadcrumbs, etc
# (since they'll all be aimed at incorrect URLs otherwise)
if '_popup' not in request.GET:
gtmp = request.GET.copy()
gtmp['_popup'] = 1
request.GET = gtmp
return admin.site.model_page(request, app, model, id)
# POST == call model and, if we get a valid HttpResponseRedirect,
# override it with a redirect to the callback URL we saved earlier
elif request.method == 'POST':
response = admin.site.model_page(request, app, model, id)
if isinstance(response, HttpResponseRedirect) and \
CALLBACK_URL_VAR in request.session:
response['Location'] = request.session[CALLBACK_URL_VAR]
del request.session[CALLBACK_URL_VAR]
return response
### my_template.html:
<a href="/admin/foo/bar/edit/12345/">Edit, and return!</a>
<a href="/admin/pages/article/edit/12345">Edit, then come back</a>
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.