I'm beginner with Django and I've resolved my problem yet, but I want to understand...
I've a login page on my app and a logout page, here is it:
urls.py:
url('deconnexion', views.logout, name='deconnexion'),
url('connexion', views.connexion, name='connexion'),
views.py:
def connexion(request):
error = False
if request.method == "POST":
form = ConnexionForm(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
user = authenticate(username=username, password=password)
if user:
login(request, user)
else:
error = True
else:
form = ConnexionForm()
return render(request, 'dashboard/connexion.html', locals())
#login_required(login_url='/dashboard/connexion/')
def logout(request):
django_logout(request)
return redirect(reverse(connexion))
If I change place for url: connexion in place of deconnexion, my script doesn't work... I don't logout me and I'm redirected on the connexion page which is being connected...
If somebody have an idea?
P.S.: Sorry for my poor English, I'm French... And French with English.... we all know it's complicated... sorry ;)
As described in django documentations you can do like this:
from django.contrib.auth import logout
def logout_view(request):
logout(request)
return redirect(reverse(connexion))
Related
I am using Django to build a web app. I am using Vue JS for the frontend. My problem is when ever I use csrf_protect its showing 403 error
My views:
#csrf_protect
def SignUpView(request):
if request.method == "POST":
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username, password = form.cleaned_data.get('username'), form.cleaned_data.get('password1')
new_user = authenticate(username = username, password = password)
login(request, new_user)
return redirect('/')
else:
form = SignUpForm()
return render(request, 'Accounts/SignUp.html', {'form':form})
#csrf_protect
def validateUsername(request):
username = request.GET.get('username', None)
usernameRegEx = r'^[a-zA-Z0-9#+-_.#]*$'
usernameRegExResult = {
'valid' : bool(re.search(usernameRegEx, username, re.M|re.I)),
'is_taken' : User.objects.filter(username=username).exists()
}
return JsonResponse(usernameRegExResult)
I read the Django docs which says I can use csrf_protect decorator above my view but in my case its not working. Somebody please help.
CSRF is a protection that prevents cross site request forgery. It works by generating an unique token that identify the form. So if you send data to your server without the token it gave you (through cookies for instance) it will not accept it.
If you have the CSRF middleware turned on you should not need CSRF protect decorator!
I am trying to execute one of the url of urls.py with urllib in django view function. After execution i got error like
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 411: Length Required
Is this possible to execute url with urllib inside django view function.
#login_required(login_url='http://domain/user/login?destination=apps/member/change_password')
def change_password(request):
'''Form for user to change their password'''
form = SetPasswordForm(user=request.user, data=request.POST or None)
if form.is_valid():
form.save()
ob = urllib.request.urlopen(url='http://domain/login/', data=request)
messages.success(request, 'Your password has been succesfully updated!')
return redirect('hq:profile')
return render(request, 'registration/password_change_form.html',
{'form': form})
when i execute urllib
Yes it is possible but keep in mind, that the time of that request will add up to your loading time.
If you do that from within the same django system you should think, if there would be a better solution.
In your case it may eventually use:
from django.contrib.auth import authenticate
authenticate(username, password)
I have solved my problem by modifying as below.
from django.contrib.auth import login
#login_required(login_url='http://domain/user/login?destination=apps/member/change_password')
def change_password(request):
'''Form for user to change their password'''
form = SetPasswordForm(user=request.user, data=request.POST or None)
if form.is_valid():
user = form.save()
user.is_active = True
user.save()
user.backend = "django.contrib.auth.backends.ModelBackend"
login(request, user)
messages.success(request, 'Your password has been succesfully updated!')
return redirect('hq:profile')
return render(request, 'registration/password_change_form.html',
{'form': form})
I am using generic form view for authentication, I am getting next parameter in url but unfortunately I don't know how to redirect it to next, after successful login for Generic Form View, here is my view
class LoginView(
views.AnonymousRequiredMixin,
generic.FormView):
form_class = LoginForm
success_url = reverse_lazy('home')
template_name = 'accounts/registered/login.html'
def form_valid(self, form):
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None and user.is_active and user.is_seller:
login(self.request, user)
return super(LoginView, self).form_valid(form)
else:
return self.form_invalid(form)
I am getting this
http://127.0.0.1:8000/accounts/login/?next=/accounts/dashboard/
help me out!
So essentially, what the url that you are getting means is that it's trying to go to 127.0.0.1:8000/accounts/dashboard/, but because the user needs to be logged in, it's going to the login page first. Essentially, this means that your view is not logging the user in for some reason.
Try using (or extending) Django's built in LoginForm class (https://docs.djangoproject.com/en/2.0/topics/auth/default/#django.contrib.auth.views.LoginView)
Alternatively, go with a broader solution suite, such as django allauth (https://github.com/pennersr/django-allauth/blob/master/docs/index.rst)
You should use HttpRedirectResponse:
views.py
from django.http import HttpResponseRedirect
def login(request):
# You logic goes here
return HttpResponseRedirect('dashboard')
def dashboard(request):
context = {
# User information goes here
}
return render(request, 'dashboard', context)
Do not forget to add this call to the login method in your urls.py:
path('login', views.login, name='login'),
path('dashboard', views.dashboard, name='dashboard'),
You should also take a look at https://docs.djangoproject.com/en/2.0/ref/request-response/ for a better understanding of how request and response work.
You should also be familiar with https://docs.djangoproject.com/en/2.0/intro/tutorial04/ so that you could understand an example of HttpResponseRedirect.
when I am using login_required it does not rendering to appropriate url it always render to home page only
login view
def login_view(request):
print(request.user.is_authenticated())
w="Welcome"
title = "Login"
form = UserLoginForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = authenticate(username=username, password=password)
login(request, user)
messages.success(request, "Successfully Logged In. Welcome Back!")
return HttpResponseRedirect("/")
return render(request, "registration/login.html", {"form":form, "title":title})
settings.py file
LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = '/'
I applied login required on contact us but when i am logging in then it is rendering to home page.
contact us view
#login_required
def contactformview(request):
form = ContactForms(request.POST or None)
if form.is_valid():
form.save()
return HttpResponse(' Thanks For Contacting WIth Us We Will Get Back To You Within 24 Hours')
return render(request, 'contact-us.html', {'form':form})
When Django redirects to the login page, it includes the next url in the querystring, e.g.
/login/?next=contact
Your login_view ignores the querystring and always returns HttpResponseRedirect("/"), so you will always be redirected to the homepage.
It would be better to use Django's login view instead of your own, because it handles the redirect for you. If you must use your own login view, you can look at the source code to see how Django handles the redirect, and adjust your view.
What are the options when you want to return the user to the same page in Django and what are the pros/cons of each?
Methods I know:
HTTP_REFERER
GET parameter containing the previous URL
Session data to store the previous URL
Are there any other?
One of the way is using HTTP_REFERER header like as below:
from django.http import HttpResponseRedirect
def someview(request):
...
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Not sure of cons of this!
100% working Example
For Class Based View and Function:
from django.http import HttpResponseRedirect
...
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
or
from django.http import HttpResponseRedirect
...
return HttpResponseRedirect(self.request.META.get('HTTP_REFERER'))
Example -
class TaskNotificationReadAllView(generic.View):
def get(self, request, *args, **kwargs):
TaskNotification.objects.filter(assigned_to=request.user).update(read=True)
print(request.META.get('HTTP_REFERER'))
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
While the question and answer is old, I think it's lacking a few options. I have not find any cons with the methods, I would be happy to know if there are any?
request.path_info
request.get_full_path()
request.build_absolute_uri()
from django.shortcuts import redirect
redirect(request.path_info) # No query parameters
redirect(request.build_absolute_uri()) # Keeps query parameters
redirect(request.get_full_path()) # Keeps query parameters
In django view suppose you are not logged in but click on some content that content trigger some url like /board/2/new_topic then #login_required will redirect you to login page with this url
http://localhost:8000/signin/?next=/boards/2/new_topic/
so our aim is redirect to http://localhost:8000/boards/2/new_topic/ page after successful login so one line we will have to add
if 'next' in request.GET:
return redirect(request.GET['next'])
then if it next is there then it will redirect according to that other normal redirect .
Views.py :
def signin(request):
if request.method == "POST":
user_login_form = UserLoginForm(request.POST)
email = request.POST['email']
password = request.POST['password']
user = authenticate(request, email=email, password=password)
if user and user.is_active:
login(request, user)
if 'next' in request.GET:
return redirect(request.GET['next'])
else:
return redirect('home')
else:
return render(request, 'signin.html', context={'form': user_login_form})
else:
user_login_form = UserLoginForm()
return render(request, 'signin.html', context={'form': user_login_form})