Trewq
Trewq

Reputation: 3237

How to redirect correctly using reverse url

I have need to redirect a successful submission to a specific page.

urlpatterns = patterns('',
url(r'create/$', RestaurantCreate.as_view(), name='restaurant_create'),
url(r'preview/$', RestaurantPreview.as_view(), name='restaurant_preview'),

)

Once the restaurant is created, I'd like to redirect it to the preview page to this url (assume slug was 'applebees') like so:

http://127.0.0.1/restaurant/applebees/preview

Here is my RestaurantCreate class:

class RestaurantCreate(CreateView):    
form_class = RestaurantForm
template_name = 'restaurant_form.html'
success_url = 'success'
model = Restaurant

def form_valid(self, form):
    obj = form.save(commit=False)
    obj.slug = unique_slug(obj.name, Restaurant)
    obj.created_by = self.request.user
    obj.save()
    return HttpResponseRedirect('/')

I need to change the last line of the code above. Now, I can hack it to append some strings and redirect, but how do I do this the right way (using named url or reverse url?). Any ideas on how to do redirect correctly?

Upvotes: 0

Views: 209

Answers (1)

Rod Xavier
Rod Xavier

Reputation: 4043

Your URLconf should be like this

urlpatterns = patterns('',
    url(r'^create/$', RestaurantCreate.as_view(), name='restaurant_create'),
    url(r'^(?P<slug>[-\w]+)/preview/$', RestaurantPreview.as_view(), name='restaurant_preview'),
)

And you can use django.shortcuts.redirect

from django.shortcuts import redirect
def form_valid(self, form):
    obj = form.save(commit=False)
    obj.slug = unique_slug(obj.name, Restaurant)
    obj.created_by = self.request.user
    obj.save()
    return redirect('restaurant_preview', slug=obj.slug)

Upvotes: 1

Related Questions