chriss
chriss

Reputation: 4449

how to pass id from url to post_save_redirect in urls.py

I have several objects in the database. Url to edit an object using the generic view looks like site.com/cases/edit/123/ where 123 is an id of the particular object. Consider the cases/url.py contents:

url(r'edit/(?P<object_id>\d{1,5})/$', update_object, { ... 'post_save_redirect': ???}, name = 'cases_edit'),

where update_object is a generic view. How to construct the post_save_redirect to point to site.com/cases/edit/123/. My problem is, that I don't know how to pass the id of the object to redirect function. I tried something like:

'post_save_redirect': 'edit/(?P<object_id>\d{1,5})/'
'post_save_redirect': 'edit/' + str(object_id) + '/'

but obviously none of these work. reverse function was suggested, but how to pass the particular id?

'post_save_redirect': reverse('cases_edit', kwargs = {'object_id': ???})

{% url %} in the temple also requires passing the id of the particular object. The id can be passed via extra_context:

extra_context = {'object_id': ???}

In all the cases the problem is to get object_id from the url.

regards
chriss

Upvotes: 0

Views: 2132

Answers (3)

Facundo Casco
Facundo Casco

Reputation: 10585

Right from the docs at: https://docs.djangoproject.com/en/dev/ref/generic-views/#django-views-generic-create-update-create-object

post_save_redirect may contain dictionary string formatting, which will be interpolated against the object's field attributes. For example, you could use post_save_redirect="/polls/%(slug)s/".

Upvotes: 0

Jason Christa
Jason Christa

Reputation: 12508

In short what you need to do is wrap the update_object function.

def update_object_wrapper(request, object_id, *args, **kwargs):
    redirect_to = reverse('your object edit url name', object_id)
    return update_object(request, object_id, post_save_redirect=redirect_to, *args, **kwargs)

Upvotes: 1

S.Lott
S.Lott

Reputation: 391872

First, read up on the reverse function.

Second, read up on the {% url %} tag.

You use the reverse function in a view to generate the expected redirect location.

Also, you should be using the {% url %} tag in your templates.

Upvotes: 0

Related Questions