Question

I am new to Django and web programming in general, please don't make the answers too complicated. I have looked up the documentation and questions in here but I can't wrap my head around it.

I have a form and after validating and saving the model to the database I want to redirect the user to a new page. My question is, how do I do it with HttpResponseRedirect(or even the shortcut redirect) correctly, because it redirects the view correctly, the url pattern gets called but when it reaches the view in the views.py something goes array. Why doesn't the template change but the view does?

Can somebody tell me where I am wrong, and how to fix it?

views.py

class CreateSuccess(generic.ListView):
    template_name = 'login/successReg.html'

def CreateUser(request):
    if request.method == "POST":
        form = CreateUserForm(request.POST)
        if form.is_valid():
            newUser = form.save()

            return HttpResponseRedirect('sucess/')
    else:
        form = CreateUserForm()

    return render(request, 'login/addUser.html', {'form':form})

urls.py

    urlpatterns = patterns('',
    url(r'^$', views.LoginIndex.as_view(), name='loginIndex'),
    url(r'^create/', views.CreateUser, name='addUser'),
    url(r'^authenticate/', views.LoginUser.as_view(), name='loginUser'),
    url(r'^create/success/', views.CreateSuccess.as_view(), name='successReg'),
)
Was it helpful?

Solution

Try returning an reverse() object which constructs the required url for you

if form.is_valid():
    newUser = form.save()
    url = reverse('your_app:successReg') # Replace your_app with the name of your app
    return HttpResponseRedirect(url)

More about reverse():

reverse(viewname)

  • viewname is either the function name (either a function reference, or the string version of the name) which means that either you could make viewname a existing function in your views.py or either reference it by its string name in the urls.py

It's always recommended to do it in the form reverse('app_name : name_defined_in_urls')

Note: since your a beginner I dropped those optional args and kwargs parameters which are used if you want to redirect a user to dynamic webpage

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top