I'm particularly new to django and still in the learning process.
I have this code where it would have the user input any text into the field and once the user hits the submit button it would grab the text they inputted and look for it in the django database for that item. It's able to do what I want, except when there are no users with that username. I don't know where I would do an if statement, or a work around for that.
views.py
from .forms import RequestPasswordResetForm
from django.contrib.auth.models import User
def request_password(request):
next = request.POST.get('next', '/')
if request.method == "POST":
user = request.POST['passUsername']
users = User.objects.get(username=user)
form = RequestPasswordResetForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, 'Request has been sent! Admin will be with you shortly.')
return HttpResponseRedirect(next)
you can handle it within the try catch block where get method will raise exception (DoesNotExist) if then object is not present in the DB.
def request_password(request):
next = request.POST.get('next', '/')
try:
if request.method == "POST":
username = request.POST['passUsername']
user = User.objects.get(username=username)
form = RequestPasswordResetForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, 'Request has been sent! Admin will be with you shortly.')
return HttpResponseRedirect(next)
except User.DoesNotExist:
messages.error(request, 'Invalid Username')
I would use an if statement alongside the function 'exists()'. It would look something like this:
username = request.POST['passUsername']
if (User.objects.exists(username = username):
user = User.objects.get(username = username)
else:
# Throw error
Also, be careful with your variable naming :)
Related
Ive this Django Login and Registration form
but the registration form is fetching in database auth_user but not in helloworld_register
This is my Registration code
def Register(request):
if request.method =='POST':
username=request.POST['username']
email=request.POST['email']
first_name=request.POST['first_name']
last_name=request.POST['last_name']
password1=request.POST['password1']
password2=request.POST['password2']
if User.objects.filter(email=email).exists():
messages.info(request, 'uh oh..:( This Email is Already Taken ')
print('emailtaken')
return redirect('/Register')
elif User.objects.filter(first_name=first_name).exists():
messages.info(request, 'uh oh..:( This Name is Already Taken ')
print('Name taken')
return redirect('/Register')
user=User.objects.create_user(username=username, email=email,first_name=first_name,last_name=last_name,password=password1)
user.save();
messages.info(request, 'Registration complete Login to continue ..:)')
print('user created')
return redirect('/LOGIN')
return render(request, 'Register.html')
And this is my Login Code
def LOGIN(request):
if request.method=='POST':
email=request.POST['email']
password1=request.POST['password1']
user=auth.authenticate(email=email,password1=password1)
#user.save();
if user is not None:
auth.LOGIN(request,user)
return redirect('LOGIN')
else:
messages.info(request, 'mmm :( Invalid Credentials ')
return redirect('LOGIN')
Even though if i try Logging in with registered credentilals im unable to login
First of all, I would like to correct the terminology. Both snippets you provided are not Forms but Views. And 'auth_user' is not a database, its a table, as I will assume for 'helloworld_register'.
Related to your first problem, it seems that you are using Django's default User model. And by default this model uses 'auth_user' both to create and retrieve objects.
If you want to change defaults, you are going to need a custom user model, in fact here is a quote from Django documentation about such:
If you’re starting a new project, it’s highly recommended to set up a
custom user model, even if the default User model is sufficient for
you. This model behaves identically to the default user model, but
you’ll be able to customize it in the future if the need arises
As for your second issue, take a look at this example. I see a few errors in your snippet, such as:
user=auth.authenticate(email=email,password1=password1)
# there is no field password1 in the User model.
if user is not None:
auth.LOGIN(request,user) # Wrong call do login() method
return redirect('LOGIN') # You want to redirect to some other place
Therefore you are probably looking for something like this:
(Also, do not ignore good practices such as views names in snake_case)
from django.contrib.auth import authenticate, login
from django.shortcuts import redirect
def my_view(request):
email= request.POST['email']
password = request.POST['password1']
user = authenticate(request, email=email, password=password)
if user is not None:
login(request, user)
redirect('/your/app/index')
else:
messages.error(request, 'mmm: Invalid Credentials.')
redirect('/back/to/login')
I am trying to create a login form in Django. In that form, there are 2 fields, username, and password for login. Now I have used lower() at the time of getting the username. Have a look at the code below. I have used lower() because if an user enters the upper case letter they don't have to face any problem.
Here is the code
def loginForm(request):
page = 'login'
if request.user.is_authenticated: #if user is already login, restricted to visit the login page again
return redirect('home')
if request.method == 'POST':
username = request.POST.get('username').lower()
password = request.POST.get('password')
try:
user = User.objects.get(username=username)
except:
messages.error(request,'User does not exist')
user = authenticate(request,username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
messages.error(request,'Invalid Username or Password')
context = {'page':page}
return render(request, 'base/register_login.html',context)
here is the SS of the error..
Screenshot of the error in the code
Kindly let me know how can I solve this error..
Looks like username isn't in the data when you post data through to your view.
A simple way to fix this error is to set a different default value for username like so:
username = request.POST.get('username', '').lower()
I'm working on a django application. The application has a dashboard. How can i make it so that everytime the user wants to access the dashboard, he/she has to confirm their identity, with the same password they use to log into the same application?
Thank you
#Verify that the USERNAME and PASSWORD combination exist USING THE AUTHENTICATE METHOD,
Views.py:
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
#IN YOUR CASE get the pwd using forms or something,
instance_password = request.post.get('the_pwd_field')
user = authenticate(request, username= request.user.username, password= instance_password)
if user is not None:
# REDIRECT TO THE DASHBOARD
else:
# FAIL CASE SCENARIO
In views.py
from django.contrib.auth.hashers import check_password
form = YourFormForPassword(request.POST or None)
if form.is_valid():
currentpasswordentered = form.cleaned_data.get("try_password")
currentpassword = request.user.password
authenticate_user = check_password(currentpasswordentered, currentpassword)
if authenticate_user:
# REDIRECT TO THE DASHBOARD
else:
#Redirect to other page or keep same login page
If you want, user to enter credentials explicitly before accessing the dashboard, then you have to return the "form" that accepts creds from user, when they try to access the dashboard.
def dashboard_login_view(request):
context = {}
if request.method == 'POST':
form = DashboardLoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('dashboard_login_username').lower()
password = form.cleaned_data.get('dashboard_login_password')
authenticated = check_password(password)
if authenticated:
return HttpResponseRedirect(reverse('dashboard_view'))
else:
messages.error('User is not authenticated.')
return HttpResponseRedirect(reverse('login'))
else:
context['form_one'] = DashboardLoginForm()
return render(request, 'dashboardlogin.html', context)
In my project I have an open signup form, where you can create your Company and all the information bellow it.
After that you can invite people to help you administrate the information of your company. To do that, my idea was to, when the logged user add another admin, I would create the user manually with a fake password and send a Reset Password request to the created email, so he can create his own password. The important code is below:
from django.contrib.auth.forms import PasswordResetForm
...
def create_admin(request):
if request.method == 'POST':
form = AdminForm(request.POST)
if form.is_valid():
email = form.cleaned_data.get("email")
random_pass = User.objects.make_random_password()
user = User(username=email, email=email, password=random_pass)
user.save()
company.add_admin(user)
reset_form = PasswordResetForm({'email': email})
reset_form.save(
email_template_name="rh/password_reset_email.html",
subject_template_name="rh/password_reset_subject.txt")
return redirect('dashboard')
else:
form = AdminForm()
return render(request, 'rh/create_admin.html', {'form': form})
Unfortunately, the above code returns a Exception Type: AttributeError 'PasswordResetForm' object has no attribute 'cleaned_data'
To note:
I already have a fully working reset password feature, using everything from django and custom templates. That's why I'm trying to make this work this way
I would like to customize the email_template_name and subject_template_name, like in my code
thanks in advance
After a bit of dialog in comments I'll leave the response. The two issues were the way the password was being created and the form not being validated. This code should work:
email = form.cleaned_data.get("email")
random_pass = User.objects.make_random_password()
user = User(username=email, email=email)
user.set_password(random_pass)
user.save()
company.add_admin(user)
reset_form = PasswordResetForm({'email': email})
reset_form.is_valid()
reset_form.save(
email_template_name="rh/password_reset_email.html",
subject_template_name="rh/password_reset_subject.txt")
return redirect('dashboard')
(Note that in this code I used the form and not the view, because I'm not sure about what you did with that. If this code doesn't work please correct it.)
I can't seem to work out how to log in users in Django. I'm confused because the documentation tells you explicitely how to do it, but still somehow I must be making a mistake.
The link
https://docs.djangoproject.com/en/dev/topics/auth/default/#django.contrib.auth.login
says
"To log a user in, from a view, use login(). It takes an HttpRequest object and a User object. login() saves the user’s ID in the session, using Django’s session framework."
So I have the following views.py:
def login_view(request):
if request.method == 'GET':
return render(request, 'app/login.htm')
if request.method == 'POST':
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is None:
return HttpResponseRedirect(reverse('error'))
if not user.is_active:
return HttpResponseRedirect(reverse('error'))
# Correct password, and the user is marked "active"
auth.login(request, user)
# Redirect to a success page.
return HttpResponseRedirect(reverse('home'))
def home(request):
contextdict = {}
if request.session.user.is_authenticated():
contextdict['username'] = request.session.user.username
context = RequestContext(request, contextdict )
return render(request, 'app/home.htm', context)
Now, by using print 'qqq' I know for a fact that 'is None' and 'not is_active' have been evaluated to True, and so auth.login is evaluated and the HttpResponseRedirect is returned. I expected everythin to go normally and the user to be logged in, and the user name to be passed as context in the home view. However, Django gives me the following error:
AttributeError at /app/home/
'SessionStore' object has no attribute 'user'
Yeah, I have no idea what I'm doing.
You should use request.user to get user object, not request.session.user.
The data in session is used to retrieve the user object, but the session does not contain the actual user