Login not working in Django - django

I'm trying to login but Django is not allowing the navigation to the profile.html
This is what I have so far
views.py
def login(request):
if request.method == 'POST':
form = UserLoginForm(request.POST)
if form.is_valid():
userObj = form.cleaned_data
print(userObj)
username = userObj['username']
password = userObj['password']
user = authenticate(username=username, password=password)
if user is not None:
print("in login")
login(request)
return render(request, 'profiles.html', {'form': form})
else:
return render(request, 'login_form.html', {'form': form})
else:
return render(request, 'login_form.html')
forms.py
class UserLoginForm(forms.Form):
username = forms.CharField(
required=True,
label='Username',
max_length=32
)
password = forms.CharField(
required=True,
label='Password',
max_length=32,
widget=forms.PasswordInput()
)

Check This Code I have done login Register
https://github.com/gowthamand/django-1.11.5-crud-ajax-login-register
I used Inbuilt Login

I think that you need to pass the user to login function
from django.contrib.auth import authenticate, login as f_login
def login(request):
if request.method == 'POST':
form = UserLoginForm(request.POST)
if form.is_valid():
userObj = form.cleaned_data
print(userObj)
username = userObj['username']
password = userObj['password']
user = authenticate(username=username, password=password)
if user is not None:
print("in login")
f_login(request, user)
return render(request, 'profiles.html', {'form': form})
else:
return render(request, 'login_form.html', {'form': form})
else:
return render(request, 'login_form.html', {'form': form})

Related

Django Login Authentication: I am able to SignUp new user and create new user as well but UNABLE to login as SignUp user

I'm able to SignUp new user as well but UNABLE to login for handlelogin
def handlelogin(request):
if request.method == 'POST':
loginemail= request.POST['loginemail']
loginpass = request.POST['loginpass']
user = authenticate(request, username=loginemail, password=loginpass)
if user is not None:
print(loginemail, loginpass)
login(request, user)
messages.success(request, "Successfullly Logged-In")
return redirect('/')
else:
messages.error(request, "Invalid Credentials, Please Try Again")
return redirect('/')
return HttpResponse('404 - Page Not Find')
I have tried print() statement to check and it do work in else statement only, not in if user is not none.
NOTE: THE SYNTAX IN QUESTION IS LITTLE BIT DISTURBED... BUT IN CODE IT IS COMPLTELY FINE.
BTW I use Django forms for login and logout users:
views.py:
def user_login(request):
if request.method == 'POST':
form = UserLoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(request, username=cd['username'], password=cd['password'])
if user is not None:
login(request, user)
messages.success(request, 'you logged in successfully', 'success')
return HttpResponseRedirect('dashboard/')
else:
messages.error(request, 'username or password is wrong', 'danger')
else:
form = UserLoginForm()
return render(request, 'login.html', {'form': form})
def user_logout(request):
logout(request)
messages.success(request, 'you logged out successfully', 'success')
return HttpResponseRedirect('')
forms.py
class UserLoginForm(forms.Form):
username = forms.CharField(max_length=30)
password = forms.CharField(max_length=50)
urls.py
urlpatterns = [
path('', user_login),
path('logout/', user_logout, name='user_logout'),
]
Also if you haven't make sign Up page you should make user manually by python3 manage.py createsuperuser command.
For sign Up page:
urls.py
urlpatterns = [
...
path('signup/', signup, name='signup'),
]
views.py
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('home')
else:
form = SignUpForm()
return render(request, 'signup.html', {'form': form})
forms.py
class SignUpForm(UserCreationForm):
first_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
last_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')

Email Verification in Django when a new user signs up

I am creating a user registration page for my website. I want to send an email verification mail to the mail the user inputs while registering. I tried many solutions but nothing seems to work for me.
My code:
views.py
def registerPage(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST, request.FILES)
if form.is_valid():
user = form.save()
username = form.cleaned_data.get('username')
messages.success(request, 'Account was created for ' + username)
return redirect('login')
context = {'form': form}
return render(request, 'Home/register.html', context)
def loginPage(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
messages.info(request, 'Username OR password is incorrect')
return redirect('login')
context = {}
return render(request, 'Home/login.html', context)
forms.py
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ["username", "email", "password1", "password2"]

How can i create a login view after registration?

I create models,forms and views for registrarion and i want to create a login view so that after registration user can login.
models.py
from django.contrib.auth.models import AbstractUser
from django_countries.fields import CountryField
g_CHOICES = (('male','male'),('female','female'))
class User(AbstractUser):
gender = models.CharField(max_length=100,choices=g_CHOICES,default="male")
country = CountryField()
location = models.CharField(max_length=30, blank=True)
forms.py
g_CHOICES = (('male','male'),('female','female'))
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
gender = forms.ChoiceField(choices=g_CHOICES)
country = CountryField().formfield()
location = forms.CharField(max_length=30,)
class Meta:
model = User
fields = ['first_name','last_name','username','email',
'password1','password2','gender',
'country','location']
views.py
def register(request):
if request.method == 'POST':
rform = UserRegisterForm(request.POST)
if rform.is_valid():
rform.save()
username = rform.cleaned_data.get('username')
messages.success(request,('Account created for '+str(username)))
return redirect('/')
else:
rform = UserRegisterForm()
return render(request,'reg.html',{'rform':rform})
Now i want to create a view for login please someone help
You need a view that takes the user's username and password from the POST request, then authenticates them and logs them in using 'authenticate' and 'login' from django.contrib.auth package.
from django.contrib.auth import login, authenticate
from django.views import View
class HandleLogin(View):
def get(self, request):
return render(request, "login.html", {})
def post(self, request):
username= request.POST.get("username")
password = request.POST.get("password")
user = authenticate(username, password)
if user is not None:
if user.is_active:
login(request, user)
# Do something for succesfull logged in
else:
# Do something else because user is not active
else:
# Do something about user not existing
For more information: https://docs.djangoproject.com/en/2.2/topics/auth/default/
You can use something like below one:
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
messages.success(request, 'You are now logged in')
return redirect('dashboard')
else:
messages.error(request, 'Invalid credentials')
return redirect('login')
else:
return render(request, 'accounts/login.html')
Or if you are using a django form you can do this way too and this is more preferred way:
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(request,
username=cd['username'],
password=cd['password'])
if user is not None:
login(request, user)
return HttpResponse('Authenticated '\
'successfully')
else:
return HttpResponse('Invalid login')
else:
form = LoginForm()
return render(request, 'account/login.html', {'form': form})

ValueError: The view accounts.views.register didn't return an HttpResponse object. It returned None instead. When attempting to register user

When attempting to register a user (after changing my project from default user model to custom user model) I get this value error. The following is my View.
def register(request):
if request.method =='POST':
form = RegisterForm(request.POST)
if form.is_valid():
form.save()
email= request.POST.get('email')
password = request.POST.get('password1')
user = authenticate(
request,
email=email,
password=password,
)
login(request, user)
return redirect(reverse('accounts:view_profile'))
else:
form = RegisterForm()
args = {'form': form}
return render(request, 'accounts/reg_form.html', args)
Try it like this:
def register(request):
form = RegisterForm(request.POST or None)
if request.method =='POST':
if form.is_valid():
form.save()
email= request.POST.get('email')
password = request.POST.get('password1')
user = authenticate(
request,
email=email,
password=password,
)
login(request, user)
return redirect(reverse('accounts:view_profile'))
args = {'form': form}
return render(request, 'accounts/reg_form.html', args)

Why am I getting this error in django project ?`

So I am working on user authentication, login, logout. I am getting the error when I am opening the registration portal.
AttributeError at /profile/
'User' object has no attribute 'get_profile'
Following is my views.py
def Registration(request):
if request.user.is_authenticated:
return HttpResponseRedirect('/profile/')
if request.method == 'POST':
form = UserRegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(username = form.cleaned_data['username'],email = form.cleaned_data['email'] , password = form.cleaned_data['password'])
user.save()
UserProfile= UserProfile(user=user, birth_date=form.cleaned_data['birth_date',])
UserProfile.save()
return HttpResponseRedirect('/profile/')
else:
return render('visit/registration/register.html', {'form': form},)
else:
form= LoginForm()
context = {'form': form}
return render(request, 'visit/registration/register.html', context )
#login_required
def Profile(request):
if not request.user.is_authenticated:
return HttpResponseRedirect('/login/')
UserProfile = request.user.get_profile()
context ={'UserProfile': UserProfile}
return render(request,'visit/profile.html', context)
def LoginRequest(request):
if request.user.is_authenticated:
return HttpResponseRedirect('/profile')
if request.method == 'POST':
form = LoginRequest(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
UserProfile = authenticate(username=username, password=password)
if UserProfile is not None:
login(request, UserProfile)
return HttpResponseRedirect('/profile/')
else:
return render(request,'visit/registration/login.html',{'form':form})
else:
return render(request, 'visit/registration/login.html', {'form': form})
else:
form= LoginForm()
context = {'form': form}
return render(request, 'visit/registration/login.html', context, )
def logoutRequest(request):
logout(request)
return render(request, 'visit/login.html')
def index(request):
return render(request, 'visit/index.html', context=None)
I am not sure what/where the error is. I am using the Django 2.0.2.
I know there are similar questions but I am not getting the proper solution.
Help would be appricated. Following is my settings.py
#provides our get_profile
AUTH_PROFILE_MODULE = 'visit.model.UserProfile'
# URL for #login required
LOGIN_URL = '/login/'
#redirect authenticated user
LOGIN_REDIRECT_URL = '/profile/'
As per #neverwalker comment, this method is deprecated 1.7. please refer below code
user_profile = UserProfile.objects.get(activation_key='some_key')
user = user_profile.user