Django login url - django

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.

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"), ]

Hello. I am having a problem to change the pages in my django project that it shows a page not found (404)

I've been building my first Django project, and I was doing the "login page", and it is working, but when then, I've made a condition that if the login is wrong, it comes back to the login page and shows an error message, and if it is right, it should go to a page where is written "logadissimo", but when I try this last one, I get the problem below:
Page not found (404) Request Method: GET Request
URL: http://localhost:8000/ Using the URLconf defined in sitetcc.urls,
Django tried these URL patterns, in this order:
admin/ login/ login/submit login/logado The empty path didn't match
any of these.
You're seeing this error because you have DEBUG = True in your Django
settings file. Change that to False, and Django will display a
standard 404 page.
this is my url.py from the project:
"""
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls.conf import include
from django.urls import path
from core import views
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', views.login_user),
path('login/submit', views.submit_login),
path('login/logado', views.logado)
]
the urls.py from the application:
from . import views
from django.urls import path
app_name = 'core'
urlpatterns = [
path('', views.login_user, name='login'),
path('', views.submit_login, name='submit'),
path('', views.logado, name='logado')
]
the views.py:
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_protect
from django.contrib.auth import authenticate, login
from django.contrib import messages
# Create your views here.
def logado(request):
return render(request, 'logado.html')
def login_user(request):
return render(request,'login.html')
#csrf_protect
def submit_login(request):
if request.POST:
username = request.POST.get('username')
password = request.POST.get('password')
print(username)
print(password)
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return redirect('/logado/')
else:
messages.error(request,'Usuário e senha inválido. Favor tentar novamente:')
return redirect('/login/')
and a print screen with the folders' structure and the page "logado":
https://imgur.com/a/xAsBRHO
Thank you!
try return redirect('logado') and return redirect('login') syntax return redirect('your_view_name')
That's because you're passing a hardcoded URL (/logado/) to redirect that doesn't exists in your project's url.py, so Django can't match that route.
There are a couple of ways you can pass an argument to redirect, you can see some examples here. I strongly recommend you to use the name of your url's view, so in the future you can change the route of your path without any issues.
Also, you can declare your URLs like this, in that way you'll keep things clean and not bloat your project's urls.py.
Doing this you'll have your project's urls.py like this:
from django.contrib import admin
from django.urls.conf import include
from django.urls import path
from core import views
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', include('core.urls'),
]
And your application's urls.py like this:
from . import views
from django.urls import path
app_name = 'core'
urlpatterns = [
path('', views.login_user, name='login'),
path('login/submit/', views.submit_login, name='submit'),
path('login/logado/', views.logado, name='logado')
]
(Don't forget the trailing / at the end of each route)
Now you can call your view like this return redirect('core:logado')

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.

How to redirect users to a specific url after registration in django registration?

So I am using django-registration app to implement a user registration page for my site. I used Django's backends.simple views which allows the users to immediately login after registration. My question is how do I redirect them to my other app's page located in the same directory as the project.
Here is what my main urls.py looks like:
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
url(r'^accounts/', include('registration.backends.simple.urls')),
url(r'^upload/', include('mysite.fileupload.urls')),
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^mysite/', include('mysite.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
)
import os
urlpatterns += patterns('',
(r'^media/(.*)$', 'django.views.static.serve', {'document_root': os.path.join(os.path.abspath(os.path.dirname(__file__)), 'media')}),
)
fileupload is the name of the other app I have in the project directory mysite.
This is what the backends.simple.urls looks like:
"""
URLconf for registration and activation, using django-registration's
one-step backend.
If the default behavior of these views is acceptable to you, simply
use a line like this in your root URLconf to set up the default URLs
for registration::
(r'^accounts/', include('registration.backends.simple.urls')),
This will also automatically set up the views in
``django.contrib.auth`` at sensible default locations.
If you'd like to customize registration behavior, feel free to set up
your own URL patterns for these views instead.
"""
from django.conf.urls import include
from django.conf.urls import patterns
from django.conf.urls import url
from django.views.generic.base import TemplateView
from registration.backends.simple.views import RegistrationView
urlpatterns = patterns('',
url(r'^register/$',
RegistrationView.as_view(),
name='registration_register'),
url(r'^register/closed/$',
TemplateView.as_view(template_name='registration/registration_closed.html'),
name='registration_disallowed'),
(r'', include('registration.auth_urls')),
)
And here is the backends.simple.views:
from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.contrib.auth.models import User
from registration import signals
from registration.views import RegistrationView as BaseRegistrationView
class RegistrationView(BaseRegistrationView):
"""
A registration backend which implements the simplest possible
workflow: a user supplies a username, email address and password
(the bare minimum for a useful account), and is immediately signed
up and logged in).
"""
def register(self, request, **cleaned_data):
username, email, password = cleaned_data['username'], cleaned_data['email'], cleaned_data['password1']
User.objects.create_user(username, email, password)
new_user = authenticate(username=username, password=password)
login(request, new_user)
signals.user_registered.send(sender=self.__class__,
user=new_user,
request=request)
return new_user
def registration_allowed(self, request):
"""
Indicate whether account registration is currently permitted,
based on the value of the setting ``REGISTRATION_OPEN``. This
is determined as follows:
* If ``REGISTRATION_OPEN`` is not specified in settings, or is
set to ``True``, registration is permitted.
* If ``REGISTRATION_OPEN`` is both specified and set to
``False``, registration is not permitted.
"""
return getattr(settings, 'REGISTRATION_OPEN', True)
def get_success_url(self, request, user):
return (user.get_absolute_url(), (), {})
I tried the changing the get_success_url function to just return the url I want which is /upload/new but it still redirected me to users/insert username page and gave an error. How do I redirect the user to the upload/new page where the other app resides after registration?
Don't change the code in the registration module. Instead, subclass the RegistrationView, and override the get_success_url method to return the url you want.
from registration.backends.simple.views import RegistrationView
class MyRegistrationView(RegistrationView):
def get_success_url(self, request, user):
return "/upload/new"
Then include your custom registration view in your main urls.py, instead of including the simple backend urls.
urlpatterns = [
# your custom registration view
url(r'^register/$', MyRegistrationView.as_view(), name='registration_register'),
# the rest of the views from the simple backend
url(r'^register/closed/$', TemplateView.as_view(template_name='registration/registration_closed.html'),
name='registration_disallowed'),
url(r'', include('registration.auth_urls')),
]
I am using django_registration 3.1 package. I have posted all 3 files (views.py urls.py forms.py) that are needed to use this package.
To redirect user to a custom url on successfull registration, create a view that subclasses RegistrationView. Pass in a success_url of your choice.
Views.py:
from django_registration.backends.one_step.views import RegistrationView
from django.urls import reverse_lazy
class MyRegistrationView(RegistrationView):
success_url = reverse_lazy('homepage:homepage') # using reverse() will give error
urls.py:
from django.urls import path, include
from django_registration.backends.one_step.views import RegistrationView
from core.forms import CustomUserForm
from .views import MyRegistrationView
app_name = 'core'
urlpatterns = [
# login using rest api
path('api/', include('core.api.urls')),
# register for our custom class
path('auth/register/', MyRegistrationView.as_view(
form_class=CustomUserForm
), name='django_registration_register'),
path('auth/', include('django_registration.backends.one_step.urls')),
path('auth/', include('django.contrib.auth.urls'))
]
forms.py:
from django_registration.forms import RegistrationForm
from core.models import CustomUser
class CustomUserForm(RegistrationForm):
class Meta(RegistrationForm.Meta):
model = CustomUser
You can set SIMPLE_BACKEND_REDIRECT_URL in settings.py.
settings.py
SIMPLE_BACKEND_REDIRECT_URL = '/upload/new'
If you wish, you can modify the following file /usr/local/lib/python2.7/dist-packages/registration/backends/simple/urls.py, changing the path, for example:
Before modifying:
success_url = getattr (settings, 'SIMPLE_BACKEND_REDIRECT_URL', '/'),
After modifying:
success_url = getattr (settings, 'SIMPLE_BACKEND_REDIRECT_URL', '/upload/new'),
Regards.
Diego

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