How can I make Django user logout without a new url page? - python

For logout I am using ready django.contrib.auth.LogoutView and everyone in their tutorials are creating a new url for example '/logout' and my question is how can I use that view without a new url page and html template? Plese use some code for views.py in your answers ;)

If you don't want any redirects at all and want to stay on the same page, like when you send an AJAX request then you can write your own view like this:
from django.contrib.auth import logout
from django.http import HttpResponse
def logout_view(request):
logout(request)
return HttpResponse('OK')

You don't have to route the /logout url to a template. You can redirect it to whatever page you want by using the next_page attribute (docs).
You can also look into setting a LOGOUT_REDIRECT_URL: https://docs.djangoproject.com/en/3.1/ref/settings/#logout-redirect-url.

Related

django authorization without using request.user.is_authenticated()

I am working on django website and I am using django Auth for user authentication and for authorization of user i am using request.user.is_authenticated() code in django view but using this i have to write this code in each and every view, because in my site there is only homepage, registration page and login page which can be accessed without login. So in each and every view i have to right this code.
def dashboard(request):
if request.user.is_authenticated():
return render(request, 'home/dashboard.py')
else:
return HttpResponse('User is not logged In')
That's why I want to ask is there any way to write code only once for all views those can not be accessed without login as we do in CakePHP using authcomponent.
Yes, just use the login_required decorator or LoginRequiredMixin
from django.contrib.auth.decorators import login_required
#login_required
def dashboard(request):
return render(request, 'home/dashboard.py')
from django.contrib.auth.mixins import LoginRequiredMixin
class MyCBV(LoginRequiredMixin, GenericView):
What this will do is redirect anyone attempting to access the view back to the LOGIN_URL (which can be overridden here) with a next get parameter back to the view, so that they must login before continuing. This isn't the same as what you currently do, but its much friendlier
If your entire website needs to be logged in, then you can use a middleware to make this the default
You can use #login_required instead. See here

How do I redirect visitors to login page?

I have the following url handler in my main Django project urls.py:
url(r'^$', 'core.views.generic.index')
Instead of landing on the index page as above, I want users to land on the login page.
I have another urls.py in an app called core that sends visitors to the login page:
url(r'^/login$', private.MeLogin.as_view())
How can I send all the people visiting url(r'^$', ...) in my main app to private.MeLogin.as_view() in my core app?
EDIT:
I have tried the following,
def index(request):
return HttpResponseRedirect('/#/login')
but I get that this page has a redirect loop
The way to solve that be using a decorator, in this case login_required.
Django documentation
from django.contrib.auth.decorators import login_required
#login_required
def index(request):
index view code in here
What this will do is redirect you to your login view.
As mention in the Documentation
login_required() does the following:
If the user isn’t logged in, redirect to settings.LOGIN_URL, passing the current absolute path in the query string.
If the user is logged in, execute the view normally. The view code is free to assume the user is logged in.
You can also customize your decorator check the documentation for more information.
To login required, you must use a decorator indicating that:
from django.contrib.auth.decorators import login_required
#login_required
def index(request):
return render(request,'home.html')
In any view that the login is required, just use it.

Redefining home in django

I'm working on a Django project in which I plan to make user profiles. My goal is to have a standard login page as seen here. After logging in, however, I want to redefine
url(r'^$', 'MyApp.views.home', name='home'),
to not show this page, but a user profile with the same url as home.
For example, www.example.com shows a login screen. After logging it, you're redirected to www.example.com, but you see your profile now.
How can I do this in Django?
You need simple check in view:
if request.user.is_authenticated():
return HttpResponseRedirect('/profileurl/')
An easy way to do it would be a redirect to another view:
MyApp.views
def home(request):
if request.user.is_authenticated():
redirect
else:
home page
If you want the actual url entry to load a different template than the home page, or a modified home page, you could just as easily render whatever template you wanted in response to the url request instead of issuing a redirect
This is generally how I would go about it. You can add context if needed.
views.py:
from django.shortcuts import render
def home(request):
if request.user.is_authenticated():
return user_home(request)
else:
return login_home(request)
def user_home(request)
return render(request, 'path/to/user_template.html')
def login_home(request)
return render(request, 'path/to/login_template.html')

How can I redirect to a different URL in Django?

I have two pages, one which is to display details for a specific item and another to search for items. Let's say that the urls.py is properly configured for both of them and within views.py for my app, I have:
def item(request, id):
return render(request, 'item.html', data)
def search(request):
#use GET to get query parameters
if len(query)==1:
#here, I want to redirect my request to item, passing in the id
return render(request, 'search.html', data)
What do I do to properly redirect the request? I've tried return item(request, id) and that renders the correct page, but it doesn't change the URL in the address bar. How can I make it actually redirect instead of just rendering my other page? The URL pattern for the item page is /item/{id}. I've looked at the answer to similar questions on SO and the documentation, but still couldn't figure it out.
Edit: I just started learning Python less than a week ago and the other answer isn't clear enough to help me out.
Edit 2: Nvm, not sure what I did wrong before, but it worked when I tried it again.
You can use HttpResponseRedirect:
from django.http import HttpResponseRedirect
# ...
return HttpResponseRedirect('/url/url1/')
Where "url" and "url1" equals the path to the redirect.
Just minute suggestion from the above answer for the change in import statement
from django.http import HttpResponseRedirect
return HttpResponseRedirect('/url-name-here/')
you can try this :
from django.shortcuts import redirect
return redirect(f'/customer/{pk}')

Clear POST in web page

I have a small python/django web site and I'm using a html form POST some information, annoyingly however this information is stored in POST so when a user refreshes in say IE/chrome they get that warning message about the page containing POST data. How do I clear the POST data after it has been processed so a user can refresh and not see this warning message?
Also I have some logic as follows that detects a POST
if request.method == "POST":
do something
Select all
Open in new window
This is fine when I actually post the form, but when I refresh the page it also detects the POST and does the logic that I now dont want to do.
How can I solve this also??
Thanks
After form is validated and it is valid. Then do the redirect to some other page e.g. a success page or redirect to the same view. The redirection will avoid Double Form Submition problem. Read more about it here.
Use HttpResponseRedirect when you return the response for POST request. This is explained in tutorial 4 as
After incrementing the choice count, the code returns an HttpResponseRedirect rather than a normal HttpResponse. HttpResponseRedirect takes a single argument: the URL to which the user will be redirected (see the following point for how we construct the URL in this case).
As the Python comment above points out, you should always return an HttpResponseRedirect after successfully dealing with POST data. This tip isn't specific to Django; it's just good Web development practice.
As Rohan said, you should use HttpResponseRedirect. But also you can use a shortcut:
from django.shortcuts import redirect
def some_view(request):
if request.method == 'POST':
# do smth
return redirect('/page-with-form/')

Categories