Django remember me doesn't work - django

I want, to close session when browser is closed, but if user checked remember me, session must be open after browser close, so i did this one but it doesn't work, it always closes.
my settings.py:
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
my views.py
if request.POST['rememberme']:
settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = False

views.py
from django.contrib.auth import views as auth_views
def login_user(request, template_name='registration/login.html', extra_context=None):
response = auth_views.login(request, template_name)
if request.POST.has_key('remember_me'):
request.session.set_expiry(1209600) # 2 weeks
urls.py
urlpatterns = [
url(r'^login/$', login_user, name='auth_login'),
]

Related

Redirect all page not found to home page

I would like to redirect all 404 pages to a home page. I try this but it don't work
app/views.py
from django.http import HttpResponse
from django.shortcuts import render, redirect
def home(request): return HttpResponse('<h1> HOME </h1>')
def redirectPNF(request, exception): return redirect('home')
app/urls.py
from . import views
urlpatterns = [ path('home', views.home, name="home"), ]
app/settings.py
handler404 = 'app.views.redirectPNF'
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']
DEBUG = False
Just Add this line in urls.py instead of settings.py
Everything else seems ok.
It is also mentioned in the django documentation that setting handler variables from anywhere else will have no effect. It has to be set from URLconf
The default error views in Django should suffice for most web applications, but can easily be overridden if you need any custom behavior. Specify the handlers as seen below in your URLconf (setting them anywhere else will have no effect).
app/urls.py
from . import views
handler404 = 'app.views.redirectPNF' # Added this line in URLconf instead of settings.py
urlpatterns = [ path('home', views.home, name="home"), ]

how can I prevent user to go to login page after successful authentication?

I am adding settings.py, root url and views.py. After login user is redirected to respective dashboard. In this situation, if user is pressing back button or changing url to accounts/login, then also it should remain on the dashboard page only. I am using django-registration-redux
settings.py
REGISTRATION_OPEN = True
ACCOUNT_ACTIVATION_DAYS = 7
REGISTRATION_AUTO_LOGIN = False
REGISTRATION_FORM = 'signin.forms.MyRegForm'
LOGIN_REDIRECT_URL = '/signin/user_sign/'
views.py
def user_sign(request):
obj = UserSelection.objects.get(user=request.user)
if obj.user_type == 'candidate':
return redirect('candidate:cand_dash')
else:
return redirect('employer:employer_dash')
urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from signin.regbackend import MyRegistrationView
from django.contrib.auth import views as auth_views
urlpatterns = [
url(r'^$', auth_views.LoginView.as_view(template_name='registration/login.html'), name='home'),
url(r'^accounts/register/$', MyRegistrationView.as_view(), name='registration_register'),
url(r'^accounts/', include('registration.backends.default.urls')),
url(r'^candidate/', include('candidate.urls')),
url(r'^employer/', include('employer.urls')),
url(r'^signin/', include('signin.urls')),
]
You could use a Boolean variable authenticated.
Then you should need to set it as False before the user Authentication.
def registration(request):
authenticated = False
...
Then after the user's authentication just change the var as authenticated = True
Finally every time you need to know if user is authenticated just use if user.authenticated
Also, if you need to use authenticated a lot take a look at custom decorators (https://docs.djangoproject.com/en/2.0/topics/http/decorators/) maybe they could help you.

Django login url

How to enable redirect user after login at personal page included user.id, like http://mysite/client/12. I added app client.
urls.py
from django.conf.urls import url
from . import views
app_name = 'client'
urlpatterns = [
url(r'^(?P<user_id>\d+)/$', views.user_profile, name='user_profile'),
]
views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
#login_required
def user_profile(request,user_id):
user_id = request.user.id
return render(request, 'client/profile.html')
And changed in settings.py
LOGIN_REDIRECT_URL = 'client:user_profile request.user.id'
Now when I click LogIn I get error
Unsafe redirect to URL with protocol 'client'
I think that I am not trying to solve this problem correctly.
LOGIN_REDIRECT_URL should be a URL, e.g. LOGIN_REDIRECT_URL = '/accounts/profile/'
Check the docs here
Because you're doing 'client:user_profile request.user.id' it looks like the system is trying to determine client as a protocol like http or https.

Django is not showing the right path when clicking on a link

This is what it shows when you click on the link
Page not found (404)
Request Method: GET Request URL:
http://localhost:8000/jobapplication/new/1
Using the URLconf defined in careal.urls, Django tried these URL
patterns, in this order:
^$ [name='landing-index']
^admin/
^accounts/
^taskmanager/
^login/$ [name='login']
The problem is that I don't know why it is opening the link as http://localhost:8000/jobapplication/new/1, when it should be http://localhost:8000/taskmanager/jobapplication/new/1
This is what I have in the urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.contrib.auth import views as auth_views
from landingpage import views as landingpage_views
urlpatterns = [
url(r'^$', landingpage_views.index, name='landing-index'),
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('allauth.urls')),
url(r'^taskmanager/', include('taskmanager.urls')),
url(r'^login/$', auth_views.login, name='login'),
]
This is in urls.py in the app taskmanager
from django.conf.urls import url
from . import views
from taskmanager.views import *
app_name = 'taskmanager'
urlpatterns = [
# Task manager urls
url(r'^$', JobApplicationIndex.as_view(), name='index'),
url(r'jobapplication/add/(?P<jobpost_id>[0-9]+)/$', JobApplicationCreate.as_view(), name='jobapplication-add'),
url(r'jobapplication/new/(?P<jobpost_id>[0-9]+)/$', views.JobApplicationAdd, name='jobapplication-new'),
url(r'jobapplication/edit/(?P<jobpost_id>[0-9]+)/$', views.JobApplicationEdit, name='jobapplication-edit'),
url(r'jobapplication/edit/(?P<pk>[0-9]+)/$', JobApplicationUpdate.as_view(), name='jobapplication-edit'),
url(r'^jobapplication/(?P<pk>[0-9]+)/$', JobApplicationDetails.as_view(), name='jobapplication-detail'),
# Company urls
url(r'company/$', CompanyIndex.as_view(), name='company-index'),
url(r'company/add/$', CompanyCreate.as_view(), name='company-add'),
url(r'^company/(?P<pk>[0-9]+)/$', CompanyDetails.as_view(), name='company-detail'),
# Job Post urls
url(r'jobpost/$', JobPostIndex.as_view(), name='jobpost-index'),
url(r'^jobpost/(?P<pk>[0-9]+)/$', JobPostDetails.as_view(), name='jobpost-detail'),
# Statistics urls
url(r'^kpi/$', views.kpi, name='kpi'),
]
And this is what I have in views.py in taskmanager, related to jobapplication
# Job Application views
class JobApplicationIndex(generic.ListView):
template_name = 'taskmanager/jobapplication_index.html'
def get_queryset(self):
if self.request.user.is_authenticated:
return JobApplication.objects.filter(user=self.request.user.id).order_by('-created_at')
class JobApplicationCreate(CreateView):
model = JobApplication
fields = ['jobpost', 'sent_date', 'deadline', 'success_rate']
def get_initial(self):
jobpost = get_object_or_404(JobPost, id=self.kwargs.get('jobpost_id'))
return {
'jobpost':jobpost,
}
def form_valid(self, form):
form.instance.user = self.request.user
return super(JobApplicationCreate, self).form_valid(form)
class JobApplicationDetails(generic.DetailView):
model = JobApplication
class JobApplicationEdit(UpdateView):
model = JobApplication
#fields = ['jobpostid', 'is_favorite']
#p = JobApplication.objects.get(id=jobpostid)
#p.is_favorite = is_favorite
#p.save()
class JobApplicationUpdate(UpdateView):
model = JobApplication
fields = ['sent_date', 'deadline', 'success_rate']
template_name_suffix = '_update_form'
def JobApplicationAdd(request, jobpost_id):
if request.method == 'GET' and request.user.is_authenticated:
# If job app for this id exists, redirect to that job app page with a message
if JobApplication.objects.filter(jobpost_id=int(jobpost_id)).exists():
existing = JobApplication.objects.get(jobpost_id=int(jobpost_id))
messages.add_message(request, messages.INFO, 'An application for this opening already exists.')
return HttpResponseRedirect(reverse('taskmanager:jobapplication-detail', args=[existing.id]))
jobapp = JobApplication(user=request.user, jobpost_id=int(jobpost_id), success_rate=50)
jobapp.save()
return HttpResponseRedirect(reverse('taskmanager:index'))
--- The thing is all the other links in taskmanager work and when you click on them, the right path is opened Eg: -
- http://localhost:8000/taskmanager/jobpost/
- http://localhost:8000/taskmanager/jobpost/2/
- http://localhost:8000/taskmanager/company/2/
- http://localhost:8000/taskmanager/kpi/
Try Adding an uptick in front of the regex patterns like you did for the ones that are working.
from django.conf.urls import url
from . import views
from taskmanager.views import *
app_name = 'taskmanager'
urlpatterns = [
# Task manager urls
url(r'^$', JobApplicationIndex.as_view(), name='index'),
url(r'^jobapplication/add/(?P<jobpost_id>[0-9]+)/$', JobApplicationCreate.as_view(), name='jobapplication-add'),
url(r'^jobapplication/new/(?P<jobpost_id>[0-9]+)/$', views.JobApplicationAdd, name='jobapplication-new'),
url(r'^jobapplication/edit/(?P<jobpost_id>[0-9]+)/$', views.JobApplicationEdit, name='jobapplication-edit'),
url(r'^jobapplication/edit/(?P<pk>[0-9]+)/$', JobApplicationUpdate.as_view(), name='jobapplication-edit'),
url(r'^jobapplication/(?P<pk>[0-9]+)/$', JobApplicationDetails.as_view(), name='jobapplication-detail'),
# Company urls
url(r'^company/$', CompanyIndex.as_view(), name='company-index'),
url(r'^company/add/$', CompanyCreate.as_view(), name='company-add'),
url(r'^company/(?P<pk>[0-9]+)/$', CompanyDetails.as_view(), name='company-detail'),
# Job Post urls
url(r'^jobpost/$', JobPostIndex.as_view(), name='jobpost-index'),
url(r'^jobpost/(?P<pk>[0-9]+)/$', JobPostDetails.as_view(), name='jobpost-detail'),
# Statistics urls
url(r'^kpi/$', views.kpi, name='kpi'),
]

Django: Redirect logged in users from login page

I want to set up my site so that if a user hits the /login page and they are already logged in, it will redirect them to the homepage. If they are not logged in then it will display normally. How can I do this since the login code is built into Django?
I'm assuming you're currently using the built-in login view, with
(r'^accounts/login/$', 'django.contrib.auth.views.login'),
or something similar in your urls.
You can write your own login view that wraps the default one. It will check if the user is already logged in (through is_authenticated attribute official documentation) and redirect if he is, and use the default view otherwise.
something like:
from django.contrib.auth.views import login
def custom_login(request):
if request.user.is_authenticated:
return HttpResponseRedirect(...)
else:
return login(request)
and of course change your urls accordingly:
(r'^accounts/login/$', custom_login),
The Django 1.10 way
For Django 1.10, released in August 2016, a new parameter named redirect_authenticated_user was added to the login() function based view present in django.contrib.auth [1].
Example
Suppose we have a Django application with a file named views.py and another file named urls.py. The urls.py file will contain some Python code like this:
#
# Django 1.10 way
#
from django.contrib.auth import views as auth_views
from . import views as app_views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^login/', auth_views.login, name='login',
kwargs={'redirect_authenticated_user': True}),
url(r'^dashboard/', app_views.Dashboard.as_view(), name='dashboard'),
url(r'^$', TemplateView.as_view(template_name='index.html'), name='index'),
]
From that file, the relevant part within the urlpatterns variable definition is the following, which uses the already mentioned redirect_authenticated_user parameter with a True value:
url(r'^login/', auth_views.login, name='login',
kwargs={'redirect_authenticated_user': True}),
Take note that the default value of the redirect_authenticated_user parameter is False.
The Django 1.11 way
For Django 1.11, released in April 2017, the LoginView class based view superseded the login() function based view [2], which gives you two options to choose from:
Use the same Django 1.10 way just described before, which is a positive thing because your current code will continue working fine. If you tell Python interpreter to display warnings, by for example running in a console terminal the command python -Wd manage.py runserver in your Django project directory and then going with a web browser to your login page, you would see in that same console terminal a warning message like this:
/usr/local/lib/python3.6/site-packages/django/contrib/auth/views.py:54:
RemovedInDjango21Warning: The login() view is superseded by the
class-based LoginView().
Use the new Django 1.11 way, which will make your code more modern and compatible with future Django releases. With this option, the example given before will now look like the following one:
Example
We again suppose that we have a Django application with a file named views.py and another file named urls.py. The urls.py file will contain some Python code like this:
#
# Django 1.11 way
#
from django.contrib.auth import views as auth_views
from . import views as app_views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^login/',
auth_views.LoginView.as_view(redirect_authenticated_user=True),
name='login'),
url(r'^dashboard/', app_views.Dashboard.as_view(), name='dashboard'),
url(r'^$', TemplateView.as_view(template_name='index.html'), name='index'),
]
From that file, the relevant part within the urlpatterns variable definition is the following, which again uses the already mentioned redirect_authenticated_user parameter with a True value, but passing it as an argument to the as_view method of the LoginView class:
url(r'^login/',
auth_views.LoginView.as_view(redirect_authenticated_user=False),
name='login'),
Take note that here the default value of the redirect_authenticated_user parameter is also False.
References
[1] Relevant section in Django 1.10 release notes at https://docs.djangoproject.com/en/dev/releases/1.10/#django-contrib-auth
[2] Relevant section in Django 1.11 release notes at https://docs.djangoproject.com/en/1.11/releases/1.11/#django-contrib-auth
anonymous_required decorator
For class based views
Code:
from django.shortcuts import redirect
def anonymous_required(func):
def as_view(request, *args, **kwargs):
redirect_to = kwargs.get('next', settings.LOGIN_REDIRECT_URL )
if request.user.is_authenticated():
return redirect(redirect_to)
response = func(request, *args, **kwargs)
return response
return as_view
Usage:
url(r'^/?$',
anonymous_required(auth_views.login),
),
url(r'^register/?$',
anonymous_required(RegistrationView.as_view()),
name='auth.views.register'
),
# Could be used to decorate the dispatch function of the view instead of the url
For view functions
From http://blog.motane.lu/2010/01/06/django-anonymous_required-decorator/
Code:
from django.http import HttpResponseRedirect
def anonymous_required( view_function, redirect_to = None ):
return AnonymousRequired( view_function, redirect_to )
class AnonymousRequired( object ):
def __init__( self, view_function, redirect_to ):
if redirect_to is None:
from django.conf import settings
redirect_to = settings.LOGIN_REDIRECT_URL
self.view_function = view_function
self.redirect_to = redirect_to
def __call__( self, request, *args, **kwargs ):
if request.user is not None and request.user.is_authenticated():
return HttpResponseRedirect( self.redirect_to )
return self.view_function( request, *args, **kwargs )
Usage:
#anonymous_required
def my_view( request ):
return render_to_response( 'my-view.html' )
For Django 2.x, in your urls.py:
from django.contrib.auth import views as auth_views
from django.urls import path
urlpatterns = [
path('login/', auth_views.LoginView.as_view(redirect_authenticated_user=True), name='login'),
]
Add this decorator above your login view to redirect to /home if a user is already logged in
#user_passes_test(lambda user: not user.username, login_url='/home', redirect_field_name=None)
and don't forget to import the decorator
from django.contrib.auth.decorators import user_passes_test
Since class based views (CBVs) is on the rise. This approach will help you redirect to another url when accessing view for non authenticated users only.
In my example the sign-up page overriding the dispatch() method.
class Signup(CreateView):
template_name = 'sign-up.html'
def dispatch(self, *args, **kwargs):
if self.request.user.is_authenticated:
return redirect('path/to/desired/url')
return super().dispatch(*args, **kwargs)
Cheers!
https://docs.djangoproject.com/en/3.1/topics/auth/default/#all-authentication-views
Add the redirect route in settings
LOGIN_URL = 'login'
And in the URLs add redirect_authenticated_user=True to LoginView
path('login/', auth_views.LoginView.as_view(template_name='users/login.html',redirect_authenticated_user=True), name='login')
I know this is a pretty old question, but I'll add my technique in case anyone else needs it:
myproject/myapp/views/misc.py
from django.contrib.auth.views import login as contrib_login, logout as contrib_logout
from django.shortcuts import redirect
from django.conf import settings
def login(request, **kwargs):
if request.user.is_authenticated():
return redirect(settings.LOGIN_REDIRECT_URL)
else:
return contrib_login(request, **kwargs)
logout = contrib_logout
myproject/myapp/urls.py
from django.conf.urls import patterns, url
urlpatterns = patterns('myapp.views.misc',
url(r'^login/$', 'login', {'template_name': 'myapp/login.html'}, name='login'),
url(r'^logout/$', 'logout', {'template_name': 'myapp/logout.html'}, name='logout'),
)
...
Assuming that you are done setting up built-in Django user authentication (and using decorators), add this in your settings.py:
LOGIN_REDIRECT_URL = '/welcome/'
NOTE: '/welcome/' here is the URL of the homepage. It is up to you what to replace it with.
All you have to do is set the "root" url to the homepage view. Since the homepage view is already restricted for logged on users, it'll automatically redirect anonymous users to the login page.
Kepp the url as it is.
And add something like:
(r'^$', 'my_project.my_app.views.homepage'),