Django: cannot import name check_password - python

I'm trying to set up a custom user model, but I'm getting the following error on my login page when trying to authenticate a member
ImportError at /members/login/
cannot import name check_password
I know the check_password method exists, but not sure what I'm missing. What am I doing wring when trying to import it?
/members/backends.py
from django.conf import settings
# failing to import check_password here
from django.contrib.auth.models import check_password
from members.models import Member
class EmailAuthBackend(object):
"""Custom authentication backend the allows users to log in using
their email address."""
def authenticate(self, email=None, password=None):
"""Authentication method."""
try:
member = Member.objects.get(email=email)
if member.check_password(password):
return member
except Member.DoesNotExist:
return None
mebers/views.py
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.contrib.auth import login as django_login, authenticate, logout as django_logout
from members.forms.login import LoginForm
from members.forms.register import RegisterForm
def login(request):
"""Login view."""
if request.method != 'POST':
form = LoginForm()
form = LoginForm(data=request.POST)
if form.is_valid():
member = authenticate(email=request.POST.get('email'),
password=request.POST.get('password1'))
if member is not None:
if member.is_active:
django_login(request, member)
return redirect('/')
else:
form = LoginForm()
return render_to_response('members/login.html', {
'form': form
}, context_instance=RequestContext(request))

Try this:
from django.contrib.auth.hashers import check_password

You seem a bit confused about functions and methods. check_password is a method on the auth.models.User class; you can't just import it on its own. And you don't use it anyway; you call the - completely separate - check_password method on your own Member class; there's no need to import anything else there.

Related

Trying to redirect to different page based on login credential provided in DJango

I want to redirect to different pages based on the login credentials in django.
For an example: There are two login provided
If i login with X credentials then i will be redirected to X page. While on same login page if i login with Y credential i will be redirected to correponding Y page.
I tried to put condition in user_login views.py file but this gives me following error.
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'companyDashboard.html' not found. 'companyDashboard.html' is not a valid view function or pattern name.
My views.py file
from django.shortcuts import render
from django.template import RequestContext
from wfhApp.forms import UserForm
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.contrib.auth.decorators import login_required
# Create your views here.
#login_required
def company_dashboard(request):
return render(request, 'wfhApp/company_dashboard.html')
#login_required
def companyDashboard(request):
return render(request, 'wfhApp/companyDashboard.html')
#login_required
def user_logout(request):
logout(request)
return HttpResponseRedirect(reverse('index'))
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:
if user.username == 'prashant':
login(request, user)
return HttpResponseRedirect(reverse('company_dashboard.html'))
elif user.username == 'saurabh':
login(request, user)
return HttpResponseRedirect(reverse('companyDashboard.html'))
else:
return HttpResponse("Account Not Exists")
else:
return HttpResponse("Account Not Active")
else:
print("Someone tried to login and failed")
print("Username: {} and Password: {}".format(username, password))
return HttpResponse("Invalid Login Details")
else:
return render(request, 'wfhApp/login.html')
Thank you for your time and consideration.
Check out urlresolvers docs, to use reverse you must set name in path (urls.py). DonĀ“t add .html extension, use the setted name at urls.py.
from news import views
path('archive/', views.archive, name='news-archive')
Use the setted name.
# using the named URL
reverse('news-archive')
# passing a callable object
# (This is discouraged because you can't reverse namespaced views this way.)
from news import views
reverse(views.archive)

django messages syntaxerror useing f string

i am trying to send a message to the user of my site when they register i used django message import but i did not work
here is my views.py code
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse
from django.shortcuts import render, redirect
from .models import cooking
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login, logout, authenticate
from django.contrib import messages
# Create your views here.
def homepage(request):
return render(request=request,template_name='main/home.html',context={"cooking": cooking.objects.all})
def register(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
username = form.cleaned_data.get('username')
messages.succees(request, f"new account created: {username}")#error on this line
login(request, user)
return redirect("main:homepage")
else:
for msg in form.error_messages:
messages.error(request, form.error_messages[msg])
form = UserCreationForm
return render(request,"main/register.html",context={"form":form })
f-strings have been introduced in Python 3.6, you're probably using a previous version.
If you really wanted to use them you could install future-fstrings but I'm not sure it's worth.
A probably better solution would be to either upgrade Python to a version greather or equal to 3.6 or use one of the alternative formatting options:
"new account created: {}".format(username)
"new account created: %s" % username

View UrlGatewayLogin didn't return an HttpResponse object. It returned None instead

It's a bit repetitive this error is everywhere to find, but I'm a bit confused about what is happening.
I'm trying to pass a token in the url for the user to login like so http://localhost:8000/auth/login/?token=token. After the user is authenticated it should be redirected to dashboard. But I'm getting this error. Can you help me understand what is happening?
View:
import logging
from django.contrib.auth import authenticate, login
from django.core.urlresolvers import reverse, reverse_lazy
from django.shortcuts import render
from django.views.generic import View
from django.http import HttpResponseRedirect, Http404, HttpResponse
from django.contrib.auth.backends import ModelBackend
from rest_framework_jwt.settings import api_settings
from business_accounts.models.my_user import MyUser
logger = logging.getLogger(__name__)
jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
class UrlGatewayLogin(View):
def get(self, request, **kwargs):
page_group = kwargs.get('page_group')
token = request.GET.get('token')
try:
payload = jwt_decode_handler(token)
user = MyUser.objects.get(pk=payload.get('id'))
user.backend = 'django.contrib.auth.backends.ModelBackend'
except MyUser.DoesNotExist:
return None
authenticate(token=token)
logger.warning("User is=%s", user)
print(user)
login(request, user)
return HttpResponseRedirect('dashboard', {'page_group': page_group})
URL:
url(r'^auth/login/$', UrlGatewayLogin.as_view(), name='auth-login')
As the error suggests, your view should always return an HttpResponse object. At the moment, you have return None in your except block.
You could prevent the error by doing something like:
from django.http import HttpResponseBadRequest
try:
...
except MyUser.DoesNotExist:
return HttpResponseBadRequest("Invalid token")

Cannot assign a user in Django

i have a simple chat application where i've customize the Authentication back end to use only the name. So far it is working and the users is logged in using Django login().
Now i have a problem with assign a user where this Error came up and cus the rest of the app to stop:
ValueError: Cannot assign "<SimpleLazyObject:
<django.contrib.auth.models.AnonymousUser
object at 0x7f7db7b71e80>>": "PChat.user" must be a "User" instance.
View.py
from chatbot import settings
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse,HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate, login
from Pchat.models import PChat
from django.contrib.auth.models import User
#csrf_exempt
def P_home(request):
context= locals()
template= 'P_home.html'
return render(request,template,context)
#csrf_exempt
def P_chat(request):
context= locals()
template= 'P_chat.html'
return render(request,template,context)
#csrf_exempt
def LogIIn(request):
if request.method == "POST":
name = request.POST.get('param1')
user = authenticate(username=name)
login(request, user)
return HttpResponse("OK")
#csrf_exempt
def Post(request):
if request.method == "POST":
msg = request.POST.get('param1')
if request.user.is_authenticated():
c = PChat(user=request.user, message=msg)
c.save()
return JsonResponse({ 'msg': msg, 'user': c.request.user })
else:
return HttpResponse("Account None")
models.py
from django.db import models
from django.db import models
from django.contrib.auth.models import User
class PChat(models.Model):
created = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User)
message = models.CharField(max_length=200)
def __unicode__(self):
return self.message
auth_backend.py
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
class PasswordlessAuthBackend(ModelBackend):
"""Log in to Django without providing a password."""
def authenticate(self, username=None):
try:
return User.objects.get(username=username)
except User.DoesNotExist:
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
OK, there are several errors on your code:
1) In P_home and P_chat you are using locals(), that's not recommended. You must avoid that whenever possible. You need to be explicit with data passed to the context dictionary.
2) In LogIIn view you must call login function when user is not None. [1]
3) The final error is in Post view, you must ask first wheter request.user is authenticated or not using request.user.is_authenticated() function. If the user is authenticated, then request.user is a normal User instance in other case its going to be an AnonymousUser, they both are different things. The field user in PChat model is expecting an User instead an AnonymousUser instance.
[1] https://docs.djangoproject.com/en/1.11/topics/auth/default/#how-to-log-a-user-in
You have problem in line:
c = PChat(user=request.user, message=msg)
request.user is not a User object. Firstly check request.user is actual user or not.
if request.user.is_authenticated():
c = PChat(user=request.user, message=msg)
c.save()
return JsonResponse({ 'msg': msg, 'user': c.user.username })
else:
return JsonResponse({ 'msg': 'user is not logged in' })
Edit
def Post(request):
if request.method == "POST":
msg = request.POST.get('param1')
if request.user.is_authenticated():
c = PChat(user=request.user, message=msg)
c.save()
return JsonResponse({ 'msg': msg, 'user': c.request.user })
return HttpResponse("Account None")

Django login part

I am now working on a system using the Django framework. I am writing the user login part. It seems successful but it doesn't work very well.
The login system can recognise the user by his/her username and password.
The authentication could only last for one "webpage". When I loaded another page or even reloaded the page, django can't get the info of the user(seems logged out)
If I looked at the page resources, I saw a session number made after the login process.
What should I do to ensure only one login is needed? And keep my user logged in during the whole process?
Here is my view file
from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from django.template import RequestContext, loader
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render_to_response,redirect
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt
from django.template.context_processors import csrf
from . import models
from . import form as f
from django.contrib.sessions.backends.db import SessionStore
def index(request):
if request.user != None :
template = loader.get_template('index.html')
return HttpResponse(template.render(None))
else :
return HttpResponseRedirect('/PDT/login_failed')
def Home(request):
template = loader.get_template('Home.html')
return HttpResponse(template.render(None))
def loggin_in(request):
c = {}
c.update(csrf(request))
return render_to_response('login.html', c)
def login_user(request):
logout(request)
username = password = ''
if request.POST:
username = request.POST.get('username','')
password = request.POST.get('password','')
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
request.session['username']=user.username
return HttpResponseRedirect('/PDT/logged_successful')
return HttpResponseRedirect('/PDT/inactive')
return HttpResponseRedirect('/PDT/incorrect')
return HttpResponseRedirect('/PDT/login_failed')
def logged_in(request):
if request.user :
return render_to_response('index.html',{ 'user' : request.user },context_instance=RequestContext(request))
else :
return HttpResponseRedirect('/PDT/login_failed')
def login_failed(request):
return render_to_response('problem.html',{ 'message' : "Login failed" })
def log_out(request):
request.session.flush()
logout(request)
return render_to_response('problem.html',{ 'message' : "Logged out" })
def inactive(request):
return render_to_response('problem.html',{ 'message' : "Inactive" })
def incorrect(request):
return render_to_response('problem.html',{ 'message' : "Incorrect Username or Password" })
def iter_update(request):
if request.session['username'] != None :
return render_to_response('iter_update.html',{ 'user' : request.user },context_instance=RequestContext(request))
else :
return HttpResponseRedirect('/PDT/login_failed')
def Create_form(request):
if request.method == "POST":
form = f.ProjectForm(request.POST)
if(form.is_valid()):
print(request.POST['title'])
form.save()
message = 'success'
else:
message = 'fail'
return render_to_response('Create_form.html',
{'message': message,
'user': request.user,},
context_instance=RequestContext(request))
else:
return render_to_response('Create_form.html',
{'form': f.ProjectForm()},
context_instance=RequestContext(request))
Please use return render(request, template_name, context_dict) to render templates. Your peculiar way probably strips it of context.
Also, take a look at this decorator, and use it instead of your current if request.user != None : statements.
Your user is logged in, but because you are strangely rendering the Home and Index templates via template.render(None), there is no request or user context in your template. Instead, use the render shortcut which runs context processors.

Categories