I am trying to have user validation in my django social media/blog app. I do not understand why this code does not work. The problem: No matter what name I type in the form it says the user does not exist even though the user does in fact exist. Any help would be amazing.
from django.shortcuts import render, redirect
from sign_in.forms import SignInForm
from django.contrib.auth.models import User
from django.contrib import messages
from django.contrib.auth.forms import forms
from django.http import HttpResponseRedirect
def sign_in(request):
if request.method == "POST":
form = SignInForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = User.objects.filter(username=username, password=password)
if user.exists():
return HttpResponseRedirect("boom/")
else:
messages.error(request, f"User {user} does not exist.")
else:
form = SignInForm()
return render(request, "sign_in/sign_in.html", {"form": form})
this is not how Django authentication works.
https://docs.djangoproject.com/en/3.1/topics/auth/
use authenticate method
try this
from django.contrib.auth import login, authenticate
def sign_in(request):
if request.method == "POST":
form = SignInForm(request.POST)
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)
if user.exists():
return HttpResponseRedirect("boom/")
else:
messages.error(request, f"User {user} does not exist.")
else:
form = SignInForm()
return render(request, "sign_in/sign_in.html", {"form": form})
Related
I'm developing a site on Django, but I got an error ERR_TOO_MANY_REDIRECTS. I think that the matter is in the views.py file. Help figure it out.
P.S. already tried to delete cookie files, it didn't help(
from email import message
from wsgiref.util import request_uri
from django.shortcuts import redirect, render
from django.contrib.auth.models import User, auth
from django.contrib import messages
# Create your views here.
def reg(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
cpassword = request.POST['cpassword']
if password == cpassword:
if User.objects.filter(username=username):
messages.info(request, 'Username taken')
return redirect('registration')
else:
user = User.objects.create_user(username=username, password=password)
user.save()
return redirect('login')
else:
messages.info(request, 'Passwords not matching')
return redirect('registration')
return redirect('/')
else:
return render(request, 'registration.html')
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 credentials')
return redirect('login')
else:
return render(request, 'login.html')
def logout(request):
auth.logout(request)
return redirect('/')
The problem is coming from your return redirect('/'). Redirect to one of the views written in your urls.py and your problem will be solved.
When I try to login on my django site, I get this error:
AttributeError at /login/
'User' object has no attribute 'method'
What is the problem? I'm fairly sure it was working yesterday, and now it isn't.
This is my login view:
from django import forms
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.http import HttpResponseRedirect
class LoginForm (forms.Form):
username = forms.CharField()
password = forms.CharField()
def login (request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
# username = request.POST['username']
# password = request.POST['password']
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:
login(user)
return redirect ("/login/success")
form = LoginForm(request.POST)
else:
form = LoginForm(request.POST)
return render (request, 'login.html', {'form':form})
You are calling your function with user as the param instead of a request. Rename your function, the imported Django's login or the way you import it.
Also, you are missing the request param, you should do login(request, user).
Use one of these options:
def my_login (request): # fix the necessary urls also
if request.method == 'POST':
.....
login(request, user)
or
from django.contrib import auth
.....
user = auth.authenticate(username=username, password=password)
if user is not None and user.is_active:
auth.login(request, user)
or
from django.contrib.auth import authenticate, login as django_login
.....
user = authenticate(username=username, password=password)
if user is not None and user.is_active:
django_login(request, user)
I defined SignUpFrom but still, the server shows that name 'SignUpForm' is not defined by anyone, please suggest to me how I'll fix it. Thanks in advance.
Code Location: App_Login Views.py
views.py--App_Loginstrong text
[from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth import login, authenticate, logout
from django.shortcuts import HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth.decorators import login_required
# Create your views here.
def sign_up(request):
form = SignUpForm()
registered = False
if request.method == 'POST':
form = SignUpForm(data=request.POST)
if form.is_valid():
form.save()
registered = True
dict = {'form':form, 'registered':registered}
return render(request, 'App_Login/signup.html', context=dict)
def login_page(request):
form = AuthenticationForm()
if request.method == 'POST':
form = AuthenticationForm(data=request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return HttpResponseRedirect(reverse('index'))
return render(request, 'App_Login/login.html', context={'form':form})
#login_required
def logout_user(request):
logout(request)
return HttpResponseRedirect(reverse('index'))
You will have to import the sign up form too
I'm trying to have a registration and login form both on my index page (NOT separate login/register urls). I'm able to display the forms, but having trouble with submission. At first I just had the registration form and submission for account creation worked just fine, but adding the Login form has started to cause some issues. Relatively new to Django and can't seem to find the documentation to fit my use case.
views.py
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
from .forms import UserRegisterForm
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
import datetime
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.contrib.auth.decorators import login_required
def index(request):
if request.method == 'POST':
if request.POST.get('submit') == 'login':
login_form = AuthenticationForm(request.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("Your account was inactive.")
else:
return HttpResponse("Invalid login details given")
elif request.POST.get('submit') == 'register':
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('index')
else:
form = UserRegisterForm()
login_form = AuthenticationForm()
now = datetime.datetime.now()
cur_year = now.year
context = {
'login_form': login_form,
'form' : form,
'year' : cur_year
}
return render(request, 'home/index.html', context)
def about(request):
return render(request, 'about.html')
I get the following error on trying to submit either the login or register form:
local variable 'login_form' referenced before assignment
can provide website url if that would help.
I got it working through a combination of what #Chris Curvey answered and changing the buttons from using a value of 'login' or 'register' to a name with those strings, then in my conditions using "if 'login' in request.POST:"
if 'login' in request.POST:
form = UserRegisterForm()
[login logic]
elif 'register' in request.POST:
login_form = AuthenticationForm()
[registration logic]
If the user submits an invalid registration form, you'll never define the login form. Then when you hit context =, you will get this exception.
I'd suggest creating an "empty" form instance for the "other" form. (That's hard to explain, an example will help
if request.POST.get('submit') == 'login':
form = UserRegisterForm()
login_form = AuthenticationForm(request.POST)
[login logic here]
elif request.POST.get('submit') == 'register':
login_form = AuthenticationForm()
form = UserRegisterForm(request.POST)
[registration logic here]
I'd like to add Recaptcha to my login form. I'm following this repository but i'm having some problems: i added this to my views.py:
from django import forms
from captcha.fields import ReCaptchaField
class FormWithCaptcha(forms.Form):
captcha = ReCaptchaField()
But i don't really know where to go from here. I suppose i need to add something to my login.html page but i don't know what. Can anyone give me some help? Note that i already added my public and private keys to my settings.py file.
This is the whole views.py:
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Tutorial
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import login, logout, authenticate
from django.contrib import messages
from .forms import NewUserForm
from django import forms
from captcha.fields import ReCaptchaField
class FormWithCaptcha(forms.Form):
captcha = ReCaptchaField()
def homepage(request):
return render(request=request,
template_name="main/home.html",
context={"tutorials": Tutorial.objects.all})
def register(request):
if request.method == "POST":
form = NewUserForm(request.POST)
if form.is_valid():
user = form.save()
username = form.cleaned_data.get('username')
messages.success(request, f"New Account Created: {username}")
login(request, user)
messages.info(request, f"You are now logged in as {username}")
return redirect("main:homepage")
else:
for msg in form.error_messages:
messages.error(request, f"{msg}: {form.error_messages[msg]}")
form = NewUserForm
return render(request,
"main/register.html",
context={"form":form})
def logout_request(request):
logout(request)
messages.info(request, "Logged out successfully!")
return redirect("main:homepage")
def login_request(request):
if request.method == "POST":
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
messages.info(request, f"You are now logged in as {username}")
return redirect("main:homepage")
else:
messages.error(request, "Invalid username or password")
else:
messages.error(request, "Invalid username or password")
form = AuthenticationForm()
return render(request,
"main/login.html",
{"form":form})
You can achieve your goal without external libs by subclassing LoginForm from django.contrib.auth
Please see this answer for code examples and a more detailed explanation. Using context processors you can also add the recaptcha public key into login.html template.
You should post your views.pyso I could help you better, but using common Django sense, you should render the login.html file with FormWithCaptcha as a context variable, named recaptcha, for example and then in your login file call it like {{recaptcha}} wherever you need it. But again, post your views file if your issue is not yet fixed.
def login_request(request):
if request.method == "POST":
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
messages.info(request, f"You are now logged in as {username}")
return redirect("main:homepage")
else:
messages.error(request, "Invalid username or password")
else:
messages.error(request, "Invalid username or password")
form = AuthenticationForm()
recaptcha = FormWithCaptcha()
return render(request,
"main/login.html",
{"form":form, "recaptcha": recaptcha})