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.
Related
iam new to django.Can anyone send me the code of signup and login page to get particular details of the username without using django.contrib.auth.models import User.
(i.e if we login with some usename then it should only give details of that username not remaining).
Find view you want manipulate user in, declare user like current_user = request.user. I will provide you my login and register views below. In examples shown below I had from django.contrib.auth.models import User, but you can modify it as shown above.
Register:
def registerPage(request):
if request.user.is_authenticated:
return redirect('todoapp:home')
else:
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
email = request.POST.get('email')
if form.is_valid():
if check_does_email_already_exist(email):
form.save()
messages.success(request, "User is registered sucessfully")
return redirect('todoapp:login')
else:
messages.warning(
request, "User with same email already exist")
else:
messages.warning(
request, "That username already exist or your password is too short")
context = {
'form': form,
}
return render(request, 'register.html', context)
Login:
def loginPage(request):
if request.user.is_authenticated:
return redirect('todoapp:home')
else:
if request.method == 'POST':
username = request.POST.get('uname')
password = request.POST.get('passwd')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return redirect('todoapp:home')
else:
messages.warning(
request, "Your password or username isn't valid")
return redirect('todoapp:login')
else:
pass
return render(request, 'login.html')
These are my imports:
from django.shortcuts import render, redirect
from django.urls import reverse
from django.utils import timezone
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.shortcuts import get_object_or_404
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import CreateUserForm
And this is my forms.py:
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User
from django.forms import fields
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = [
'username',
'email',
'password1',
'password2',
]
I hope my answer will help you.
Trying to register user in Django. it keep giving me HttpResponse error
signup.html templates location is : templates/registration/signup.html
Here's what i tried:
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignUpForm(UserCreationForm):
username = forms.CharField(max_length=50)
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2', )
views.py
from django.contrib.auth import login, authenticate
from django.shortcuts import render, redirect, HttpResponse
from django.contrib.auth.decorators import login_required
from .forms import SignUpForm
#login_required
def home(request):
return render(request, 'registration/home.html')
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
email = form.cleaned_data.get('email')
raw_password = form.cleaned_data.get('password1')
user = authenticate(email= email, password= raw_password)
login(request, user)
return redirect('registration/home')
else:
form = SignUpForm()
return render(request, 'registration/signup.html', {'form': form})
I did tried replacing redirect with HttpResponseRedirect but it did't work
Account urls.py
from django.contrib.auth import views as auth_views
from django.conf.urls import url
from django.urls import path
from . import views
urlpatterns = [
path("login/", auth_views.LoginView.as_view(template_name = "registration/login.html"), name='login'),
path("logout/", auth_views.LogoutView.as_view(), name='logout'),
path('home/', views.home, name='home'),
url('signup/', views.signup, name='signup'),
]
Error
ValueError at /accounts/signup/
The view account.views.signup didn't return an HttpResponse object. It returned None instead.
Request Method: GET
Request URL: http://127.0.0.1:8000/accounts/signup/
Django Version: 3.0.3
Exception Type: ValueError
Exception Value:
The view account.views.signup didn't return an HttpResponse object. It returned None instead.
You need to support GET method e.g.:
def signup(request):
form = SignUpForm()
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
email = form.cleaned_data.get('email')
raw_password = form.cleaned_data.get('password1')
user = authenticate(email= email, password= raw_password)
login(request, user)
return redirect('registration/home')
return render(request, 'registration/signup.html', {'form': form})
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
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')
forms.py:
from django import forms
from django.contrib.auth import authenticate, get_user_model
from django.contrib.auth.models import User
from django.forms import ModelForm
from django.utils.text import capfirst
from .models import Classname, Sectionname, Teachername, Attendancename
class AuthenticationForm(forms.Form):
username = forms.CharField(max_length=20)
password = forms.CharField(widget=forms.PasswordInput)
error_messages = {
'invalid_login': ("Please enter a correct %(username)s and password."
"Note that both fields may be case-sensitive."),
'inactive': ("This account is inactive"),
}
def clean(self):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
if username and password:
self.user_cache = authenticate(username=username, password=password)
if self.user_cache is None:
raise forms.ValidationError(
self.error_messages['invalid_login'],
code='invalid_login',
)
else:
self.confirm_login_allowed(self.user_cache)
return self.cleaned_data
def confirm_login_allowed(self, user):
if user.is_active:
login(self.user) /** It raises error here... **/
else:
raise forms.ValidationError(
self.error_messages['inactive'],
code='inactive',
)
def get_user_id(self):
if self.user_cache:
return self.user_cache.id
return None
def get_user(self):
return self.user_cache
views.py:
from django.shortcuts import render, get_object_or_404
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.http import Http404, HttpResponseRedirect, HttpResponse
from django.template.response import TemplateResponse
from django.views.generic import DeleteView, ListView
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.cache import never_cache
from .models import Classname, Sectionname, Teachername, Attendancename
from .forms import ClassnameForm, SectionnameForm, TeachernameForm, AttendancenameForm, UserForm, PasswordChangeForm, AuthenticationForm
def user_login(request):
if request.method == 'POST':
form = AuthenticationForm(request.POST)
if form.is_valid():
return HttpResponseRedirect(reverse('student:mains'))
else:
print(form.errors)
else:
form = AuthenticationForm()
return render(request, 'login.html', {'form': form},)
urls.py:
from django.conf.urls import url, patterns
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
url(r'^register/$', views.register, name='register'),
url(r'^login/$', views.user_login, name='login'),
url(r'^logout/$', views.user_logout, name='logout'),
url(r'^password_change/$', auth_views.password_change, {'template_name': 'password_change_form.html', 'post_change_redirect': '/stu/password_change/done/'}, name="password_change"),
url(r'^password_change/done/$', auth_views.password_change_done, {'template_name': 'password_change_done.html'}, name="password_change_done"),
url(r'^restricted/', views.restricted, name='restricted'),
url(r'^mains/', views.mains, name = 'mains'),
]
I'm new to django authentication. I'm trying to make things as per the docs I have read. As your see above I've a 'user_login' view and 'AuthenticationForm' form.
I'm tring to login the user, but don't know the way how to do it? As I tried it in my view but didn't worked.
Then I tried it in my 'can_login_allowed' form's method but doesn't work.
Is there any other method to implement it?
Please! Can Anybody help me to fix it?
Thanks in Advance....
The login function takes request as first parameter. So you have write confirm_login_allowed like this:
def confirm_login_allowed(self, request):
if self.user_cache.is_active:
login(request,self.user_cache)
else:
raise forms.ValidationError(
self.error_messages['inactive'],
code='inactive',
)
And call it in the view like this
def user_login(request):
if request.method == 'POST':
form = AuthenticationForm(request.POST)
if form.is_valid():
form.confirm_login_allowed(request)
return HttpResponseRedirect(reverse('student:mains'))
else:
....
Also don't call the confirm_login_allowed method from clean method because it does't have the request.