NoReverseMatch (Reverse for ' user_login' not found) - django

I have a django project called log and an application called basic_app. I created a register form but when I want to create a user_login, I get this error:
NoReverseMatch at /basic_app/user_login/
Reverse for ' user_login' not found. ' user_login' is not a valid view function or pattern name.
views.py:
from django.shortcuts import render
from basic_app.forms import UserForm, UserProfileInfoForm
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers 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('You are loged in!')
#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 = UserProfileInfoForm(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 = UserProfileInfoForm()
return render(request, 'basic_app/registration.html',
{'user_form':user_form,
'profile_form':profile_form,
'registered':registered})
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:
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 supplied!')
else:
return render(request, 'basic_app/login.html',{})
basic_app/urls.py:
from django.conf.urls import url
from basic_app import views
#TEMPLATE URLS
app_name = 'basic_app'
urlpatterns = [
url(r'^register/$', views.register, name='register'),
url(r'^user_login/$', views.user_login, name='user_login'),
log/urls.py:
from django.conf.urls import url, include
from django.contrib import admin
from basic_app import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^admin/', admin.site.urls),
url(r'^basic_app/', include('basic_app.urls')),
url(r'^logout/$', views.user_logout, name='logout'),
url(r'special/', views.special, name='special')
login.html:
{% extends 'basic_app/basic.html' %}
{% block body_block %}
<div class="jumbotron">
<h1>Please Login: </h1>
<form action="{% url 'basic_app: user_login' %}" method="post">
{% csrf_token %}
<label for="username">Username:</label>
<input type="text" name="username" placeholder="Enter Username">
<label for="passwrod">Password:</label>
<input type="password" name="password">
<input type="submit" name="" value="Login">
</form>
</div>
{% endblock %}

Related

Django register form not showing up on admin users when submitted

I want to create a register and login but when I create account in http://127.0.0.1:8000/register/ it doesn't show in admin (http://127.0.0.1:8000/admin/auth/user/)
views.py
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth import authenticate, login
def register(request):
form = UserCreationForm()
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
context = {'form': form}
return render(request, 'user/register.html', context)
def login(request):
context = { }
return render(request, 'user/login.html', context)
urls.py
from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
path('register/', views.register, name = "register"),
path('login/', views.login, name="login"),
]
user/register.html
<form method="POST" action=" ">
{% csrf_token %}
{{form.as_p}}
<input type="submit" name="Create User">
</form>
I need help, Thank you!

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

why is my input fields not showing in the website?

I have created a login and registration page using the same code. The registration page shows username input fields and other fields but the login page only shows the button. Can anyone help me in this
Code:
Login Page:
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Join Today</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Sign Up</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Already Have An Account? <a class="ml-2" href="{% url 'login' %}">Sign In</a>
</small>
</div>
</div>
Registration Page:
<div class="site-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Log In </legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Login</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Need An Account? <a class="ml-2" href="{% url 'register' %}">Sign Up Now</a>
</small>
</div>
</div>
Registration page
Login page
This is the views of the project
Views.py
from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm
from .models import Post
from django.contrib.auth.decorators import login_required
def home(request):
context = {
'posts': Post.objects.all()
}
return render(request, 'blog/home.html', context)
def about(request):
return render(request, 'blog/about.html', {'title': 'About'})
def gallery(request):
return render(request, 'blog/gallery.html', {'title': 'Gallery'})
def foodopedia(request):
return render(request, 'blog/foodopedia.html', {'title': 'Foodopedia'})
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Account created for {username}!')
return redirect('blog-home')
else:
form = UserRegisterForm()
return render(request, 'blog/register.html', {'form': form})
def login(request):
return render(request, 'blog/login.html', {'title': 'Login'})
#login_required
def profile(request):
return render(request, 'blog/profile.html', {'title': 'Profile'})
def upload(request):
context = {}
if request.method == 'POST':
uploaded_file = request.FILES['document']
fs = FileSystemStorage()
name = fs.save(uploaded_file.name, uploaded_file)
context['url'] = fs.url(name)
context['filename'] = name
pred, probability = process_image(name)
context['prediction'] = pred
context['probability'] = probability
return render(request, 'blog/foodopedia.html', context)
This is the urls.py of the project
from django.contrib import admin
from django.urls import path, include
from blog import views as blog_views
from django.contrib.auth import views as auth_views
from blog import views as blog_views
urlpatterns = [
path('admin/', admin.site.urls),
path('register/', blog_views.register, name='register'),
path('profile/', blog_views.profile, name='profile'),
path('', include('blog.urls')),
path('login/', auth_views.LoginView.as_view(template_name='blog/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(template_name='blog/logout.html'), name='logout'),
]
This is the form.py file:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
You forgot to create a new form in forms.py, then also dont forget to enhance your login view.
You could try using this, adapted from the example in this tutorial:
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import AuthenticationForm
def login(request):
if request.user.is_authenticated:
return redirect('/')
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('/')
else:
form = AuthenticationForm(request.POST)
return render(request, 'blog/login.html', {'form': form, 'title': 'Login'})
else:
form = AuthenticationForm()
return render(request, 'blog/login.html', {'form': form, 'title': 'Login'})
To use that you would have to change the login line in your urls.py to this:
path('login/', blog_views.login, name='login'),

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.

how to implement AuthenticationForm in a view?

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:
from django.shortcuts import render, get_object_or_404
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.http import Http404, HttpResponseRedirect, HttpResponse
from django.template.response import TemplateResponse
from django.views.generic import DeleteView, ListView
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.cache import never_cache
from .models import Classname, Sectionname, Teachername, Attendancename
from .forms import ClassnameForm, SectionnameForm, TeachernameForm, AttendancenameForm, UserForm, PasswordChangeForm, AuthenticationForm
def user_login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
login(request, user)
return HttpResponseRedirect(reverse('student:mains'))
else:
return HttpResponse("Invalid Login details supplied!")
return render(request, 'login.html', {'form': form},)
my 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>
Here above I'm trying to implement authentications on my current app. I want to show login failure error on same login page, For which I have written a 'AuthenticationForm' class above.
I read some docs but don't know exactly how to use this form in my views for Authentication purpose.
Please! Can anybody suggest me how to make it correct