I am creating a password reset form after a user is authenticated they are presented with the reset page where they can enter the username and new password. However once they have set this new data and click the submit button the data is shown in the url of the next page that is shown. How do I need to configure my application to not do this?
views.py
def index(request):
if request.method == 'POST':
form = login(request.POST)
if form.is_valid():
user = form.cleaned_data['username']
passw = form.cleaned_data['password']
if user and passw:
#try the post to login
r=validateUser(user,passw)
if r:
formReset = reset()
return render(request, 'loggedin.html',{'form' : formReset})
else:
return render(request, 'index.html',{'form' : form})
else:
form = login()
loggedin(request)
return render(request, 'index.html', {'form' : form})
def loggedin(request):
if request.method == 'GET':
form = reset(request.GET)
if form.is_valid():
user = form.cleaned_data['username']
newpassword = form.cleaned_data['newpassword']
confirmnewpassword = form.cleaned_data['confirmnewpassword']
if newpassword == confirmnewpassword:
#passwords match
val = resetpassword(user,newpassword)
else:
return render(request, 'loggedin.html', {"message" : 'Passwords do not match', 'form' : form})
else:
return render(request, 'loggedin.html',{'form' : form})
forms.py
from django import forms
class login(forms.Form):
#class used for the login prompt
username = forms.CharField(widget=forms.TextInput(attrs={'class' : 'btn btn-lg btn-default'}),label='')
password = forms.CharField(widget=forms.PasswordInput(attrs={'class' : 'btn btn-lg btn-default'}),label='')
class reset(forms.Form):
#class used for inputs to reset password
username = forms.CharField(widget=forms.TextInput(attrs={'class' : 'btn btn-default'}),label='User Name')
newpassword = forms.CharField(widget=forms.PasswordInput(attrs={'class' : 'btn btn-default'}),label='New Password')
confirmnewpassword = forms.CharField(widget=forms.PasswordInput(attrs={'class' : 'btn btn-default'}),label='Confirm Password')
loggedin.html
{% extends "base.html" %}
{% load staticfiles %}
{% block content %}
<form action="/" method="GET">
{% csrf_token %}
<div class="container">
<h1>You are logged in</h1>
{{ message }} </br>
{{ form.as_p }}
<input type="submit" class="btn btn-lg btn-default" action="submit" value="Reset">
</div></form>{% endblock %}
That's how a GET action works. You should be using POST for this anyway.
Related
I have a view like:
def some_view(request, page_url):
form = UserTicketForm(request.POST)
if request.method == 'POST':
if form.is_valid():
first_name = request.POST.get('first_name')
ticket_text = request.POST.get('ticket_text')
data = dict(
form=UserTicketForm,
)
return render(request, 'front/some_page.html', data)
and in HTML page it has:
{% csrf_token %}
{% bootstrap_form form %}
{% block submit %}
<div class="button_holder">
<button type="submit" name="register-submit" class="btn btn-primary" value="send">
submit
</button>
</div>
{% endblock %}
each time I refresh the page, it resubmits the last submitted form. how can fix this issue?
You need to redirect to a different url after the form is submitted and saved
if form.is_valid():
first_name = request.POST.get('first_name')
ticket_text = request.POST.get('ticket_text')
return HttpResponseRedirect(reverse('some_url'))
Write Like this
def some_view(request, page_url):
if request.method == 'POST':
form = UserTicketForm(request.POST)
if form.is_valid():
first_name = request.POST.get('first_name')
ticket_text = request.POST.get('ticket_text')
data = dict(
form=UserTicketForm,
)
return render(request, 'front/some_page.html', data)
I was using django-registration-redux for my registration backend earlier and everything worked fine. I then decided to change the registration backend to django's default registration django.contrib.auth and the registration has been working fine but the login doesn't work. However, the thing is, only my superuser acoount can login, every other user can't login, both the regular users and the ones with staff clearance. It keeps giving me invalid username/password error.
Below is the login section of my views.py
def signin(request):
if request.user.is_authenticated:
return HttpResponseRedirect("/")
form = LoginForm()
errors = None
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
username = username.lower()
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
login(request, user)
if user.is_staff:
return redirect('sweet:vendor_index')
else:
return redirect('sweet:index')
else:
errors = "Invalid Username or Password"
return render(request, 'myregistration/signin.html', {'form':form, 'errors':errors})
Below is my signin.html
{% extends "base.html" %}
{% block title %}sign in{% endblock %}
{% block content %}
<h1>Sign in</h1>
{% if form.errors %}
<p class="error">Please correct the errors below:</p>
{{ errors }}
{% endif %}
<form method="post" action="{% url 'myregistration:signin' %}">{% csrf_token %}
<dl>
<dt><label for="id_username">Username:</label>{% if form.username.errors %} <span class="error">{{ form.username.errors|join:", " }}</span>{% endif %}</dt>
<dd>{{ form.username }}</dd>
<dt><label for="id_password">Password:</label>{% if form.password.errors %} <span class="error">{{ form.password.errors|join:", " }}</span>{% endif %}</dt>
<dd>{{ form.password }}</dd>
<dt><input type="submit" value="sign in" /></dt>
</dl>
</form>
<p>Forgotten password? Click here to reset password</p>
{% endblock %}
{% block content-related %}
<p>If you don't have an account, you can <a href="/accounts/register/">sign
up</a> for one.
{% endblock %}
And finally, my urls.py
from django.conf.urls import url
from myregistration import views
from django.contrib.auth import views as auth_views
app_name = 'myregistration'
urlpatterns = [
url(r'^register_vendor/', views.register_vendor, name='register_vendor'),
url(r'^register_customer/', views.register_customer, name='register_customer'),
url(r'^email_confirm/', views.email_confirm, name='email_confirm'),
url(r'^password_change/$', views.password_change, name='password_change'),
url(r'^password_reset/$', auth_views.password_reset, name='password_reset'),
url(r'^password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'),
url(r'^signin/', views.signin, name='signin'),
url(r'^logout/', views.logout, name='logout'),
url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate, name='activate'),
]
Below is my registration method
def register_customer(request):
registered = False
if request.method == 'POST':
customerform = CustomerSignUpForm(data=request.POST)
if customerform.is_valid():
customer = customerform.save(commit=False)
# Remeber to hash password again
customer.set_password(customer.password)
customer.is_active = False
customer.is_staff = False
customer.save()
text_content = "Account Activation Email"
mail_subject = "Activate your Juggernut account"
template_name = "myregistration/account_activate.html"
from_email = customerform.cleaned_data.get('email')
recipients = [customer.email]
kwargs = {
"uidb64":urlsafe_base64_encode(force_bytes(customer.pk)).decode(),
"token":account_activation_token.make_token(customer)
}
activation_url = reverse("myregistration:activate", kwargs=kwargs)
activation_url = "{0}://{1}{2}".format(request.scheme, request.get_host(), activation_url)
context = {
'customer':customer,
'activation_url':activation_url
}
html_content = render_to_string(template_name, context)
email=EmailMultiAlternatives(mail_subject, text_content, from_email, recipients)
email.attach_alternative(html_content, 'text/html')
email.send()
return redirect("myregistration:email_confirm")
registered=True
else:
print(customerform.errors)
else:
customerform = CustomerSignUpForm()
return render(request, 'myregistration/register_customer.html', {'customerform':customerform, 'registered':registered})
As you can see, in your views you have a form class to your view form = LoginForm(), but in your template you're not rendering this form and you won't be able to validate it and the line if form.is_valid(): will always return False.
You have two options, render the form class or change:
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
username = username.lower()
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
login(request, user)
if user.is_staff:
return redirect('sweet:vendor_index')
else:
return redirect('sweet:index')
else:
errors = "Invalid Username or Password"
to:
username = request.POST.get('username')
username = username.lower()
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
if user.is_staff:
return redirect('sweet:vendor_index')
else:
return redirect('sweet:index')
Probably the LoginForm class take another parameters and cannot be validated
I am working width Django now. But I don't make sense about that.
I want to get id and password from the form and check if the password from form is correct to compare with the password of database.
Following are the my codes.
Please help me.
models.py
from django.db import models
class Doctor(models.Model):
doctor_id = models.CharField(max_length=16, primary_key=True)
clinic_id = models.ForeignKey(Clinic)
doctor_email = models.CharField(max_length=64)
doctor_password = models.CharField(max_length=32)
doctor_name = models.CharField(max_length=32)
create_date = models.DateTimeField(auto_now_add=True)
modify_date = models.DateTimeField(auto_now=True)
forms.py
from django import forms
from .models import Doctor
class LoginForm(forms.Form):
class Meta:
model = Doctor
fields = ('doctor_id', 'doctor_password',)
views.py
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponse
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from .forms import LoginForm
from .models import Doctor
#ensure_csrf_cookie
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
_id = form.cleaned_data['doctor_id']
_password = form.cleaned_data['doctor_password']
b = Doctor.objects.all().filter(doctor_id=_id)
if _password is doctor_password:
login(request, user)
return HttpResponse('Authenticated successfully')
else:
return HttpResponse('Disabled account')
else:
return HttpResponse('Invalid login')
else:
form = LoginForm()
return render(request, 'apiv1/login.html', {'form': form})
login.html
{% extends "base.html" %}
{% load staticfiles%}
{% block title%}Title{% endblock %}
{% block remoshincss %}/static/css/style.css{% endblock %}
{% block content %}
<div class="container">
<div align="center" class="imgtop"><img id="profile-img" class="profile-img-card" src="/static/img/remoshinlogo.png" /></div>
<div class="card card-container">
<p id="profile-name" class="profile-name-card"></p>
<form class="form-signin" action="{% url 'login' %}" method="post">{% csrf_token %}
<input type="user" id="userid" name="userid" class="form-control inputUser" placeholder="USER-ID" autofocus>
<input type="password" id="password" name="password" class="form-control inputPassword" placeholder="PASSWORD">
<input type="hidden" name="next" value="{{ next }}" />
<br>
<div align="center"><button style="width: 200px;" class="btn btn-lg btn-primary btn-block btn-signin" type="submit"><font color="#708090">Login</font></button></div>
</form>
</div>
</div>
{% endblock %}
Import check_password
from django.contrib.auth.hashers import check_password
check password
pass_ = check_password(_password, b.doctor_password)
if pass_ is False:
return HttpResponse('Invalid login')
Code:
#ensure_csrf_cookie
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
_id = form.cleaned_data['doctor_id']
_password = form.cleaned_data['doctor_password']
docter = Doctor.objects.filter(doctor_id=_id).last()
if docter is None:
return HttpResponse('Invalid login')
pass_ = check_password(_password, docter.doctor_password)
if pass_ is False:
return HttpResponse('Invalid login')
return HttpResponse('Authenticated successfully')
else:
return HttpResponse('Invalid login')
else:
form = LoginForm()
return render(request, 'apiv1/login.html', {'form': form})
LoginForm in forms.py
class LoginForm(forms.Form):
username = forms.CharField(label='Username', max_length=30)
password = forms.CharField(
label='Password',
widget = forms.PasswordInput(),
)
def clean_username(self):
username = self.cleaned_data['username']
try:
User.objects.get(username = username)
user.objects.get(username = username)
except ObjectDoesNotExist:
raise forms.ValidationError('Invalid Username or Password!')
def clean_password(self):
password1 = self.cleaned_data['password']
username = self.cleaned_data['username']
user = User.objects.get(username = username)
password2 = user.password
if user.check_password(password1):
return password1
else:
raise forms.ValidationError('Invalid Username or Password!')
login_page in views.py
def login_page(request):
template = get_template('login_page.html')
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return HttpResponseRedirect('/user/username')
else:
form = LoginForm()
variables = RequestContext(request, {
'form': form
})
return render_to_response('login_page.html', variables)
login_page.html template
{% extends "base.html" %}
{% block title %}User Login{% endblock %}
{% block head %}User Login{% endblock %}
{% block content %}
{% if form.has_errors %}
<p>Your username and password didn't match.
Please try again.</p>
{% endif %}
<form method="post" action=".">
<p><label for="id_username">Username:</label>
{{ form.username }}</p>
<p><label for="id_password">Password:</label>
{{ form.password }}</p>
<input type="submit" value="login" />
<input type="hidden" name="next" value="/" />
</form>
{% endblock %}
The above view when called from localhost:8000/login/ results in a User matching query does not exist error. I can't exactly sense the reason. I am using the default authentication system used by Django 1.8.
I am new to Django. Please help me out.
That exception comes from :
user = User.objects.get(username = username)
in clean_password. You already know how to fix this error, you have done it in your clean_username by sorrounding that query by try, except to avoid this error.
I have been trying to do my login and register on the sane template, but have been having issues with it. please i need some help. Below are my codes:
views.py:
def register_user(request):
if request.user.is_authenticated():
return redirect('home')
if request.method == 'POST':
rform = RegistrationForm(request.POST)
if rform.is_valid():
user = User.objects.create_user()
user.username = rform.cleaned_data['email']
user.set_password(rform.cleaned_data['password'])
user.first_name = rform.cleaned_data['first_name']
user.last_name = rform.cleaned_data['last_name']
user.email = rform.cleaned_data['email']
user.gender = rform.cleaned_data['gender']
user.save()
loggedin_user = authenticate(email = rform.cleaned_data['email'],
password = rform.cleaned_data['password'])
if user is not None:
login(request, loggedin_user)
return redirect('home')
else:
return render(request, 'accounts/access.html', {'rform': RegistrationForm()})
else:
return render(request, 'accounts/access.html', {'rform': RegistrationForm()})
else:
form = RegistrationForm()
return render(request, 'accounts/access.html', {'rform':form})
def login_now(request, *args, **kwargs):
if request.user.is_authenticated():
return redirect('home')
if request.method == "POST":
form = AuthenticationForm(request.POST)
if form.is_valid():
username = form.cleaned_data['email']
password = form.cleaned_data['password']
user = authenticate(username = form.cleaned_data['email'], password = password)
if user is not None:
login(request, user)
return redirect('home')
else:
return render(request, 'accounts/access.html', {'form': AuthenticationForm(), 'rform':RegistrationForm(), 'next':reverse_lazy('home')})
else:
return render(request, 'accounts/access.html', {'form': AuthenticationForm(), 'rform':RegistrationForm(), 'next':reverse_lazy('home')})
else:
return render(request, 'accounts/access.html', {'form': AuthenticationForm(), 'rform':RegistrationForm(), 'next':reverse_lazy('home')})
forms.py:
CHOICES = [
('Male', "Male"),
('Female', "Female"),
]
class RegistrationForm(forms.Form):
first_name = forms.CharField(max_length=25, widget=forms.TextInput(attrs={'placeholder': 'First name'}))
last_name = forms.CharField(max_length=25, widget=forms.TextInput(attrs={'placeholder': 'Last name'}))
email = forms.EmailField(max_length=50, widget=forms.TextInput(attrs={'placeholder': 'Email'}))
password = forms.CharField(max_length=25, widget=forms.PasswordInput(attrs={'placeholder': 'Password'}))
password1 = forms.CharField(max_length=25, widget=forms.PasswordInput(attrs={'placeholder': 'Password Confirm'}), label=("Re-type Password"))
gender = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect(attrs={'placeholder': 'Gender'}))
class Meta:
model = ('User',)
def clean_email(self):
data = self.cleaned_data['email']
if User.objects.get(email=data):
raise forms.ValidationError('A user with this email already exist. You may recover the password with a password reset')
return data
def clean_password(self):
password = self.cleaned_data.get("password")
password1 = self.cleaned_data.get("password1")
if password1 and password and password1 != password:
raise forms.ValidationError(
self.error_messages['password_mismatch'],
code='password_mismatch',
)
return password
access.html:
<div id = 'signup'>
<form id="post-form" action="{% url 'register' %}" method="POST">
{% csrf_token %}
<h3>REGISTER</h3>
<div>
{%for field in rform%}
<div style="margin-top:10px;">
{{field.label_tag}}<br/> {{field}}
{%if field.errors%} <br/>{{field.errors}} {%endif%}
</div>
{%endfor%}
</div>
<input type="submit" value="Register" class='sub' id='register'/>
</div>
<div id='login'>
{% if form.errors %}
{{ form.non_field_errors}}
{% endif %}
<form action='{% url 'login' %}' method='post' id ='signIn'>
{% csrf_token %}
<h3>SIGN IN</h3>
<p><label>Email:</label><br/>
{{ rform.email }}
{{ rform.email.errors }}</p>
<p><label>Password:</label><br/>
{{ rform.password }}
{{ rform.password.errors }}</p>
<p><input type="submit" value="login" id='submit' class='sub' /><br>
<input type="hidden" name="next" value="{% url 'home' %}" />
</form>
</div>
I try to register with the above and all i always get, is a redirection, please i need help.
Thanks in advance.
Please note, i extended the user profile that's why i have the gender in my registration form.
In your code, you are not comparing the right parameters
loggedin_user = authenticate(email = rform.cleaned_data['email'],
password = rform.cleaned_data['password'])
if user is not None:
login(request, loggedin_user)
return redirect('home')
You are checking an None variable, not the one returned by the authenticate ! if loggedin_user is not None is the correct check.
Check the example on the official doc.
You need to send the validated form rform so you can show the feedback (errors) to the user, you are sending a new form after the validation RegistrationForm()!
Also try to identify the source of the problem, you are posting your hole code but you don't know where the problem comes from, at least do some debugging ;) !