Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I redirect from view In Django

Tags:

python

django

This is a view written for my posts app in Django. The problem is that after filling the update form and submitting it happens successfully. But it creates confusion for the user because the same HTML page is there and how can I redirect into the updated object?

def post_update(request,id=None):
    instance=get_object_or_404(Post,id=id)
    if instance.created_user != request.user.username :
        messages.success(request, "Post owned by another user, You are having read permission only")
        return render(request,"my_blog/denied.html",{})
    else :  
        form=PostForm(request.POST or None,request.FILES or None,instance=instance)
        if form.is_valid():
            instance=form.save(commit=False)
            instance.save()
        context={ "form":form,
                  "instance":instance }

        return render(request,"my_blog/post_create.html",context)
like image 693
Self Avatar asked Mar 05 '17 21:03

Self


People also ask

How do I link views and urls in Django?

A request in Django first comes to urls.py and then goes to the matching function in views.py. Python functions in views.py take the web request from urls.py and give the web response to templates. It may go to the data access layer in models.py as per the queryset.

What is permanent redirect in Django?

Permanent redirects are for when resource URLs change.


1 Answers

As already suggested by @mdegis you can use the Django redirect function to redirect to another view or url.

from django.shortcuts import redirect

def view_to_redirect_to(request):
    #This could be the view that handles the display of created objects"
    ....
    perform action here
    return render(request, template, context)

def my_view(request):
    ....
    perform form action here
    return redirect(view_to_redirect_to)

Read more about redirect here and here

You can pass positional or keyword argument(s) to the redirect shortcut using the reverse() method and the named url of the view you're redirecting to.

In urls.py

from news import views

url(r'^archive/$', views.archive, name='url_to_redirect_to')

In views.py

from django.urls import reverse

def my_view(request):
    ....
    return redirect(reverse('url_to_redirect_to', kwargs={'args_1':value}))

More about reverse Here

like image 73
Hmatrix Avatar answered Oct 10 '22 11:10

Hmatrix