user created with no password Django (users can't log in) - python

Im registering succesfully user, but when ot redirects me to login page I'm 100% sure password is correct, but it is not login me in, so I checked the admin page for that particular user, username exists, but it says that the password is not created yet.
this is my views.py
#from selectors import EpollSelector
from django.shortcuts import render, redirect
from django.contrib import messages
from django.http import HttpResponseRedirect
from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm
from django.contrib.auth.decorators import login_required
# Create your views here
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'You are now able to log in!')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'Users/register.html', {'form': form})
#login_required
def profile(request):
if request.method == "POST":
u_form = UserUpdateForm(request.POST, instance = request.user)
p_form = ProfileUpdateForm(request.POST,
request.FILES,
instance=request.user.profile)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request, f'You account has been updated!')
return redirect('profile')
else:
u_form = UserUpdateForm(instance = request.user)
p_form = ProfileUpdateForm(instance=request.user.profile)
context = {
'u_form' :u_form,
'p_form' :p_form
}
return render(request, 'Users/profile.html', context)
and this is my forms.py code
from socket import fromshare
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserChangeForm
from .models import Profile
class UserRegisterForm(UserChangeForm):
email = forms.EmailField()
password1 = forms.CharField(label = "Password", widget = forms.PasswordInput)
password2 = forms.CharField(label = "Repeat password", widget = forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
class UserUpdateForm(forms.ModelForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email']
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image']
Please suggest some solution. I was following Corey Schafer tutorial.

Try to read about django.contrib.auth and passwords.
https://docs.djangoproject.com/en/4.1/topics/auth/default/#changing-passwords
Django don't change password to hash, you should do it yourself before user.save()
in your case:
... # your staff
form = UserRegisterForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.set_password(form.cleaned_data['password'])
user.save()
username = user.username
messages.success(request, f'You are now able to log in!')
... # other staff

Related

How can I save the username in the database as an email?>

I want a signup page with 3 fields (email, password and repeat password). My goal is that when the user enters the email address, it is also saved in the database as a username. I would be super happy if someone could help me, I've been sitting for x hours trying to solve this problem. Thanks very much!
model.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
email_confirmed = models.BooleanField(default=False)
#receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
instance.profile.save()
forms.py
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
# Sign Up Form
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='Enter a valid email address')
class Meta:
model = User
fields = [
'username',
'password1',
'password2',
]
views.py
from django.contrib import messages
from django.contrib.auth.models import Group
from django.contrib.sites.shortcuts import get_current_site
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from django.template.loader import render_to_string
from .token import AccountActivationTokenGenerator, account_activation_token
from django.shortcuts import render, redirect
from .forms import *
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth import get_user_model, login
from django.utils.http import urlsafe_base64_decode
from django.views.generic import View, UpdateView
from django.contrib.auth.decorators import login_required
from .decorators import *
from django.urls import reverse_lazy
from django.utils.encoding import force_str
#unauthenticatedUser
def Example_login(request):
if request.method == 'POST':
email = request.POST.get('email')
password = request.POST.get('password')
user = authenticate(request, username=email, password=password)
if user is not None:
login(request, user)
return redirect('Example_dashboard')
else:
messages.info(request, 'Username OR password is incorrecct')
context = {}
return render(request, 'accounds/templates/Example_login.html', context)
def reset_passwrd(request):
return render(request, "reset_password.html")
#login_required(login_url='login')
def Example_dashboard(request):
form = MembersForm()
current_user = request.user
name = current_user.username.split(".")[0]
context = {'form': form, "cunrrent_user": name}
return render(request, 'example_dashboard.html', context)
def Login(request):
if request.method == 'POST':
email = request.POST.get('Benutzername')
password = request.POST.get('Passwort')
user = authenticate(request, username=email, password=password)
if user is not None:
login(request, user)
return redirect('Example_dashboard')
else:
messages.info(request, 'Username OR password is incorrecct')
return render(request, "login.html")
def logoutUser(request):
logout(request)
return redirect('login')
def registrierung(request):
return render(request, "registrierung.html")
#unauthenticatedUser
def Example_register(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
user = form.save()
#username = form.cleaned_data.get('usernname')
group = Group.objects.get(name='studends')
user.groups.add(group)
messages.success(request, 'Account was created' )
return redirect('login')
contex = {'form' : form}
return render(request, 'exampl_register.html',contex)
# Sign Up View
class SignUpView(View):
form_class = SignUpForm
template_name = 'signup.html'
def get(self, request, *args, **kwargs):
form = self.form_class()
return render(request, self.template_name, {'form': form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.is_active = False # Deactivate account till it is confirmed
user.save()
current_site = get_current_site(request)
subject = 'Activate Your MySite Account'
message = render_to_string('account_activation_email.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user),
})
user.email_user(subject, message)
messages.success(request, ('Please Confirm your email to complete registration.'))
return redirect('login')
return render(request, self.template_name, {'form': form})
class ActivateAccount(View):
def get(self, request, uidb64, token, *args, **kwargs):
try:
uid = force_str(urlsafe_base64_decode(uidb64))
user = User.objects.get(pk=uid)
except (TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
if user is not None and account_activation_token.check_token(user, token):
user.is_active = True
user.profile.email_confirmed = True
user.save()
login(request, user)
messages.success(request, ('Your account have been confirmed.'))
return redirect('login')
else:
messages.warning(request, ('The confirmation link was invalid, possibly because it has already been used.'))
return redirect('login')
I Need your help
If you want to use email instead of the default username, you have to overwrite the default User model with the custom one
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
class User(AbstractBaseUser, PermissionsMixin):
# Use the email for logging in
email = models.EmailField(max_length=254, unique=True)
USERNAME_FIELD = 'email'

Hash a password field outside of the User model - Django

I am trying to have a user register, and then log in. Once they are logged in they specify their WiFi name, followed by a wifi password, and their choice of a VPN. The problem I am having is hashing the wifi_password field upon saving it to the database. I am trying to hash the password within the edit function in views.py. I have posted the entirety of my models, forms, and views. The code is still sloppy, and will need some cleaning up when I can achieve functionality. Thanks.
models.py
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
vpn_choices = [
('openvpn', 'Open VPN'),
('pia', 'Private Internet Access'),
('expressvpn', 'Express VPN'),
]
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,
on_delete = models.CASCADE,
null = True)
wifi = models.CharField(max_length = 128)
wifi_password = models.CharField(max_length = 128)
vpn_choice = models.CharField(max_length = 20, choices = vpn_choices)
def __str__(self):
return f'self.user.username {self.user.username}'
forms.py
from django import forms
from django.contrib.auth.models import User, AbstractUser
from django.contrib.auth import get_user_model
from server.models import Profile
from django.forms import ModelForm
vpn_choices = [
('openvpn', 'Open VPN'),
('pia', 'Private Internet Access'),
('expressvpn', 'Express VPN'),
]
class LoginForm(forms.Form):
username = forms.CharField(max_length = 126)
password = forms.CharField(max_length = 126, widget = forms.PasswordInput)
class UserRegistrationForm(forms.ModelForm):
password = forms.CharField(label = 'Password',
widget = forms.PasswordInput)
password2 = forms.CharField(label = 'Repeat Password',
widget = forms.PasswordInput)
class Meta:
model = User
fields = ('username',)
def clean_password2(self):
cd = self.cleaned_data
if cd['password'] != cd['password2']:
raise forms.ValidationError('Passwords don\'t match.')
return cd['password2']
class ProfileEditForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('wifi', 'wifi_password', 'vpn_choice')
labels = {
'wifi': ('WiFi'),
'wifi_password': ('WiFi Password'),
'vpn_choice': ('VPN Choice'),
}
widgets = {
'wifi_password': forms.PasswordInput
}
views.py
from django.shortcuts import render, redirect, reverse
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponse, HttpResponseRedirect
from .forms import LoginForm, UserRegistrationForm, ProfileEditForm
from django.contrib.auth.decorators import login_required
from server.models import Profile
from django.contrib.auth.hashers import make_password
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:
if user.is_active:
login(request, user)
return HttpResponse('Authenticated '\
'successfully')
else:
return HttpResponse('Disabled account')
else:
return HttpResponse('Invalid Login')
else:
form = LoginForm()
return render(request, 'login.html', {'form': form})
def index(request):
return render(request, 'index.html')
def register(request):
if request.method == 'POST':
user_form = UserRegistrationForm(request.POST)
if user_form.is_valid():
# Create a new user object but avoid saving it yet
new_user = user_form.save(commit = False)
# Set the chosen password
new_user.set_password(
user_form.cleaned_data['password'])
# Save the User object
new_user.save()
# Create the user profile
Profile.objects.create(user = new_user)
return render(request,
'register_done.html',
{'new_user': new_user})
else:
user_form = UserRegistrationForm()
return render(request,
'register.html',
{'user_form': user_form})
#login_required
def user_logout(request):
logout(request)
return HttpResponseRedirect(reverse('index'))
#login_required
def edit(request):
if request.method == 'POST':
profile_form = ProfileEditForm(instance = request.user.profile,
data = request.POST)
if profile_form.is_valid():
settings = profile_form.save(commit = False)
password = make_password('wifi_password')
settings.save()
else:
profile_form = ProfileEditForm()
return render(request, 'edit.html',
{'profile_form': profile_form})
But if you will hash the password yourself, you will need to override authenticate as well as the Django won't be able to regenerate the hash to find the user record

How do I show model field values in HTML page, in Django for this particular case?

I need to display the details of the user on the profilepage. But in the following situation, I am unable to render phone number and flag(attributes of SpecialUser model) on my profile page. I was asked to implement an extended model for the User model in Django auth for an application. I introduced 2 new fields i.e, phonenumber(charfield), flag(booleanfield). My form is able to take both the inputs. But I couldn't render these values again into my HTML file. Could someone help me out!
models.py
# accounts.models.py
from django.db import models
from django.contrib.auth.models import User
class SpecialUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
flag = models.BooleanField(verbose_name="Special User", default=False)
phonenumber = models.CharField(max_length=10, verbose_name="phonenumber")
def __str__(self):
return self.user.username
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import SpecialUser
class RegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ["username", "email", "password1", "password2"]
class SuperUserForm(forms.ModelForm):
class Meta:
model = SpecialUser
fields = ["flag", "phonenumber"]
views.py
from accounts.models import SpecialUser
from django.shortcuts import render, redirect
from .forms import RegisterForm, SuperUserForm
from django.contrib import messages
from django.contrib.auth.models import auth
def register(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
sp_form = SuperUserForm(request.POST)
if form.is_valid() and sp_form.is_valid():
user = form.save()
sp_form = sp_form.save(commit=False)
sp_form.user = user
sp_form.save()
messages.success(request, 'Account created!')
return redirect('login')
else:
form = RegisterForm(request.POST)
sp_form = SuperUserForm(request.POST)
messages.warning(request, 'Your account cannot be created.')
return render(request, 'register.html', {'form': form, 'sp_form': sp_form})
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)
data = SpecialUser.objects.all()
dt = {"all": data}
return render(request, "profilepage.html", dt)
else:
messages.info(request, 'invalid credentials')
return redirect('login')
else:
return render(request, 'login.html')
def logout(request):
auth.logout(request)
return redirect('login')
profilepage.html
<h1>{{user.username}}</h1>
<h4>Email : {{user.email}}</h4>
<h5>Phone Number : {{all.phonenumber}}</h5>
{%if user.flag %}
<button>Special User</button>
{%endif%}
here is the correct html you need to see your data
{%for d in all%}
{%ifequal d.user user%}
<h1>{{d.user.username}}</h1>
<h4>Email : {{d.user.email}}</h4>
<h5>Phone Number : {{d.phonenumber}}</h5>
{%if d.flag %}
<button>Special User</button>
{%endif%}
{%endifequal%}
{%endfor%}

Password mismatch in registration form that inherits from UserCreationForm

I have a form that inherits from the UserCreationForm. The file looks like this:
from django import forms
from django.contrib.auth import password_validation
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User, Group
from main.models.users import MyUser
class MyUserCreationForm(UserCreationForm):
email = forms.EmailField(required=True)
group = forms.CharField(max_length=50, required=True)
class Meta:
model = MyUser
fields = ("group", "email", "username", "email", "password1", "password2")
def save(self, commit=True):
user = super(MyUserCreationForm, self).save(commit=False)
user.email = self.cleaned_data["email"]
if commit:
user.save()
return user
For some reason, when trying to fill up the form, I get a password mismatch error like so:
ERROR - {'password_mismatch': "The two password fields didn't match."}
I tried overriding the clean_password1 and clean_password2 with no help. Code:
def clean_password1(self):
password1 = self.cleaned_data.get('password1')
try:
password_validation.validate_password(password1, self.instance)
except forms.ValidationError as error:
# Method inherited from BaseForm
self.add_error('password1', error)
return password1
Any ideas why this is happening? Why is it thinking that both of my passwords are not identical? I'm sure they are, as I tried a million times and even copy and pasted.
view:
def register(request):
if request.method == 'POST':
form = MyUserCreationForm(request.POST)
if form.is_valid():
print(f"Valid form. Choosen group: {form.cleaned_data.get('group')}")
user = form.save()
group = Group.objects.get(name=form.cleaned_data.get('group'))
user.groups.add(group)
login(request, user)
messages.success(request, f"Thanks, {form.cleaned_data.get('username')}, "
f"for signing up as a {form.cleaned_data.get('group')} ")
return redirect('main:homepage')
else:
logger.error(form.error_messages)
for msg in form.error_messages:
messages.error(request, f'{msg}: {form.error_messages[msg]}')
return render(request,
template_name='main/register.html',
context={'form': form})
else:
form = MyUserCreationForm()
return render(request,
template_name='main/register.html',
context={'form': form})
i am not sure about code but you can try this
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
def signup(request):
if request.method == 'POST':
#inhereting Usercreation form
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
#validating the password match while creating the user.
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 = UserCreationForm()
return render(request, 'signup.html', {'form': form})

DJANGO: Trying to save POST data to Student model - IntegrityError

Hi I am trying to save data from a form to Student model; abstract User model.
Please help!
PROBLEM: IntegrityError at /register/ UNIQUE constraint failed:
accounts_students.username
Not sure what the problem, in the view i am trying to clean the data and save it to the database.
Interestingly, the data is being saved, just the page is not being
redirected!
from .models import *
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from betterforms.multiform import MultiModelForm
from django.contrib.auth.forms import UserCreationForm
class RegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = Students
fields = (
'username',
'first_name',
'last_name',
'email',
'password1',
'password2',
'bio',
'location',
'birth_date',
)
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
models.py
class Students(AbstractUser):
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
views.py
from django.shortcuts import render
from django.shortcuts import redirect
from accounts.forms import RegistrationForm, EditProfileForm
from django.contrib.auth.models import User
from accounts.models import Students
from django.contrib.auth.forms import UserChangeForm
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
# Create your views here.
# def login(request):
# return render(request, 'accounts/login.html')
def home(request):
return render(request, 'accounts/home.html')
def login_redirect(request):
return redirect('/login/')
def register(request):
# Once register page loads, either it will send to the server POST data (if the form is submitted), else if it don't send post data create a user form to register
if request.method == "POST":
form = RegistrationForm(request.POST)
if form.is_valid():
bio = form.cleaned_data['bio']
location = form.cleaned_data['location']
birth_date = form.cleaned_data['birth_date']
form.save()
Students.objects.create(bio=bio, location=location, birth_date=birth_date)
# Students.objects.create(user=user)
return redirect('../home/')
else:
# Create the django default user form and send it as a dictionary in args to the reg_form.html page.
form = RegistrationForm()
args = {'form': form}
return render(request, 'accounts/reg_form.html', args)
#login_required
def view_profile(request):
args = {'user': request.user}
return render(request, 'accounts/profile.html', args)
#login_required
def edit_profile(request):
# Handle post request - if the user submits a form change form details and pass the intance user
if request.method == 'POST':
form = EditProfileForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
return redirect('../profile')
# Handles the get request - if no post info is submitted then get the form and display it on the edit profile page.
else:
form = EditProfileForm(instance=request.user)
args = {'form': form}
return render(request, 'accounts/profile_edit.html', args)

Categories