maximum recursion depth exceeded on logout(request) - django

I'm trying to create the logout functionality on my page. But getting this recursion error, everytime I hit the link that points to the logout url.
Below is the code, for what is suppose to be showing content and a logout functionality if the user is logged in. Otherwise show the login form.
view methods
def login(request):
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
context = {
}
if user is not None:
print('Correct user'
else:
print('Wrong user')
return render(request, 'index.html', context)
def logout(request):
print('logged out')
logout(request)
return redirect('index')
url
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^login/$', views.login, name='login'),
url(r'^logout/$', views.logout, name='logout'),
]
index.html
{% if user %}
<h3>Hello {{user.username}}</h3>
Logout
{% else %}
<form action="{% url 'crowd:login' %}" method='post'>
{% csrf_token %}
<input class='logintext' type='text' placeholder='Username' name='username'>
<input class='logintext' type='password' placeholder='Password' name='password'><br>
<input class='loginbutton' type='submit' value='Login'>
<a class='loginforgotpassword' href="{% url 'crowd:register' %}"> Forgot password?</a>
<a class='loginregister' href="{% url 'crowd:register' %}"> Register</a>
</form>
{% endif%}
console error:
File "C:\Users\Rasmus\workspace\Crowd\src\Cr\views.py", line 48, in logout
logout(request)
File "C:\Users\Rasmus\workspace\Crowd\src\Cr\views.py", line 48, in logout
logout(request)
File "C:\Users\Rasmus\workspace\Crowd\src\Cr\views.py", line 48, in logout
logout(request)
File "C:\Users\Rasmus\workspace\Crowd\src\Cr\views.py", line 47, in logout
print('logged out')
RecursionError: maximum recursion depth exceeded
[04/Sep/2016 23:35:59] "GET /Crowd/logout/ HTTP/1.1" 500 3210436

Kindly change name of your logout view.
The error is with:
def logout(request):
print('logged out')
logout(request)
return redirect('index')
your view name is logout with request parameter. so when you call logout(request) in the view, it calls your logout view not Django's logout function. that's causing recursion.

Related

Why is my Django login not getting authenticated?

I do know that this is a repeated question. I did refer those answers but still I couldn't get my issue fixed. Kindly do help. Registration works just fine. The registered users gets added to the DB fine. Logout works fine. The issue is with login. Whenever I try logging in , I keep getting the response "Invalid login details".
views.py
from django.shortcuts import render, redirect
from . forms import *
from django.http import HttpResponse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
# USER LOGIN
def user_login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user =authenticate( username=username, password=password)
if user is not None:
if user.is_active:
login(request,user)
return redirect('home')
else:
return HttpResponse("Account not active")
else:
return HttpResponse("Invalid login details") #whenever I try to login, I always gets this response.
else:
return render(request, 'basic_app/login.html')
#USER LOGOUT
#login_required
def user_logout(request):
logout(request)
return redirect('login')
urls.py(application).
from django.urls import path
from . import views
urlpatterns = [
path('',views.index, name='home'),
path('register/',views.register, name='register'),
path('login/',views.user_login, name='login'),
path('logout/',views.user_logout, name='logout'),
]
login.html
{% extends 'basic_app/base.html' %}
{% block body_block %}
<div class='jumbotron'>
<h2>User Login</h2>
<form action="{% url 'login' %}" method="post">
{% csrf_token %}
<label for="username">Username:</label>
<input id="username" type="text" placeholder="Enter Username">
<label for="password">Password</label>
<input id="password" type="password" placeholder="Enter Password">
<input type="submit" value="Login">
</form>
</div>
{% endblock %}
settings.py
LOGIN_URL = '/basic_app/login/'
Try this:-
Make a copy of your Project in another folder. AND delete the current database and
create a new Database as usual like :- IN Terminal - Create Superuser command is :-
python manage.py createsuperuser.
In your views.py, in the user_login function you are checking if the user.is_active.
Instead try checking if the user is authenticated in the if statement.
Because I think that the user would probably be inactive before being logged in or authenticated.
For example, this is from the documentation:
if request.user.is_authenticated:
# Do something for authenticated users.
...
else:
# Do something for anonymous users.
...
Check the documentation here
Edit
Sorry, I was lookin at the wrong if block.
You don't seem to have assigned anything to the user variable. That maybe why the user is returned as none.
Also you can try:
user = request.user

Django NoReverseMatch when trying to logout

I have a django view function signout that I want to call form a form/template. When i click logout, it calls the function but the redirect after doesnt work. I get the message Reverse for '<WSGIRequest: POST '/account/signout'>' not found. '<WSGIRequest: POST '/account/signout'>' is not a valid view function or pattern name.
Urls.py
urlpatterns = [
path('register', views.register, name='register'),
path('login', views.login, name='login'),
path('signout', views.signout, name='signout'),
path('dashboard', views.dashboard, name='dashboard'),
]
Views.py
def signout(request):
if(request.method == 'POST'):
auth.logout(request)
messages.success(request, 'You are logged out!')
return redirect(request, 'index')
Template form
<form action="{% url 'signout'%}" id="logout" method="POST">
{% csrf_token %}
<input type="hidden">
<button type="submit" class="btn btn-primary btn-sm"><i class="fas fa-sign-out-alt"></i>
Log Out</button>
</form>
What is going wrong?? The rest of routes work just fine and they are declared the same as signout.
You are doing wrong in your view .You don't need parenthesis while checking the if condition and redirect doesn't take the request parameter.
Change your view like this
def signout(request):
if request.method == 'POST':
auth.logout(request)
messages.success(request, 'You are logged out!')
return redirect('index')

Register Page instantly buffering

When I tried to register in my site, it's instantly buffering,
The server is working properly and others were coded finely.
The urls.py
urlpatterns = [
#Login Page
url(r"^login/$", login, {'template_name':'users/login.html'},
name='login'),
#Logout Page
url(r"^logout/$", views.logout_view, name="logout"),
# Registration Page
url(r"^register/$", views.register, name='register'),
]
The views.py
def register(request):
"""Register a new user."""
if request.method != "POST":
#display blank register form.
form = UserCreationForm()
else:
# process completed form.
form = UserCreationForm(data=request.POST)
if form.is_valid():
new_user = form.save()
# Log the user in and then redirect to home page
authenticate_user = authenticate(username=new_user.username,
password=request.POST['password1'])
login(request, authenticate_user)
return HttpResponseRedirect(reverse('learning_logs:index'))
context = {'form': form}
return render(request, 'users/register.html', context)
Double checked I am in the right views.py
The register.html is:
{% extends "learning_logs/base.html" %}
{% block content %}
<form action="{% url "users:register" %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<button name="submit">log in</button>
<input type="hidden" name="next" value="{% url "learning_logs:index" %}">
</form>
{% endblock content %}
Where might be the problem live?

django-auth Login is not working as expected

my forms.py:
from django import forms
from django.contrib.auth import authenticate, get_user_model
from django.contrib.auth.models import User
from django.forms import ModelForm
from django.utils.text import capfirst
from .models import Classname, Sectionname, Teachername, Attendancename
class AuthenticationForm(forms.Form):
username = forms.CharField(max_length=20)
password = forms.CharField(widget=forms.PasswordInput)
error_messages = {
'invalid_login': ("Please enter a correct %(username)s and password."
"Note that both fields may be case-sensitive."),
'inactive': ("This account is inactive"),
}
def __init__(self, request=None, *args, **kwargs):
self.request = request
self.user_cache = None
super(AuthenticationForm, self).__init__(*args, **kwargs)
UserModel = get_user_model()
self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD)
if self.fields['username'].label is None:
self.fields['username'].label = capfirst(self.username_field.verbose_name)
def clean(self):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
if username and password:
self.user_cache = authenticate(username=username, password=password)
if self.user_cache is None:
raise forms.ValidationError(
self.error_messages['invalid_login'],
code='invalid_login',
params={'username': self.username_field.verbose_name},
)
else:
self.confirm_login_allowed(self.user_cache)
return self.cleaned_data
def confirm_login_allowed(self, user):
if not user.is_active:
raise forms.ValidationError(
self.error_messages['inactive'],
code='inactive',
)
def get_user_id(self):
if self.user_cache:
return self.user_cache.id
return None
def get_user(self):
return self.user_cache
views.py:
#csrf_protect
#never_cache
def login(request, template_name='login.html',
authentication_form=AuthenticationForm,
extra_context=None):
if request.method == "POST":
form = authentication_form(request, data=request.POST)
if form.is_valid():
return HttpResponseRedirect(reverse('student:mains'))
else:
print(form.errors)
else:
form = authentication_form(request)
context = {
'form': form,
}
return TemplateResponse(request, template_name, context)
my login template:
<html>
<head><title>Login</title></head>
<strong> Mysite Login </strong>
<br><br>
<h3> Please Enter your credentials carefully </h3>
<body>
{% if form.errors %}
<p>NOT VALID</p>
{% for errors in form.errors %}
{{ errors }}
{% endfor %}
{% endif %}
<form method="post">
{% csrf_token %}
<label>Username: </label>
<input type="text">
<br>
<label>Password: </label>
<input type="password">
<br>
<input type="submit" value="Login">
</form>
</body>
</html>
my urls.py:
from django.conf.urls import url, patterns
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
url(r'^register/$', views.register, name='register'),
url(r'^login/$', views.login, name='login'),
url(r'^logout/$', views.logout, name='logout'),
url(r'^password_change/$', auth_views.password_change, {'template_name': 'password_change_form.html', 'post_change_redirect': '/stu/password_change/done/'}, name="password_change"),
url(r'^password_change/done/$', auth_views.password_change_done, {'template_name': 'password_change_done.html'}, name="password_change_done"),
url(r'^restricted/', views.restricted, name='restricted'),
url(r'^mains/', views.mains, name = 'mains'),
]
I'm trying to implement django-authentication on my project. I have read some docs and made the above authentication views and forms.
The problem is that when I'm submitting my login form with correct credentials it doesn't redirect me to the redirect location as specified in my views. It doesn't do anything.
Is it the correct way in which I'm trying to do it? As I'm not using here model form.
Please suggest me the way to correct it...
Thanks! in Advance...
Still facing the same issue...
Change this:
<form method="post">
<label>Username: </label>
<input name="name">
<label>Password: </label>
<input name="phone">
to,
<form method="post" action="{% url 'login_url_name' %}">
<label>Username: </label>
<input name="username">
<label>Password: </label>
<input name="password">
Debugging suggestions:
Make sure you’re hitting the correct view when you submit the form. How? Add debug logging1 at the beginning of login(). If you don’t see the logging when you submit then make sure to set <form>’s action attribute to proper URL.
Make sure your form passes is_valid() test. Add debug logging inside if form.is_valid(): branch in your view. If it doesn’t work, make sure credentials are correct. Dump request.POST to see what might be wrong with data submitted by the form.
1 Debug logging may be a simple Exception("HEYY!!") in your code. The purpose is simply to see if your code reaches the branch in question. You’ll be sure it does if you see Django yelling at you.

Django Redirect the Logout Process to a View

I am very new to django, I have a following template:
{% if settings.LOGIN_SYSTEM %}
{% trans %}sign out{% endtrans %}
{% endif %}
I also have a view that clears out all the session:
class LogoutView(TemplateView):
redirect_field_name = "target"
def get(self, *args, **kwargs):
I want to make sure the login signal goes through the LogoutView get method. Can I call a view method from template?
If so an example would be great.
To logout use POST instead of GET. It is a architecture issue.
So to logout you should make a post request like the following example.
Logout template form
<form action="{% url 'logout' %}" method="post" >
{% csrf_token %}
<input type="submit" value="Logout" />
</form>
Logout url
urlpatterns = patterns('',
url(r'^logout/$', LogoutView.as_view(), name='logout'),
# other urls...
)
Logout view
from django.contrib.auth import logout
class LogoutView(ProcessFormView):
def post(self, request, *args, **kwargs):
logout(request)
return redirect('login-url-name')
Example logout
#require_POST
def logout(request):
auth.logout(request)
return redirect('/')