How can i Register and Login In The Same Page in Django? - 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>

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})

Django is not redirecting to profile page after login. What is wrong with my code?

This is my views.py
def LoginPage(request):
username = password = ''
next = ""
if request.GET:
next = request.GET['next']
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username = username, password = password)
if user is not None:
login(request, user)
if next == "":
return HttpResponseRedirect('/Profile/')
else:
return HttpResponseRedirect(next)
context = {}
return render(request, 'login.html', context)
This is my template:
{% if next %}
<form class="" action='/Profile/' method="post">
{%else%}
<form class="" action="/Login/" method="post">
{% endif %} {% csrf_token %}
<p class="login-field-title"><strong>Username*</strong></p>
<input type="text" class="form-control col-lg-10 log-inp-field" placeholder="Enter Username" required>
<p class="login-field-title"><strong>Password*</strong></p>
<input type="password" class="form-control col-lg-10 log-inp-field" placeholder="Enter Password" required> {% for message in messages %}
<p id="messages">{{message}}</p>
{% endfor %}
<button type="submit" class="btn btn-dark btn-lg col-lg-10 log-btn">Log In</button>
</form>
I don't understand what I'm doing wrong. Some help would be very appreciated. Even after logging in with a registered user it is not redirecting me to the desired page and when i change the action, even with the un registered user it redirects me to the next page.
Add this to your settings file
LOGIN_REDIRECT_URL = 'YOUR_PROFILE_URL'

django custom login view (login as guest)

i am making an ecommerce and i have a checkout view in that view i have three forms : a login form a guest login form and a billing address form so basically if a user is logged in normally or as guest i am displaying the billing address form in the template 'checkout.html' otherwise i display the login form and the guest login form but these two forms are handled in different views checkout_login and guest_checkout_login so my question is : is it safe to do so ?
this is the checkout template :
{% if not billing_profile %}
<form method="post" action="{% url 'login_page' %}"> {% csrf_token %}
<input type="hidden" name="next" value="{{ request.build_absolute_uri }}">
{{ form }}
<button type="submit" class="btn btn-default">Submit</button>
</form>
<form method="post" action="{% url 'guest_login_page' %}"> {% csrf_token %}
<input type="hidden" name="next" value="{{ request.build_absolute_uri }}">
{{ guest_form }}
<button type="submit" class="btn btn-default">Submit</button>
</form>
{% else %}
<h1>checkout</h1>
billing profile:{{billing_profile}} </br>
<form method="post" action=".">{% csrf_token %}
{{ adress_form }}
<button type="submit" class="btn btn-default">Submit</button>
</form>
{% endif %}
{% endblock %}
this is the chekout_login view:
def login_page(request):
form = LoginForm(request.POST or None)
next_ = request.POST.get('next')
if request.method == 'POST':
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
if is_safe_url(next_, request.get_host()):
guest_email_id = request.session.get('guest_email_id')
if guest_email_id:
del request.session['guest_email_id']
return redirect(next_)
else:
return redirect("/")
else:
form = LoginForm()
return redirect("/")
if i am doing any mistake please tell me

Login through dropdown menu in Django

I have struggle with django's login. So i want user to login through my dropdown menu, but my LoginForm doesnt show up. I dunno what to do
forms.py
class LoginForm(forms.Form):
username = forms.CharField(label=(u'Username'),widget = forms.TextInput(attrs = {'placeholder': 'Username'}))
password = forms.CharField(max_length=16, label=(u'Password'),
widget = forms.PasswordInput(attrs = {'placeholder': 'Password (min 8 chrct)'}, render_value = False),
validators=[MinLengthValidator(8, message = 'Password must be at least 8 characters')])
views.py
def LoginRequest(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile/')
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
tutor = authenticate(username=username, password=password)
if tutor is not None:
login(request, tutor)
return HttpResponseRedirect('/profile/')
else:
return render_to_response('/', {'form': form}, context_instance=RequestContext(request))
else:
return render_to_response('/', {'form': form}, context_instance=RequestContext(request))
else:
form = LoginForm()
context = {'form': form}
return render_to_response('/', {'form': form}, context_instance=RequestContext(request))
navbar.html
<a class="dropdown-toggle" href="#" data-toggle="dropdown">Login <strong class="caret"></strong></a>
<div class="dropdown-menu" style="padding: 15px; padding-bottom: 0px;">
<form action="" method="POST">
{% csrf_token %}
{% if form.errors %}
{{ form.errors}}
{% endif %}
{{form}}
<input class="btn btn-primary" type="submit" value="Login" />
</form>
</div>
It looks like your issue is not with Django but with your bootstrap drop down.
Wrap your drop down html in a <div class="dropdown">.
<div class="dropdown">
<a class="dropdown-toggle" href="#" data-toggle="dropdown">Login <strong class="caret"></strong></a>
<div class="dropdown-menu" style="padding: 15px; padding-bottom: 0px;">
<form action="" method="POST">
{% csrf_token %}
{% if form.errors %}
{{ form.errors }}
{% endif %}
{{ form }}
<input class="btn btn-primary" type="submit" value="Login"/>
</form>
</div>
</div>

CSRF token missing or incorrect in signup

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?