Reverse for '<WSGIRequest: GET '/accounts/login'>' not found. '<WSGIRequest: GET '/accounts/login'>' is not a valid view function or pattern name - django-views

urls.py/telusko
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', include('blog.urls')),
path('admin/', admin.site.urls),
path('accounts/',include('accounts.urls'))
]
urls.py/accounts
from django.urls import path
from . import views
# create a path or url for REGISTER
urlpatterns = [
path("registration",views.registration,name="registration"),
path("login",views.login,name="login")
]
views.py/accounts
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.models import User, auth
# Create your views here.
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
User = auth.authenticate(username=username,password=password)
if User is not None:
auth.login(request, User)
return redirect('/')
else:
messages.info(request,'invalid details')
return redirect('login')
else:
return redirect(request,'login')
def registration(request):
if request.method == 'POST':
first_name = request.POST['first_name']
last_name = request.POST['last_name']
username = request.POST['username']
email = request.POST['email']
password1 = request.POST['password1']
password2 = request.POST['password2']
if password1==password2:
if User.objects.filter(username=username).exists():
messages.info(request,'username already exists')
return redirect('registration')
elif User.objects.filter(email=email).exists():
messages.info(request,'email taken')
return redirect('registration')
else:
user = User.objects.create_user(username=username, password=password1, email=email, first_name=first_name,last_name=last_name)
user.save();
messages.info(request,'user created')
return redirect('login')
else:
messages.info(request,'password not matching...')
return redirect('registration')
return redirect('/')
else:
return render(request,'registration.html')
index.html
<div class="col-md-8">
<div class="float-right">
<ul class="top_links">
<li>REGISTER</li>
<li>LOGIN</li>
</ul>
</div>
</div>
login.html/template
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LOGIN</title>
</head>
<body>
<form action="login" method="post">
{% csrf_token %}
<input type="text" name="username" placeholder="username"><br>
<input type="password" name="password" placeholder="password"><br>
<input type="submit" name="login" placeholder="login">
</form>
<div>
{% for Message in messages %}
<h3> {{Message}} </h3>
{% endfor %}
</div>
</body>
</html>
above is code for register and login pages
the problem is just simple i.e: i'm able to register in registration page similarly i'm not able get the login page when i click on login page i'm encountering this kinda issue help me out with this error
the error occuring :
NoReverseMatch at /accounts/login
Reverse for '<WSGIRequest: GET '/accounts/login'>' not found. '<WSGIRequest: GET '/accounts/login'>' is not a valid view function or pattern name.
Request Method: GET
Request URL: http://127.0.0.1:8000/accounts/login
Django Version: 4.1.3
Exception Type: NoReverseMatch
Exception Value:
Reverse for '<WSGIRequest: GET '/accounts/login'>' not found. '<WSGIRequest: GET '/accounts/login'>' is not a valid view function or pattern name.
Exception Location: C:\Users\vinod\Envs\test\lib\site-packages\django\urls\resolvers.py, line 828, in _reverse_with_prefix
Raised during: accounts.views.login
Python Executable: C:\Users\vinod\Envs\test\Scripts\python.exe
Python Version: 3.10.2
Python Path:
['C:\Users\vinod\telusko\projects',
'C:\Users\vinod\AppData\Local\Programs\Python\Python310\python310.zip',
'C:\Users\vinod\AppData\Local\Programs\Python\Python310\DLLs',
'C:\Users\vinod\AppData\Local\Programs\Python\Python310\lib',
'C:\Users\vinod\AppData\Local\Programs\Python\Python310',
'C:\Users\vinod\Envs\test',
'C:\Users\vinod\Envs\test\lib\site-packages']
Server time: Thu, 15 Dec 2022 15:47:04 +0000

use reverse() method instead of redirect('pathname') and use django templating tag (DTL)
links
https://docs.djangoproject.com/en/4.1/ref/urlresolvers/
https://docs.djangoproject.com/en/4.1/ref/templates/builtins/

Related

Logout function in Django not working as Expected

I have not used any middleware, when i click on logout button on my Home Page template, the logout function execute without any error.but when i go back to main page without jumping to login page.. i see myself as logged in user
here is my authentiCation/views.py
from django.shortcuts import render
from django.http import request,HttpResponseRedirect
# for user creation & login form
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login
# for user related Queries
from django.contrib.auth.models import User
# imports for test purpose
from django.http import HttpResponse
# Create your views here.
# register page
def register_Page(request):
if request.method == 'POST':
form= UserCreationForm(request.POST)
if form.is_valid():
form.save()
username= request.POST['username']
password= request.POST['password1']
user= authenticate(request,username=username,password=password)
login(request,user)
return HttpResponseRedirect('/')
else:
return HttpResponse('Either the user name is not available or you may have filled the form incorrectly')
else:
form = UserCreationForm()
context= {'form':form}
return render(request,'authentication/register_Page.html',context)
# login page
def login_page(request):
if request.method == 'POST':
username= request.POST['username']
password= request.POST['password']
# returns user if credentials are valid
user= authenticate(request, username=username, password= password)
# check if user var contains the user
if user is not None:
login(request, user)
return HttpResponseRedirect('/')
else:
return HttpResponse('Invalid credentials')
return render(request,'authentication/login.html')
# logout Page
def log_out(request):
logout(request)
return HttpResponseRedirect('logout_page')
authentiCation/urls.py
from django.urls import path
from authentiCation import views
urlpatterns = [
path('register/',views.register_Page),
path('login/',views.login_page,name='login_page'),
path('logout/',views.log_out),
]
Main App Files
urls
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('App_wfi_Community.urls')),
path('Ask/',include('askQuestion.urls')),
path('auth/',include('authentiCation.urls')),
]
Home.html
{% extends "basic.html" %}
{% load humanize %}
{% block title %}WFI-Community{% endblock title %}
{% block body %}
<!-- search button -->
<h5>Welcome {{username}},<h5> <!-- I see my username here -->
<form action="/search" method="get">
<div class="container py-3 row">
<div class="col-md-8 offset-2">
<div class="input-group">
<input name="searchfieldText" type="text" class="form-control" placeholder="Search">
<button class="btn btn-danger" type="submit">Search</button>
<span>Logout</span>
</div>
</div>
</div>
</form>
<!-- and some more HTML stuff which is irrelavent here -->
Give a name to this eg
path('logout/',views.log_out, name="logout" ) and change it in the home.html.
eg "{% url 'logout' %}">Logout

How do i redirect a user to a specific page based on their login credentials using Django, HTML?

I'm trying to program my Django website to redirect users to custom HTML pages based on their login credentials. For example, my first user has the credentials - user=user1 pass=password1. I have created a separate user1.html page for him so when user1 enters his login info and presses login, he is automatically redirected to user1.html. When user2 logs in, he is redirected to user2.html, etc. How can I enable this in a basic and non-complicated way? I will just be using this for a small demo session, therefore, the code security and so on are not important in this case.
<!DOCTYPE html>
<html>
<head>
<title> XXXTechnologies </title>
</head>
<body>
<form>
<input type="button" value="Back" onclick="history.back()">
<p> User Login Form </p>
Username: <input id="username" type="text" name="username" >
<br>
Password: <input id="password" type="password" name="password" >
<br><br>
<input type="submit" name="Login" value="Login">
</form>
</body>
</html>
loginpage models.py
from django.db import models
class customerlogin(models.Model):
user_name = models.CharField(max_length=30)
pass_word = models.CharField(max_length=30)
myproject urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('loginpage.urls')),
loginpage urls.py
from django.urls import path
from . import views
urlpatterns = [
path('',views.index, name='loginpage'),
loginpage views.py
from django.shortcuts import render
from django.http import HttpResponse
from loginpage.models import customerlogin
def userview(request):
if request.customerlogin.username == 'user1':
return render(request, 'user1slug.html', {})
elif request.cuatomerlogin.username == 'user2':
return render(request, 'user2slug.html', {})
else:
return render(request, 'default.html', {})
def index(request):
return render(request, 'login.html')
In your views.py, you can write your code like:
def userview(request):
if request.user.username == 'user1':
return render(request, 'user1.html', {})
elif request.user.username == 'user2':
return render(request, 'user2.html', {})
else:
return render(request, 'default.html', {})
Dynamic redirection, you can do it in your login view, as follows.
def login(request):
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request,user)
return redirect('redirect_page')
else:
return redirect('login')
else:
return render(request, 'account/login.html')
In the redirect page you can get dynamic data from the backend. For example, if it is a profile page, you can filter the view to request.user and can show the content to logged in user.

NoReverseMatch at /basic_app/user_login/

Register works but login doesn't for some reason even though I've rechecked the template tagging properly.
I'm using a custom login model, not using the admin authentication model.
this is the at basic_app/urls.py
from django.conf.urls import url
from basic_app import views
app_name = 'basic_app'
urlpatterns = [
url('register/',views.register,name='register'),
url('user_login/',views.user_loginPls,name='user_login'),
]
and code at base.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<nav>
<div class="container">
<ul>
<li>Home</li>
<li>Admin</li>
<li>Register</li>
{% if user.is_authenticated %}
<li>Logout</li>
{% else %}
<li>Login</li>
{% endif %}
</ul>
</div>
</nav>
<div class="container">
{% block body_block %}
{% endblock %}
</div>
</body>
</html>
and code at view.py
from django.shortcuts import render
from basic_app.forms import UserForm,UserProfileInfoModelForm
#imports
from django.contrib.auth import authenticate, login,logout
from django.http import HttpResponseRedirect, HttpResponse
#changed from django.core.usrlresolvers to django.urls
#cant use reverse as it has been deprecated
from django.urls import reverse
from django.contrib.auth.decorators import login_required
# Create your views here.
def index(request):
return render(request,'basic_app/index.html')
#login_required
def special(request):
return HttpResponse('your logged in nice!!!')
#login_required
def user_logout(request):
logout(request)
return HttpResponseRedirect(reverse('index'))
def register(request):
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
profile_form = UserProfileInfoModelForm(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
if 'profile_pic' in request.FILES:
profile.profile_pic = request.FILES['profile_pic']
profile.save()
registered = True
else:
print(user_form.errors,profile_form.errors)
else:
user_form = UserForm()
profile_form = UserProfileInfoModelForm()
return render(request,'basic_app/registration.html',{'user_form':user_form,'profile_form':profile_form,'registered':registered})
def user_loginPls(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username,password=password)
if user:
if user.is_active:
login(request,user)
return HttpResponseRedirect(reverse('index'))
else:
return HttpResponse('ACCOUNT NOT ACTIVE')
else:
print('SOMEONE TRIED TO LOGIN AND FAILED')
print("Username: {} and password: {}".format(username,password))
return HttpResponse('INVALID LOGIN DETAILS')
else:
return render(request,'basic_app/loginhtml.html',{})
I can't figure out this error, any help would be appreciated.
I'm running Django 2.0 btw
the error is in your login.html file.
In the form section, the action should take action="{% url 'user_login' %}" and not action="{% url 'basic_app/user_login' %}".
Hope this helps.

why is the user authentication unsuccessful?

i am trying to build login page using django authentication system
below is the views
from django.contrib import auth
def auth_view(request):
username = request.POST.get('username','')
password = request.POST.get('password','')
print request.POST
user = auth.authenticate(username=username, password=password) #returns user object if match else None
if user is not None:
auth.login(request, user) #make user status as logged in now using django login function
return HttpResponseRedirect('/todos')
else:
return HttpResponseRedirect('/accounts/invalid')
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login page</title>
</head>
<body>
<h2>login page</h2>
<hr>
<form action="/accounts/auth/" method="post">{% csrf_token %}
username: <input type="text" name="username" value="" id="username"><br>
password: <input type="password" name="password" value="" id="password"><br>
<input type="submit" value="Login">
</form>
</body>
</html>
urls.py
...
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('invoices.urls')),
url(r'^todos/', include('todos.urls')),
url(r'^accounts/login/$', todos.views.login, name='login'),
url(r'^accounts/auth/$', todos.views.auth_view, name='auth_view'),
url(r'^accounts/logout/$', todos.views.logout, name='logout'),
url(r'^accounts/loggedin/$',todos.views.loggedin, name='loggedin'),
url(r'^accounts/invalid/$', todos.views.invalid_login, name='invalid_login'),
]
The variable user returns None even if the user/password is correct.when i change this line user = auth.authenticate(username=username, password=password) to actual user and password eg. user = auth.authenticate(username="peter", password="P#$w0rD275") it is successfully logged in
command line out put
>>>result=auth.authenticate(username='admin', password='adkd92')
>>>print result
None
>>>result=auth.authenticate(username='admin', password='admin123')
>>>print result
admin
Perhaps you have a simple typo, you have extra comma , at end of following lines:
username = request.POST.get('username',''), # <---
password = request.POST.get('password',''), # <---
Remove it and it should be fine I guess.

Django form self validation not working

My urls.py is something like this :
from django.conf.urls import url
from django.views.generic import ListView, TemplateView
from .models import Dreamreal
from . import views
urlpatterns = [
url(r'^connection/login/$', views.login),
url(r'^connection/$', TemplateView.as_view(template_name =
'login.html')),
url(r'^login/$', views.login, name = 'login')
]
My views.py is :
from .forms import LoginForm
from . import models
def login(request):
username = "not logged in"
if request.POST:
# GET THE POSTED FORM
MyLoginForm = LoginForm(request.POST)
if MyLoginForm.is_valid():
username = MyLoginForm.cleaned_data['username']
else:
MyLoginForm = LoginForm()
return render(request, 'loggedin.html', {'username' : username})
My forms.py is :
from django import forms
from .models import Dreamreal
class LoginForm(forms.Form):
username = forms.CharField(max_length = 100)
password = forms.CharField(widget = forms.PasswordInput())
# METHOD TO VERIFY IF USER IS IN DB
def clean_message(self):
username = self.cleaned_data.get("username")
dbuser = Dreamreal.objects.filter(name = 'username')
if not dbuser:
raise forms.ValidationError("User does not exist in our db!")
return username
My models.py is :
from django.db import models
class Dreamreal(models.Model):
website = models.CharField(max_length = 50)
mail = models.CharField(max_length = 50)
name = models.CharField(max_length = 50)
phonenumber = models.IntegerField()
class Meta:
db_table = 'dreamreal'
My login.html is :
<html>
<head>
<title>LOG IN</title>
</head>
<body>
<form name="form" action="/connection/login/" method="POST">
{% csrf_token %}
<div style="max-width: 470px;">
<center><input type="text" name="username"
placeholder="username" style="margin-left: 20%;" required>
</center>
</div>
<br>
<div style="max-width: 470px;">
<center><input type="password" name="password"
placeholder="password" style="margin-left: 20%;"></center>
</div>
<br>
<div style="max-width: 470px;">
<center><button style = "border:0px; background-color:#4285F4;
margin-top:8%; height:35px; width:80%;margin-left:19%;" type =
"submit" value = "Login" >
<strong>Login</strong>
</button></center>
</div>
</form>
</body>
</html>
My loggedin.html is :
{% extends 'base.html' %}
<html>
<head>
<title>{% block title%}{{ username }}{% endblock %}</title>
</head>
<body>
{% block content %}
You are : <strong>{{ username }}</strong>
{% endblock %}
When i am running the code and then entering the name and password in the dield input at /connection/ url, it is redirecting to /connectionlogin/ url but showing valid for all the usernames i am entering in the forms rather it should show only those names which are stored in the database name Dreamreal.
Somebody please help!
You are validating the username field, so you should name your method clean_username. Django will only call the clean_message field if the form has a field called message.
To see any form errors in the template you need to include the form in the context when you call render:
return render(request, 'loggedin.html', {'username' : username, 'form': MyLoginForm}
And you won't see the errors in the template unless you use form in the template. The easiest way to do this is to include {{ form }}. If you need to do something more advanced, see the docs on working with forms.