How to get individual users data after login in django? - 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.

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.

how create a #username by taking username from registration form

i have setup the forms in the frontend what i want is that any User if gives his username for example username-> helloworld then it is interpreted as #helloworld and then this form with changed #username should be saved in the database so that i can use it afterwards.....
i am a noob in django framework .
i have been trying since last 2 days to find a answer here and by using google but unable to find a helpful answer
here is my ->forms.py
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignUpForm(UserCreationForm):
class Meta:
model = User
fields = ['first_name','last_name','username', 'email', 'password1', 'password2']
this is my -> views.py file
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate
from django.contrib import messages
from django.contrib.auth.models import User
from .forms import SignUpForm
from django.contrib.auth import get_user_model
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.shortcuts import get_current_site
from django.core.mail import EmailMessage
from django.http import HttpResponse
from django.template.loader import render_to_string
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
UserModel = get_user_model()
#index and signin def have been removed because it is out of context of question
def signup(request):
if request.user.is_authenticated:
return redirect('index')
else:
form = SignUpForm()
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
User.username = "#{}".format(User.username)
user.is_active = False
user = form.save
user.save()
current_site = get_current_site(request)
mail_subject = 'Activate your account.'
message = render_to_string('activation_mail.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': default_token_generator.make_token(user),
})
to_email = form.cleaned_data.get('email')
email = EmailMessage(
mail_subject, message, to=[to_email]
)
email.send()
return HttpResponse('Please confirm your email address to complete the registration')
else:
form = SignUpForm()
return render(request, 'signup.html', {'form': form})
Just override your form's save method to alter the data before saving.
class SignUpForm(UserCreationForm):
class Meta:
model = User
fields = ['first_name','last_name','username', 'email', 'password1', 'password2']
def save(self, *args, **kwargs):
self.instance.username = f"#{self.instance.username}"
return super().save(*args, **kwargs)

How to stop django to automatically active users while using UserRegisterForm

views.py
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Your account has been created! You are now able to log in')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
using RegisterForm for Registration form django automatically
activate user.I want to add signup email confirmation before
activating user.
So it is pretty simple, you can give a commit=False while saving the form
if form.is_valid():
user=form.save(commit=False)
# sets the field to False
user.is_active=False
user.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Your account has been created! You are now able to log in')
return redirect('login')
you have also said that
I want to add signup email confirmation before activating user.
for this, you cancheck out these links from
2017: https://medium.com/#frfahim/django-registration-with-confirmation-email-bb5da011e4ef
or 2018:Django 2 - How to register a user using email confirmation and CBVs?

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 to authenticate for login

How I can authenticate my user for login ,here authenticate does not work properly
I have used authenticate for login
views.py
from django.shortcuts import render
from basic_app.models import Signup
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponse,HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth.decorators import login_required
def signup(request):
if request.method=="POST":
obj=Signup()
obj.username=request.POST.get('username')
obj.password=request.POST.get('password')
obj.save()
context={'username':'username'}
return render(request,'basic_app/singup.html',context)
else:
return render(request,'basic_app/singup.html')
def login(request):
if request.method=="POST":
username=request.POST.get('username')
password=request.POST.get('password')
user=authenticate(username=username,password=password)
if user:
login(request,user)
return HttpResponse("you have login")
else:
return HttpResponse("wrong password or username")
else:
return render(request,'basic_app/login.html')
You should login using login after authenticating.
user = authenticate(username=request.POST.get('username',''),
password=request.POST.get('password',''))
login(request, user)
Read:https://docs.djangoproject.com/en/2.1/topics/auth/default/#how-to-log-a-user-in
Actually, you can use Django's inbuilt LoginView ("https://docs.djangoproject.com/en/2.1/topics/auth/default/#django.contrib.auth.views.LoginView")
If you want to change the layout style. Either override the Django login template or override the class view.
For overriding the class view:
from django.contrib.auth.views import LoginView
class MySignInView(LoginView):
form_class = MySignInForm
template_name = 'mylife/myrules/login.html'
I have edited your following code :
from django.shortcuts import render
from basic_app.models import Signup
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponse,HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth.decorators import login_required
def login(request):
if request.method=="POST":
username=request.POST.get('username')
password=request.POST.get('password')
user=authenticate(username=username,password=password)
if user:
login(request,user)
return HttpResponse("you have login")
else:
return HttpResponse("wrong password or username")
else:
return render(request,'basic_app/login.html')
1) When you authenticate your username and password, it just returns User and it doesn't make you to login,
2) for login you have to call login(requst,user),it will create session in your database as acknowledgment