Django automatic login after user registration (2.1.4) [duplicate] - django

This question already has answers here:
Django: How to login user directly after registration using generic CreateView
(2 answers)
Closed 4 years ago.
The automatic login of newly registered users is not working in the case of a "class-based" registration view.
I followed the example from this tutorial, which proposes the following registration view:
# myapp/views.py
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
from django.views import generic
class SignUp(generic.CreateView):
form_class = UserCreationForm
success_url = reverse_lazy('login')
template_name = 'signup.html'
I tried including the class-based solution from this answer, but after successfully registering a new user, the login doesn't happen as expected. Are there changes in Django 2.1.4 which might cause this to malfunction?
myapp.users.views:
from django.views import generic
from django.contrib.auth import authenticate, login
from .forms import CustomUserCreationForm
class SignUp(generic.CreateView):
form_class = CustomUserCreationForm
success_url = '/index'
template_name = 'signup.html'
#auto login after register:
def form_valid(self, form):
#save the new user first
form.save()
#get the username and password
username = self.request.POST['username']
password = self.request.POST['password1']
#authenticate user then login
user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'],)
login(self.request, user)
return super(SignUp, self).form_valid(form)

You already logged in after registration by this line
login(self.request, user)
You may need to redirect homepage. SO, you need to chnage this line
return super(SignUp, self).form_valid(form)
to
return HttpResponseRedirect(reverse('url_name'))

Related

How to Verify Email in Django using OTP and UserCreationForm

I am creating a Quiz App. In that I have a sign up page for user authentication which is using the default User Model and User CreationForm. I want to add a email verification in it by sending a otp on the email.
Please explain me how can I send otp on email using default user model and user creation form to verify the otp on the email.
My user app code is:
forms.py
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
email = forms.EmailField()
class Meta:
model = get_user_model()
fields = ['username', 'email', 'password1', 'password2']
views.py
import pyotp
from django.contrib.auth.models import User
from .forms import UserRegisterForm
from django.contrib import messages
from django.shortcuts import render, redirect
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
otp=pyotp.totp('base32secret3232')
form.save()
messages.success(request, f'Account Created for {User.username}. You can Login')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
You can refer below article.
https://medium.com/analytics-vidhya/how-to-implement-otp-based-authentication-on-django-rest-framework-185ae8032f07#:~:text=Step%201%3A%20Find%20that%20phone,the%20authenticity%20of%20the%20user.

Cant login to created user after using custom model

from django.db import models
from django.contrib.auth.models import AbstractUser,User
from django.utils.html import escape,mark_safe
# Create your models here.
class user(AbstractUser):
is_admin = models.BooleanField(default=False)
is_teacher = models.BooleanField(default=False)
is_student = models.BooleanField(default=False)
def login_view(request):
form = AuthenticationForm()
if request.method=='POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username,password=password)
if user.is_admin==True:
login(request,user)
return HttpResponse(f"Welcome {username}")
else:
return HttpResponse('failled')
return render(request, 'login.html', {'form': form})
cant login using the user created by superuser.
the user is creating but while calling it or using it shows
created a user with staff and superuser authorization
still cant login
I think you need to set the setting AUTH_USER_MODEL. Also, not sure why you're overriding the login view. You can use another setting LOGIN_REDIRECT_URL to set the URL where the user gets redirected on successful login.
You need to unregister the built-in User from the admin and then register your own user model in admin.py
Example in the docs
from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from customauth.models import user
admin.site.register(user, UserAdmin)
# admin.site.unregister(User)
You may have to subclass the UserChangeForm to add your custom fields

How to get individual users data after login in django?

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.

django userform not showing in HTML page

I am new to django . here I want to register user and I have a problem , the user form doesnt show in registration html page
here is my code:
views.py :
enter code here
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.views import generic
from django.views.generic import View
from .forms import UserForm
from .models import Album
class UserFormView(View):
form_class = UserForm
template_name = 'music/registration_form.html'
# display blank form
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False)
# cleaned (Normalized) data
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.set_password(password)
user.save()
# return user objects if info r correct
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('music:index')
return render(request, self.template_name, {'form': form})
form.py :
from django.contrib.auth.models import User
from django import forms
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'email', 'password']
I think there is nothing wrong with url.py as long as the page pops up, I dunno where I'm mistaken

how can i authenticate logged in user in django generic views?

Hello to Stack Overflow community,
I had created login and logout functions in django views.py hence i had successfully achieved login and logout methods also but i am confusing know that how can i pass data of this logged in user details to my class based views in views.py because i want to give access to my class based views only if user login happened
views.py
def admin_login(request):
context = {}
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user:
login(request, user)
context['user'] = request.user
return redirect('profile')
else:
context['error'] = 'Provide Valid Credentials'
return render(request, "secret_template.html", context)
else:
return render(request, "secret_template.html", context)
def admin_logout(request):
logout(request)
return redirect('secretview')
i want to authenticate below view only if user logged in
class index(TemplateView):
template_name = 'secret_template.html'
Use the LoginRequiredMixin in your view.
from django.contrib.auth.mixins import LoginRequiredMixin
class index(LoginRequiredMixin, TemplateView):
login_url = reverse_lazy('admin_login') # or whatever
template_name = 'aapp/index.html'
Following Django documentation you'll find some generic examples fitting your request:
For function based views you can simply use the login_required decorator.
from django.contrib.auth.decorators import login_required
#login_required
def my_view(request):
return Something
For class based views you have an example with method_decorator
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
#method_decorator(login_required, name='dispatch')
class ProtectedView(TemplateView):
template_name = 'secret.html'
edit:
I cannot comment, so I add this here:
You can handle a user instance from request.user inside your views methods.