How to Call default home url in django when i logged out - python

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
}

Related

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)

request.user.is_authenticated() in django views is always returning false

I am trying Google Oauth2 key,id using django-social-auth to setup a google+ login to my website. I included 2 function defs in views.py, one for index and other profile. So the login is attempted in index and if there is a pass it HttpResponseRedirects to profile page. I am stuck at this point where the login dialog for google+ pops up, i enter the user credentials and it is accepted. However, the index is not redirecting to profile page. In the code below if you see, the request.user.is_authenticated() is always returning false. On printing the request.user i always get AnonymousUser. Please let me know if i am doing anything wrong here or i need to add something to the code.
My views.py currently looks like this.
def index(request):
#print request.user
if request.user.is_authenticated():
print "user is authenticated"
return HttpResponseRedirect('/profile')
return render_to_response('index.html', {}, context_instance=RequestContext(request))
def profile(request):
return render_to_response('profile.html')
The settings file has the following parameters related :
GOOGLE_OAUTH2_CLIENT_ID = <client-id>
GOOGLE_OAUTH2_CLIENT_SECRET = <secret-key>
GOOGLE_OAUTH2_USE_UNIQUE_USER_ID = True
LOGIN_URL = '/'
LOGIN_REDIRECT_URL = '/profile/'
LOGIN_ERROR_URL = '/login-error/'
AUTHENTICATION_BACKENDS = (
'social_auth.backends.google.GoogleOAuthBackend',
'social_auth.backends.google.GoogleOAuth2Backend',
'social_auth.backends.google.GoogleBackend',
'social_auth.backends.OpenIDBackend',
'django.contrib.auth.backends.ModelBackend',
)
I followed this google developer's page in doing this task.
I tried the link w.r.t RequestContext solution and a solution mentioned in similar problem, but both weren't fruitful.

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')

login redirect to another app view

This is my project structure
project
app
login
manage.py
After successful login i want my user will be redirect to localhost:8000/app but currently it will redirect to http://localhost.com:8000/accounts/login/?next=/ because i set it up my login view as
def login_view(request):
if request.POST and form.is_valid():
user = form.login(request)
if user:
login(request, user)
return render_to_response('app/home.html',RequestContext)
else:
return HttpResponse('disabled account')
return render_to_response('login.html', form ,RequestContext)
i can't able to use HttpResponseRedirect(reverse('app.views.dashboard')) because dashboard view not exit in the same login views.py
if i import like
from app import views as app_dashboard or from app import dashboard
i am getting below error
Reverse for 'app.views.dashboard' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
final note, below is my login url currently
Sign in
Added:
app/urls.py
urlpatterns = patterns('app.views',
(r'^$', 'dashboard_view'),
project/urls.py
url(r"^", include("app.urls",)),
(r'^accounts/login/$', 'django.contrib.auth.views.login'),
(r'^accounts/logout/$', 'django.contrib.auth.views.logout', {'next_page' : '/accounts/login'}),
First point: use named urls, cf https://docs.djangoproject.com/en/1.6/topics/http/urls/#naming-url-patterns - this should resolve your reverse problem.
Second point: you show the code for your own login view but your url.py and template's extract both refer to django.contrib.auth.views.login. Also, you specify a next param in your template's url, so django.contrib.auth.views.login do redirect you there, as explained in the FineManual(tm):
If called via POST with user submitted credentials, it tries to log the user in.
If login is successful, the view redirects to the URL specified in next.
(...)
Finally: you don't need to write you own view if all you want is to force the login view to always redirect to a same URL:
(...) If next isn’t provided, it redirects to settings.LOGIN_REDIRECT_URL (which defaults to /accounts/profile/). If login isn’t successful, it redisplays the login form.
IOW:
use named urls everywhere (name your own urls, and use urls names when calling reverse or the {% url %} templatetag)
get rid of the next=... in your templates
set your settings.LOGIN_REDIRECT_URL to your dashboard's url.
def login_view(request):
if request.POST and form.is_valid():
user = form.login(request)
if user:
login(request, user)
return redirect('/app/')
else:
return HttpResponse('disabled account')
return render_to_response('login.html', form ,RequestContext)
Change render response to redirect
give your required url to redirect

Django- why inbuilt auth login function not passing info about user to after successful login url

Hi I used the django inbult auth urls and views for my project and now have finished the initial user account creation/login/reset password process.
Now, the user can log in and be redirected to the after successful login url accounts/profile/.
I have several doubts on the django login function. For convenience, I've copy paste the django inbuilt login function code below.
#sensitive_post_parameters()
#csrf_protect
#never_cache
def login(request, template_name='registration/login.html',
redirect_field_name=REDIRECT_FIELD_NAME,
authentication_form=AuthenticationForm,
current_app=None, extra_context=None):
"""
Displays the login form and handles the login action.
"""
redirect_to = request.REQUEST.get(redirect_field_name, '')
if request.method == "POST":
form = authentication_form(request, data=request.POST)
if form.is_valid():
# Ensure the user-originating redirection url is safe.
if not is_safe_url(url=redirect_to, host=request.get_host()):
redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)
# Okay, security check complete. Log the user in.
auth_login(request, form.get_user())
return HttpResponseRedirect(redirect_to)
else:
form = authentication_form(request)
current_site = get_current_site(request)
context = {
'form': form,
redirect_field_name: redirect_to,
'site': current_site,
'site_name': current_site.name,
}
if extra_context is not None:
context.update(extra_context)
return TemplateResponse(request, template_name, context,
current_app=current_app)
My questions are:
1 Is the REDIRECT_FIELD_NAME in the function set as '/profile/' in django.contrib.auth ?
I could see this variable is imported from django.contrib.auth
from django.contrib.auth import REDIRECT_FIELD_NAME, login as auth_login, logout as auth_logout, get_user_model
I don't have any setting for this variable, but after user successfully logged in, the page will be directed to /accounts/profile/
2 Has the login function passed the account info about the user? If yes, how can I access it?
From the code, if user successfully logged in, page will be redirected: return HttpResponseRedirect(redirect_to)
in my case, redirected to accounts/profile/ , initially the view for the url was simply a
HttpResponse("You have logged in successfully")
now when I am trying to implement the view function, I realize that no info about the user has been passed.
I've tried to print request in the view function, but there is no info about the user in the message printed in the server terminal, all I get is a long list of system settings or other info. However, the login should pass the info of who has just successfully logged in to the successful log in urls right?
Thank you very much for explaining.
After the login, you can access the user info by referring request.user in views and just {{user}} in templates. All you need to make sure is you're passing the RequestContext in the HttpResponse for the future request.
Yes, REDIRECT_FIELD_NAME is defined in __init__.py of django.contrib.auth which is simply a "next" what you passed from the login form.
In Django, there are more than one ways to force a user to login. By decorating a view function with #login_required, by calling the build-in login view for an user defined URL and etc., Refer about the login settings variables here. You'll get some more ideas.
Building custom login page. That link gives you an example for custom login implementaion. Consider you have decorated a view with #login_required and it's corresponding URL is /login_test/. Then the {{next}} context variable in the login form will be rendered with /login_test/. So after you login,
<input type="hidden" name="next" value="{{ next }}" />
This element's value will be taken for redirecting as per the REDIRECT_FIELD_NAME. Though I suspect that that example is missing the setting of settings.LOGIN_URL to the URL login/. Never mind, it's being passed as an argument in the decorator itself.
To override this behavior just put following in settings.py of your app :
LOGIN_REDIRECT_URL = "/"
This will redirect to your home page. You can change this url to preferred url.
Once the user is redirected to accounts/profile/ the view for that link will be returned. You can access information about the currently logged in user there as per this post by using request.user. Also tip to see what information you have access to in your views. Use import pbd; pdb.set_trace(). This pops you into a python prompt with access to all of the current variables. To see all the defined variables call locals(), though this will print out a ton of junk along with it. In the template you can display a "you can't access this page" message if the user isn't logged in.

Categories