CSRF token missing or incorrect in signup - django

I'm trying to add a signup function to my website, this is what I have done so far...
added {% csrf_token %} in home.html
use render instead of rendor_to_response
added the middleware 'django.middleware.csrf.CsrfViewMiddleware'
home.html:
<div class="panel right">
<p>
<form action="/signup" method="post">
{% csrf_token %}
{% for field in user_form %}
{{ field }}
{% endfor %}
<input type="submit" value="Create Account">
</form>
</p>
</div>
Signup method in views.py
def signup(request):
user_form = UserCreateForm(data=request.POST)
if request.method == 'POST':
if user_form.is_valid():
username = user_form.clean_username()
password = user_form.clean_password2()
user_form.save()
user = authenticate(username=username, password=password)
login(request, user)
return render(request,'blog.html')
else:
return render(request,'index.html')
return redirect('/')
What's wrong with my code?

Related

Unable to login using Django

This is my login view
def login_request(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:
form = login(request, user)
messages.success(request, f' welcome {username} !!')
return redirect('index')
else:
messages.info(request, f'Unable to Login now')
form = AuthenticationForm()
context = {'form':form}
return render(request, "BizzyCardApp/log-in.html", context)
and this is the log-in.html file
{% extends "BizzyCardApp/base.html" %}
{% block content %}
{% load crispy_forms_tags %}
<br>
<br>
<br>
<br>
<br>
<div class="container center oswald" id="grad" style="border-radius: 10%; width: 300px;">
<br>
<form>
<table class="table table-borderless table-responsive container">
<tbody>
<tr>
<div class="mb-3 mt-3">
<form method="POST">
{% csrf_token %}
{% for field in form %}
<div>
<p>{{ field.label }}: <br> {{ field }}</p>
{% for error in field.errors %}
<small style="color: red">{{ error }}</small>
{% endfor %}
</div>
{% endfor %}
</form>
</div>
</tr>
<tr>
<div class="d-flex justify-content-center">
<button type="submit" class="btn btn-light center text-center">Submit</button>
</div>
</tr>
</tbody>
</table>
</form>
<div class="text-center">
<a href="/sign-up/" class="link-dark">
Don't have an account? Sign Up
</a>
</div>
</div>
{% endblock %}
Once I hit the Submit button, it's supposed to redirect me to the index page but all that happens is that the GET request is done but there is no response from the backend to redirect. It just stays on the same page and the URL changes to
http://127.0.0.1:8000/login/?csrfmiddlewaretoken=0rkrC5wOe8LDQc9x0s0Zdag45PXRZixJAYaQns3dod58QhUL6OdmTEvZMYdRNTfq&username=tushar&password=abcd123*
Try this login view:
def login_request(request):
if request.method == 'GET':
if request.user.is_authenticated:
return redirect('/index/')
if request.method=='GET':
form = loginForm(request.POST)
if form.is_valid():
user=authenticate(username=form.cleaned_data['username'],
password=form.cleaned_data['password'])
if user:
print('user',user)
login(request,user)
return redirect('/index/')
else:
print('Not authenticated')
elif request.method=='GET':
if request.user.is_authenticated:
return redirect('/index/')
form=loginForm()
return render(request,'users/login.html',{'form':form})
In forms.py:
Add this:
class CustomAuthenticationForm(AuthenticationForm):
def confirm_login_allowed(self, user):
if not user.is_active or not user.is_validated:
raise forms.ValidationError('There was a problem with your login.', code='invalid_login')
And in login view, change AuthenticationForm to CustomAuthenticationForm. And import it in login view using below code.
from .form import CustomAuthenticationForm
Finally figured out the answer. The method for the tag wasn't given as POST.
The tag was just and not
The backend kept on getting GET requests instead and that's why the code wasn't working.
This is the Login method code I'm using now
def Login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username = username, password = password)
if user is not None:
form = auth_login(request, user)
messages.success(request, f' welcome {username} !!')
return redirect('/')
else:
messages.info(request, f'account done not exit plz sign in')
form = AuthenticationForm()
return render(request,'BizzyCardApp/log-in.html',{'form':form})

How can i Register and Login In The Same Page in Django?

i would like to have both my login form and my registration form on the same page within the same template, so i would like to have them under one view function but i am not too sure on how i can do that, here is my code.
Views.py
def register(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST) == "Register"
if form.is_valid():
form.save()
user = form.cleaned_data.get('username')
messages.success(request,"Account was Created for " + user)
context = {'form':form}
return render(request,'login.html',context)
def login(request):
if request.method == "POST":
if request.POST.get('submit') == 'Login':
username = request.POST.get('username')
password = request.POST.get('password1')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request,user)
return redirect('shop.html')
else:
messages.info(request, 'Wrong Username or password')
context = {}
return render(request,'shop.html',context)
login.html
<div class="formBx">
<form method="POST",name="Login",value="Login">
{% csrf_token %}
<h2>Sign In</h2>
{{form.username}}
{{form.password1}}
<input type="submit" name="submit" value="Login">
<p class="signup">Don't have an Account?Sign Up.</p>
{% for message in messages %}
<p id="messages">{{message}}</p>
{% endfor %}
</form>
</div>
</div>
<div class="user signUpBx">
<div class="formBx">
<form method="POST" value="Register">
{% csrf_token %}
<h2>Create an account</h2>
{{form.username}}
{{form.email}}
{{form.password1}}
{{form.password2}}
<input type="submit" name="submit" value="Register">
<p class="signup">Already Have an Account?Sign In.</p>
{% for message in messages %}
<p id="messages">{{message}}</p>
{% endfor %}
</form>
</div>
I'm getting AttributeError at /login/
'bool' object has no attribute 'is_valid' error right now.
You can use two separate forms for login and register in same view. Here is an example:
def register_login(request):
if "register" in request.method == "POST": #add the name "register" in your html button
..... your registration code
if "login" in request.method == "POST": #add the name "login" in your html button
..... your login code
**html**
<form>
{%csrf_token%}
.... your registration form
<button type="submit" name="register">register</button>
</form>
<form>
{%csrf_token%}
.... your login form
<button type="submit" name="login">register</button>
</form>

Login anonymous behaviour even though the user exist it shows invalid user

views.py
'
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("inactive")
else:
return HttpResponse("Someone tried to login and failed")
else:
return render(request, 'basic_app/login.html', {})
login.html
{% extends 'basic_app/base.html' %}
{% block content %}
<div class="jumbotron">
<form action="{% url 'basic_app:user_login' %}" method="POST">
{% csrf_token %}
<label for="username">USERNAME</label>
<input type = "text" name="Username" placeholder="enter">
<label for="password">Password</label>
<input type = "password" name="password" placeholder="PASSWORD">
<input type = "submit" name ="" value = "LOGIN">
</form>
</div>
{% endblock %}
In django admin the users are registered and are in database but when i login it shows Someone tried to login and failed .
I have to submit this by midnight need help noob here.

login with forms doesn't work

so I'm making a login page with forms, the problem is it doesn't work :D
this is my form
forms.py
from django.contrib.auth.models import User
from django import forms
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'password',]
my views.py
def user_login(request):
if request.method == 'POST':
login_form = UserForm(request.POST)
if login_form.is_valid():
username = login_form.cleaned_data.get('username')
raw_password = login_form.cleaned_data.get('password')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('restricted')
else:
login_form = UserForm()
return render(request, 'userlogin.html', {'login_form': login_form})
and my html
<h2>Login</h2>
<form method="post">
{% csrf_token %}
{{ login_form.username }}
<br>
{{ login_form.password }}
<br>
<button type="submit">Login</button>
</form>
the restricted is a html that checks which user is logged in. and it works fine
i'm not sure why it isn't working cuz it keeps redirecting me to the loginuser.html page instead of redirecting me to restricted page which only appears if a user is logged in.
You need to add more details but here is a step by step guide to login users:
forms.py:
from django.contrib.auth import authenticate, get_user_model
User = get_user_model()
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField()
def clean(self, *args, **kwargs):
username = self.cleaned_data.get("username")
password = self.cleaned_data.get("password")
user_obj = User.objects.filter(username=username).first()
if not user_obj:
raise forms.ValidationError("Invalid credentials")
else:
if not user_obj.check_password(password):
raise forms.ValidationError("Invalid credentials")
return super(LoginForm, self).clean(*args, **kwargs)
and in your views.py:
from django.contrib.auth import login
from .forms import LoginForm # or where you have the LoginForm
User = get_user_model()
def user_login(request):
form = LoginForm(request.POST or None)
if not request.user.is_authenticated:
if form.is_valid():
username_ = form.cleaned_data.get('username')
user_obj = User.objects.get(username__iexact=username_)
login(request, user_obj)
return #something
else:
# show an error or etc
...
else:
# user is authenticated before and he is in.
...
and your template.html:
<form action="" method="post">
{% csrf_token %}
<input type="text" name="username">
<hr>
<input type="password" name="password">
<hr>
<button type="submit">Login</button>
</form>
Note:
you can use django to render the form but you need to make some changes on form fields like password (adding PasswordInput widget)
Add block with form errors to your template
<h2>Login</h2>
<form method="post">
<!-- form errors -->
{% if login_form.errors %}
{% for field in login_form %}
{% for error in field.errors %}
<strong>{{ error|escape }}</strong>
{% endfor %}
{% endfor %}
{% for error in login_form.non_field_errors %}
<strong>{{ error|escape }}</strong>
{% endfor %}
{% endif %}
<!-- form errors -->
{% csrf_token %}
{{ login_form.username }}
<br>
{{ login_form.password }}
<br>
<button type="submit">Login</button>
</form>

Use next parameter for login_required views

My method to redirect a url after login, work well but the code of the template is not very sexy, can I have yours please ?
my function in views.py
def connexion(request):
error = False
n=request.GET.get('n')
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)
if request.GET.get('n'):
return redirect(request.GET['n'])
else:
return redirect(accueil)
else:
error = True
else:
form = ConnexionForm()
return render(request, 'blog/connect_user.html', locals())
my template:
<h1>Se connecter</h1>
{% if error %}
<p><strong>Utilisateur inconnu ou mauvais mot de passe.</strong></p>
{% endif %}
{%if n %}
<form method="post" action="{% url 'connexion' %}?n={{ n }}">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Se connecter" />
</form>
{% else %}
<form method="post" action="{% url 'connexion' %}">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Se connecter" />
</form>
{% endif %}
my decorator:
#login_required(redirect_field_name='n')
Why not just:
<input type="hidden" name="n" value="{{ n }}">
And in the view:
n = request.REQUEST.get('n', '')
Using request.REQUEST you can get n from either using POST or GET so you can still link to a URL like /login?n=/foo/bar. You can also do POST/REDIRECT/GET without problems.