clicking a link cause running a view - python

I have a view for logout,now I wanna when user click on an anchor link the logout view run,how can I do this?
in views.py:
def logout(request):
auth.logout(request)
return render_to_response("airAgency/index.html")

I'm new in django,I can submit a form and run a view for that, but I
don't now what should I do to run s.th like logout view when clicking
an anchor link.
Logging out via a link instead of a form is easy.
https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.logout
from django.contrib.auth import logout
def logout_view(request):
logout(request)
return http.HttpResponse("You've been logged out")
Just point a url to this view like you did with your form and go to that URL.

Related

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

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.

How to block user from opening pages if user is not logged in

I have login and work page.
I want user to login first and then redirect to work page. This scenario is working fine for me.
However when I try hitting the work page it is giving me error, I am checking it through session variable which I know I am doing it wrong as I am not sure which user is trying to access the page if user tries to hit the work page directly as there will be many users in database. How can I restrict user to hit the work page directly and if user does it should redirect to login page
views.py file method is as follows:-
def chatbox_index(request):
context={}
template_name = "bot/chatbot.html"
**<I have to check here if user session is active or not?>**
return render(request, template_name,context=context)
else:
return render(request,'' ,context=context)
after user login I am creating session and storing in below 2 variables:-
request.session['employee_name'] = employee.usrFirstName
request.session['employee_id'] = employee.id
Django provides login_required decorator for this:
from django.contrib.auth.decorators import login_required
#login_required
def chatbox_index(request):
context={}
template_name = "bot/chatbot.html"
return render(request, template_name,context=context)

reverse function does not change the url to request a different view, django

I have a form that a user fills and then clicks a button to submit, then it calls a transition page, to inform the user that the form was completed. The user can click a button to go back to the home page from the transition page.
I want to get rid of the transition page and go to the home page directly. The reverse function does not change the URL but renders the correct homepage template. However, the context data in the template does not get populated and I am assuming that the URL not changing causes that.
The homepage urls.py I include:
url(r'^(?P<user_id>\d+)/$', views.UserHomePageView.as_view() ,
name='user-homepage'),
Example: the form URL is
localhost:8000/form/15/fill
After the form is submitted, I want it to redirect to
localhost:8000/home/3
from the view after form submission, I call
return HttpResponseRedirect(reverse('homepage:user-homepage', args=[userid]))
try this:
return redirect('home')

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 to Call default home url in django when i logged out

Please visit this link for getting whole idea behind this question
How to Call loggedin username in Django url
Here i have discussed my points in this link but i didnt got specific answer for my issue that , when user loggedin i wanted it to be displayed in my url as
" 127.0.0.1:8000/username " as i got the solution in above link as create user defind HomeRedirectView which calls initially when user logsin. and it works successfully, but i got an issue when i logged out and revisit the url as " 127.0.0.1:8000/ " then this url automatically becomes " 127.0.0.1:8000/AnonymousUser " and am getting the error as "NoReverseMatch", for that i have to specifically write it into url as " 127.0.0.1:8000/home/ " then it works. So can any one suggest me how to make url as " 127.0.0.1:8000/home/ ". To know about what i have done uptill now ,please visit above link and you will come to know from the discussion.
Please suggest.
The solution you got there is not the right solution, the right solution is to use the LOGIN_REDIRECT_URL setting and point it to a view function, a named URL pattern or a direct URL.
Once a user is logged in using the default authentication mechanism of django, the request will automatically be redirected to this page.
Your second problem is when you logout a user, you want to be redirected to a specific URL. If you use the correct solution above, then all you need to do is:
Set LOGOUT_URL in your settings.py.
Create your logout view, it can be as simple as this example from the documentation:
from django.shortcuts import redirect
from django.contrib.auth import logout
def logout_view(request):
logout(request)
return redirect('/home/')
If you want to stick with your original solution, then modify it like this:
class HomeRedirectView(RedirectView):
pattern_name = 'home'
def get_redirect_url(self, *args, **kwargs):
if self.request.user.is_authenticated():
return "/user/{}/".format(self.request.user)
else:
return '/home/'
I think you are overcomplicating things a little, the following will allow you to redirect to a user home page if a user is logged in, or it will display an un-logged in view. I have made the assumption that the username in the URL is purely for display purposes (otherwise it could be a security issue for your application.
urls.py
urlpatterns = patterns('myapp.views',
url(r'^/$', 'home', name='home'),
url(r'^user/[-_.\w\d]+/$', 'user_home', name='user-home'),
)
views.py
from django.contrib.auth.models import User
from django.shortcuts import redirect, render, get_object_or_404
def home(request):
"""
Home page
"""
# If a user is authenticated then redirect them to the user page
if request.user.is_authenticated:
return redirect('user-home', request.user.username)
else:
return render(request, "myapp/home.html")
#login_required
def user_home(request):
"""
User specific home page, assume the username in URL is just for decoration.
"""
return render(request, "mpapp/home_user.html", {
"user": request.user
}

Categories