ModuleNotFoundError: No module named 'django.contrib.auth.decoraters' - django

I am trying to create a login and logout page for my sample project and have coded all logic up. The tutorial I was following used the following code
from django.shortcuts import render
from basic_app.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.decoraters import login_required
# Create your views here.
def index(request):
return render(request,'basic_app/index.html')
def register(request):
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
if user_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
registered = True
else:
print(user_form.errors)
else:
user_form = UserForm()
return render(request,'basic_app/registration.html',
{'user_form':user_form,
'registered':registered })
#login_required
def special(request):
return HttpResponse("You are logged in!")
#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:
login(request,user)
return HttpResponseRedirect(reverse('index'))
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 supplied")
else:
return render(request,'basic_app/login.html',{})
The error I am getting is this
from django.contrib.auth.decoraters import login_required
ModuleNotFoundError: No module named 'django.contrib.auth.decoraters'

You make spelling mistakes while importing the decorators:
Change:
from django.contrib.auth.decoraters import login_required
To:
from django.contrib.auth.decorators import login_required

Related

Django routing/pathing to multiply apps

Hi i know there is many of these asking about routing from a veiw to a new app in django. I have looked at a lot of them. And figured out to use app_name = 'name' and to use named routes for my html templates makes everything easier for sure. When i try to use a app_name:named-route i get this :
ValueError at /recipedashboard
The view recipeApp.views.dashboard didn't return an HttpResponse object. It returned None instead.
I have gotten the name_app:named-route to send me to the second app, but how do i pass the session to the new app?
userApp veiws:
from django.shortcuts import render, redirect
from django.contrib import messages
from .models import User as LoggedUser
# Create your views here.
def index(request):
return render(request, 'index.html')
def register(request):
if request.method == "GET":
return redirect('/')
errors = LoggedUser.objects.validate(request.POST)
if len(errors) > 0:
for er in errors.values():
messages.error(request, er)
return redirect('/')
else:
new_user = LoggedUser.objects.register(request.POST)
request.session['user_id'] = new_user.id
messages.success(request, "You have successfully registered")
return redirect('/success')
def login(request):
if request.method == "GET":
return redirect('/')
if not LoggedUser.objects.authenticate(request.POST['email'],
request.POST['password']):
messages.error(request, "Invalid Email/Password")
return redirect('/')
user = LoggedUser.objects.get(email=request.POST['email'])
request.session['user_id'] = user.id
messages.success(request, "You have successfully logged in!")
return redirect('/success')
def logout(request):
request.session.clear()
return redirect('/')
def success(request):
if 'user_id' not in request.session:
return redirect('/')
context = {
'user' : LoggedUser.objects.get(id=request.session['user_id'])
}
return redirect("recipe:recipe-dashboard")
recipeApp urls.py:
from django.urls import path
from . import views as recipeViews
app_name ='recipe'
urlpatterns = [
path('dashboard', recipeViews.dashboard, name= "recipe-dashboard" )
]
recipeApp.Views :
from django.shortcuts import render, redirect
from userApp.models import User as LoggedUser
# Create your views here.
def dashboard(request):
if 'user_id' not in request.session:
return redirect('/')
user = LoggedUser.objects.get(id=request.session['user_id'])
context = {
'user' : user
}
render (request, 'dashboard.html', context)
Your dashboard view is not returning anything.
You need to return the results of render. Like
from django.shortcuts import render, redirect
from userApp.models import User as LoggedUser
# Create your views here.
def dashboard(request):
if 'user_id' not in request.session:
return redirect('/')
user = LoggedUser.objects.get(id=request.session['user_id'])
context = {
'user' : user
}
return render (request, 'dashboard.html', context)
There is no need to deal with passing a session. The framework will handle that for you if the apps are all under the same project.

after pressing verification link ... nothing happens in Django .. user still unverified

Views.py(name of app: userprofileinfo)
from django.shortcuts import render
from userprofileinfo.forms import UserForm
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth import authenticate, login, logout
from django.views.decorators.csrf import csrf_exempt,csrf_protect
from django.views import View
from django.contrib import messages
from django.core.mail import send_mail
from django.contrib.sites.shortcuts import get_current_site
from django.utils.encoding import force_bytes, force_text, DjangoUnicodeDecodeError
from django.core.mail import send_mail
from django.contrib.sites.shortcuts import get_current_site
from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode
from django.template.loader import render_to_string
from .utils import account_activation_token
from django.urls import reverse
from django.contrib import auth
#login_required
def special(request):
return HttpResponseRedirect("You are logged in, Nice!")
#login_required
def userlogout(request):
logout(request)
return HttpResponseRedirect(reverse('careforallapp:base'))
def register(request):
registered = False
if request.method == "POST":
user_form = UserForm(data=request.POST)
if user_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.is_active = False
user.save()
email = UserForm('email')
current_site = get_current_site(request)
email_body = {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user),
}
link = reverse('userprofileinfo:activate', kwargs={
'uidb64': email_body['uid'], 'token': email_body['token']})
email_subject = 'Activate your account'
activate_url = 'http://'+current_site.domain+link
send_mail(
email_subject,
'Hi '+user.username + ', Please the link below to activate your account \n'+activate_url,
'settings.EMAIL_HOST',
[user.email],
fail_silently=False
)
return HttpResponseRedirect(reverse('careforallapp:base'))
else:
print(user_form.errors)
else:
user_form = UserForm()
return render(request,'userprofileinfo/registration.html',
{'user_form':user_form,
'registered':registered})
class VerificationView(View):
def get(self, request, uidb64, token):
try:
id = force_text(urlsafe_base64_decode(uidb64))
user = User.objects.get(pk=id)
if not account_activation_token.check_token(user, token):
return redirect('login'+'?message='+'User already activated')
if user.is_active:
return redirect('login')
user.is_active = True
user.save()
messages.success(request, 'Account activated successfully')
return redirect('login')
except Exception as ex:
pass
return HttpResponseRedirect(reverse('userprofileinfo:userlogin'))
def userlogin(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('careforallapp:base'))
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, 'userprofileinfo/login.html', {})
.env
export EMAIL_HOST_PASSWORD=*******
export EMAIL_HOST_USER = careall249#gmail.com
export EMAIL_HOST=smtp.gmail.com
urls.py
from django.conf.urls import url
from django.urls import path
from .views import VerificationView
from userprofileinfo import views
app_name = 'userprofileinfo'
urlpatterns = [
url(r'^login/', views.userlogin, name='userlogin'),
url(r'^register/', views.register, name='register'),
url(r'^logout/', views.userlogout, name='userlogout'),
url(r'^special/', views.special, name='special'),
path('activate/<uidb64>/<token>', VerificationView.as_view(), name='activate'),
]
Can someone go through the code. Login page, registration page all working fine but verification link is not working, when user register, he gets the link on his Gmail but when he presses the link for verify nothing happens. User not get active. Can somebody go through it and find the error.

Error while entering the login form details based on signup form

I am trying to enter the details in login form.But it is not authenticating the username and password with the existing usernames and passwords present in form data.
Here is my code
views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.contrib.auth import authenticate, login, logout
from . forms import signup_form,loginform,profileform
from . models import registration_form
def index(request):
return render(request,'loginapp/index.html')
def display_form(request):
rform = signup_form(request.POST)
if rform.is_valid():
rform.save()
return HttpResponseRedirect('/profile/')
else:
return render(request,'loginapp/first.html',{'rform': rform})
def login_form(request):
if request.method == 'POST':
Username = request.POST.get('Username')
Password = request.POST.get('Password')
registration_form=
authenticate(Username=Username,Password=Password)
print("Username")
if registration_form is None:
if registration_form.is_active:
login(request,registration_form)
return HttpResponseRedirect(reverse('index'))
else:
return HttpResponse("Your account was inactive.")
else:
print("Someone tried to login and failed.")
print("They used Username: {} and Password:
{}".format(Username,Password))
return HttpResponse("Invalid login details given")
return HttpResponseRedirect('/profile/')
else:
return render(request, 'loginapp/login.html', {})
def profile_form(request):
return render(request,'loginapp/profile.html')

Login using Class based view didn't work as expected while trying to login a user using email

my views.py:
from django.http import HttpResponse
from django.shortcuts import render, render_to_response
from django.contrib.auth import login, authenticate
from django.contrib.auth.models import User
from django.shortcuts import render
from django.views.generic import View
from .forms import LoginForm, RegistrationForm
class Login(View):
form_class = LoginForm
initial = {'key': 'value'}
template_name = 'web/login.html'
def get(self, request):
form = self.form_class(initial=self.initial)
return render(request, self.template_name, {'form': form})
def post(self, request):
if request.method == 'POST':
form = self.form_class(initial=self.initial)
if form.is_valid():
email=form.cleaned_data['email']
password=form.cleaned_data['password']
auser = User.objects.get(email=email)
username = auser.username
buser = authenticate(username, password)
if buser:
if buser.is_active:
login(request, buser)
return HttpResponse('Good to Go...')
else:
return HttpResponse('your account is disabled...')
else:
print "Invalid login details: {0}, {1}".format(email, password)
HttpResponse('invalid login details...')
else:
return HttpResponse('Form is not valid!')
else:
form = self.form_class()
Here above I'm trying to login a user using email as unique field in class based views. But It raises 'Form is not valid!' as I specified in my views. I don't know what's going wrong with it exactly. Please Help me how to fix it?
Thanks in Advance
You need to change the post method of this class:
def post(self, request):
if request.method == 'POST':
form = self.form_class(data=self.request.POST)
if form.is_valid():
.....

Django Error:: global name 'HttpRequestRedirect' is not defined

I am getting this error, I tried working on it a lot but cannot understand whats wrong.
I am basically trying to make a signup registration that has a couple of forms to be filled
Request Method: GET
Request URL: http://127.0.0.1:8000/gi/
Django Version: 1.5.1
Exception Type: NameError
Exception Value:
global name 'HttpRequestRedirect' is not defined
Exception Location: /home/xx/Desktop/GoAmma/vendorAmmma/vreg/views.py in GIRegistration, line 42
Python Executable: /home/xx/Desktop/forfte/bin/python
Python Version: 2.7.3
The view is as shown below:
# Create your views here.
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.template import RequestContext
from vreg.forms import RegistrationForm, LoginForm
from vreg.models import Vendor
from django.contrib.auth import authenticate, login, logout
def VendorRegistration(request):
if request.user.is_authenticated():
return HttpRequestRedirect('/profile/')
if request.method=='POST':
form= RegistrationForm(request.POST)
if form.is_valid():
user=User.objects.create_user(username=form.cleaned_data['username'], email= form.cleaned_data['emailadd'], password= form.cleaned_data['password'])
user.save()
vreg=Vendor(user=user)
vreg.save()
return HttpResponseRedirect('/profile/')
else:
return render_to_response('register.html', {'form':form}, context_instance=RequestContext(request))
else:
''' user is not submitting form show them blank registration form'''
form= RegistrationForm()
context={'form':form}
return render_to_response('register.html', context, context_instance=RequestContext(request))
#login_required
def Profile(request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/login/')
vreg= request.user.get_profile
context={'vreg':vreg}
return render_to_response('profile.html',context,context_instance=RequestContext(request))
#login_required
def GIRegistration(request):
if request.user.is_authenticated():
return HttpRequestRedirect('/profile/')
if request.method=='POST':
form= GIForm(request.POST)
if form.is_valid():
contact = form.save()
contact.save()
return HttpResponseRedirect('/profile/')
else:
return render_to_response('generalinfo.html', {'form':form}, context_instance=RequestContext(request))
else:
''' user is not submitting form show them blank registration form'''
form= GIForm()
context={'form':form}
return render_to_response('generalinfo.html', context, context_instance=RequestContext(request))
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']
vreg= authenticate(username=username,password=password)
if vreg is not None:
login(request,vreg)
return HttpResponseRedirect('/profile/')
else:
return render_to_response('login.html',{'form':form}, context_instance= RequestContext(request))
else:
return render_to_response('login.html',{'form':form}, context_instance= RequestContext(request))
else:
'''user not submitting form show the login form'''
form= LoginForm()
context={'form': form}
return render_to_response('login.html',context,context_instance= RequestContext(request))
def LogoutRequest(request):
logout(request)
return HttpResponseRedirect('/')
Its HttpResponseRedirect not HttpRequestRedirect.
Change this return HttpRequestRedirect('/profile/') to return HttpResponseRedirect('/profile/')
P.S. Never use hardcoded urls in your code, use Reverse Resolution of URLs