Why is the email not saving on user sign up? - django

I went to test the user sign up but it keeps telling me UNIQUE constraint failed: users_customuser.email. That's because the email isn't saving with the rest of the form. I checked the database with an inspector and it shows a blank email field. I put a debug print before form.save and it showed the username email and password so I know the email is in the form data. The view looks fine so it doesn't make sense to me. Tried switching to django 2.2 and it didn't help. The form is valid but the email doesn't save.
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, 'user_accounts/signup.html', {'form': form})
forms.py
class SignUpForm(UserCreationForm):
email = forms.EmailField(max_length=254, help_text='Enter a valid email address')
class Meta:
model = CustomUser
fields = ('username', 'password1', 'password2')
signup.html
{% block content %}
<h2>Sign up</h2>
<form method="post">
{% csrf_token %}
{% for field in form %}
<p>
{{ field.label_tag }}<br>
{{ field }}
{% if field.help_text %}
<small style="color: grey">{{ field.help_text }}</small>
{% endif %}
{% for error in field.errors %}
<p style="color: red">{{ error }}</p>
{% endfor %}
</p>
{% endfor %}
<button type="submit">Sign up</button>
</form>
{% endblock %}

I changed the forms.py to the following
forms.py
class SignUpForm(UserCreationForm):
# Deleted extra email field
class Meta:
model = CustomUser
fields = ('email', 'username', 'password1', 'password2') # <-- Added 'email'

Related

Django: User Login only working with terminal created users

I'm only new to django & this is my first time posting on stack overflow so appologies if I havent done this right.
My problem is that when I use my login function, it only seems to work with those created with the createsuperuser command in the terminal. Those created within the website just dont work.
The users show within the admin panel and have a password within them.
models.py
class Trickster_User(AbstractBaseUser, PermissionsMixin):
UserID = models.AutoField(primary_key=True)
Email = models.EmailField(('Email Address'), unique=True)
Username = models.CharField(('Username'),max_length=25, unique=True)
FirstName = models.CharField(('First Name'),max_length=25)
LastName = models.CharField(('Last Name'),max_length=25)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
objects = CustomUserManager()
USERNAME_FIELD = 'Email'
REQUIRED_FIELDS = ['Username', 'FirstName', 'LastName']
def __str__(self):
return self.FirstName + ' ' + self.LastName
views.py
def user_login(request):
context = {}
user = request.user
if user.is_authenticated:
return redirect('home')
if request.method == "POST":
form = UserAuthenticationForm(request.POST)
if form.is_valid():
Email = request.POST['Email']
password = request.POST['password']
user = authenticate(Email=Email, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
form = UserAuthenticationForm()
context['user_login'] = form
return render(request, 'authentication/login.html', context)
forms.py
class UserAuthenticationForm(forms.ModelForm):
Email = forms.EmailField(widget=forms.EmailInput(attrs={'class':'form-control'}))
password = forms.CharField(label='password', widget=forms.PasswordInput(attrs={'class':'form-control'}))
class Meta:
model = Trickster_User
fields = ('Email', 'password')
def clean(self):
Email = self.cleaned_data['Email']
password = self.cleaned_data['password']
if not authenticate(Email=Email, password=password):
raise forms.ValidationError("Invalid Login")
login.html
{% block content %}
<div class="shadow p-4 mb-5 bg-body rounded">
<h1> Login </h1>
<br/><br/>
<form action="" method=POST enctype="multipart/form-data">
{% csrf_token %}
{% for feild in user_login %}
<p>
{{ feild.label_tag }}
{{ feild}}
{% if feild.help_text %}
<small style="color: grey">{{ feild.help_text }}</small>
{% endif %}
{% for errors in field.errors %}
<p style="color: red">{{ feild.errors }}</p>
{% endfor %}
{% if user_login.non_feild_errors %}
<div style="color:red";>
<p>{{ user_login.non_feild_errors }}</p>
</div>
{% endif %}
</p>
{% endfor %}
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
{% endblock %}
Code to register users:
views.py
def register_user(request):
context = {}
if request.method == "POST":
form = UserRegistrationForm(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)
messages.success(request, ("Registration Successful! Password"))
return redirect('home')
else:
context['UserRegistrationForm'] = form
else:
form = UserRegistrationForm()
context['UserRegistrationForm'] = form
return render(request, 'authentication/register_user.html', context)
register_user.html
{% block content %}
{% if form.errors %}
<div class="alert alert-warning alert-dismissible fade show" role="alert">
There was an error with your form!
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{% endif %}
<div class="shadow p-4 mb-5 bg-body rounded">
<h1> Register </h1>
<br/><br/>
<form action="{% url 'register_user' %}" method=POST enctype="multipart/form-data">
{% csrf_token %}
{% for feild in UserRegistrationForm %}
<p>
{{ feild.label_tag }}
{{ feild}}
{% if feild.help_text %}
<small style="color: grey">{{ feild.help_text }}</small>
{% endif %}
{% for errors in field.errors %}
<p style="color: red">{{ feild.errors }}</p>
{% endfor %}
</p>
{% endfor %}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
{% endblock %}
Ive seen one other post on something simmilar to this but the only solution posted was to change the 'is_active' status to True by default.
I tried this and am still running into same issue.

Account with this Email already exists. how to fix this?

I tried to create a login form. But when I try to login django gives the error that Account with this Email already exists. i don`t now how to fix this.Help me plz
Here is my code, please tell me where I'm going wrong:
forms.py
class AccountAuthenticationForm(forms.ModelForm):
password = forms.CharField(label='Password', widget=forms.PasswordInput)
class Meta:
model= Account
fields = ('email', 'password')
def clen(self):
email = self.cleaned_data['email']
password = self.cleaned_data['password']
if not authenticate(email=email, password=password):
raise forms.ValidationError("Invalid login")
views.py
def login_view(request):
context = {}
user = request.user
if user.is_authenticated:
return redirect("home")
if request.POST:
form = AccountAuthenticationForm(request.POST)
if form.is_valid():
email=request.POST['email']
password = request.POST['password']
user =authenticate(email=email, password=password)
if user:
login(request,user)
return redirect("home")
else:
form = AccountAuthenticationForm()
context['login_form'] = form
return render(request, 'account/login.html', context)
login.html
{% extends 'base.html' %}
{% block content %}
<h2>Login</h2>
<form method="post">{% csrf_token %}
{% for field in login_form %}
<p>
{{field.label_tag}}
{{field}}
{% if field.help_text %}
<small style="color:grey">{field.help_text}</small>
{% endif %}
{% for error in field.errors %}
<p style="color:red">{{error}}</p>
{% endfor %}
{% if login_form.non_field_errors %}
<div style="color:red";>
<p>{{login_form.non_field_errors}}</p>
</div>
{% endif %}
</p>
{% endfor %}
<button type="submit">Log in</button>
</form>
{% endblock content %}
I'm just getting started with Django. I will be glad if you point out my mistake
solved
i just added email field to the class AccountAuthentcationForm in forms.py
and changed from forms.ModelForm to forms.Form

Django custom registration form html

New to Django and I am attempting to create a customer registration form and was successful. However the tutorial I followed showed me how to iterate through a loop, the contents of my registration_form which doesn't really give me much flexibility from a UI perspective, or so it seems. Can someone tell me how to customize this form based on the code I've got?
HTML:
<h1>This is the register.html</h1>
<div class="col-md-4 offset-md-4">
<form method="post">
{% csrf_token %}
{% for field in registration_form %}
<p>
{{field.label_tag}}
{{field}}
{% if field.help_text %}
<small style="color: grey;">{{field.help_text}}</small>
{% endif %}
{% for error in field.errors %}
<p style="color: grey;">{{error}}</p>
{% endfor %}
</p>
{% endfor %}
<button type="submit">Register</button>
</form>
</div>
views.py
def registration_view(request):
context = {}
if request.POST:
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
email = form.cleaned_data.get('email')
raw_password = form.cleaned_data.get('password1')
account = authenticate(email=email, password=raw_password)
login(request, account)
return redirect('home')
else:
context['registration_form'] = form
else:
form = RegistrationForm()
context['registration_form'] = form
print(context)
return render(request, 'accounts/register.html', context)
forms.py
class RegistrationForm(UserCreationForm):
email = forms.EmailField(max_length=100, help_text='Required. Add a valid email address')
class Meta:
model = Account
fields = ('email', 'username', 'password1', 'password2', 'first_name', 'last_name')
the form renders and works fine with registration, just looks kinda crappy. thanks!
You could render each field individually and take advantage of bootstrap styling as well. For example for the email field, you could have something like below
<div class="form-group">
{{ registration_form.email.label_tag }}
{{ registration_form.email }}
</div>
You can also have a div below it to display its errors on post
<div class="errors">
{% if registration_form.email.errors %}
{% for error in registration_form.email.errors %}
<strong>{{ error|escape }}</strong>
{% endfor %}
{% endif %}
</div>

Issue while returning the errors list

Below is code in views.py file.
class login(View):
def get(self, request):
return render(request, 'login.html')
def post(self, request):
form = LoginForm(request.POST)
if form.is_valid():
username = request.POST.get('username')
password = request.POST.get('password')
return HttpResponse("ok")
else:
form = LoginForm()
return HttpResponse(form)
Below code is in template file.
<form method="post" action="{% url 'authapp:login' %}">
{% csrf_token %}
<input type="text" name="username" class="form-control">
<input type="password" name="password" class="form-control">
<button type="submit" class="btn btn-primary">
Login
</button>
</form>
below code is in forms.py file
from django import forms
class LoginForm(forms.Form):
username = forms.CharField(max_length = 50, required = True),
password = forms.CharField(max_length = 50, required = True)
Issue Details
When i submit the form with both username and password empty, it returns just a textfield of password.
I was expecting a list of errors for required username and password. As both are required in forms file.
Can you please suggest something?
change your views.py so it actually return the forms to the template:
class login(View):
if request.method == 'GET':
form = LoginForm()
return render(request, 'login.html', {'form': form})
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
# some validation stuffs
return HttpResponse("ok")
else:
return render(request, 'login.html', {'form': form})
Your forms.py so it actually use to render:
from django import forms
class LoginForm(forms.Form):
username = forms.CharField(label="username", max_length=50, required=True, widget=forms.TextInput(attrs={'class' : 'form-control'}))
password = forms.CharField(label="password", max_length=50, required=True, widget=forms.PasswordInput(attrs={'class': 'form-control'}))
And your template:
<form method="post" action="{% url 'authapp:login' %}">
{% csrf_token %}
{{ form.username }}
{% if form.username.errors %}
{% for error in form.username.errors %}
{{ error }}
{% endfor %}
{% endif %}
{{ form.password }}
{% if form.password.errors %}
{% for error in form.password.errors %}
{{ error }}
{% endfor %}
{% endif %}
<button type="submit" class="btn btn-primary">
Login
</button>
</form>
I think you should finish reading the form docs before you doing this since last question you didn't know that you have to add forms.py in your project
You need to enable the debug true in settings.py file
DEBUG = True

login with forms doesn't work

so I'm making a login page with forms, the problem is it doesn't work :D
this is my form
forms.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', 'password',]
my views.py
def user_login(request):
if request.method == 'POST':
login_form = UserForm(request.POST)
if login_form.is_valid():
username = login_form.cleaned_data.get('username')
raw_password = login_form.cleaned_data.get('password')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('restricted')
else:
login_form = UserForm()
return render(request, 'userlogin.html', {'login_form': login_form})
and my html
<h2>Login</h2>
<form method="post">
{% csrf_token %}
{{ login_form.username }}
<br>
{{ login_form.password }}
<br>
<button type="submit">Login</button>
</form>
the restricted is a html that checks which user is logged in. and it works fine
i'm not sure why it isn't working cuz it keeps redirecting me to the loginuser.html page instead of redirecting me to restricted page which only appears if a user is logged in.
You need to add more details but here is a step by step guide to login users:
forms.py:
from django.contrib.auth import authenticate, get_user_model
User = get_user_model()
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField()
def clean(self, *args, **kwargs):
username = self.cleaned_data.get("username")
password = self.cleaned_data.get("password")
user_obj = User.objects.filter(username=username).first()
if not user_obj:
raise forms.ValidationError("Invalid credentials")
else:
if not user_obj.check_password(password):
raise forms.ValidationError("Invalid credentials")
return super(LoginForm, self).clean(*args, **kwargs)
and in your views.py:
from django.contrib.auth import login
from .forms import LoginForm # or where you have the LoginForm
User = get_user_model()
def user_login(request):
form = LoginForm(request.POST or None)
if not request.user.is_authenticated:
if form.is_valid():
username_ = form.cleaned_data.get('username')
user_obj = User.objects.get(username__iexact=username_)
login(request, user_obj)
return #something
else:
# show an error or etc
...
else:
# user is authenticated before and he is in.
...
and your template.html:
<form action="" method="post">
{% csrf_token %}
<input type="text" name="username">
<hr>
<input type="password" name="password">
<hr>
<button type="submit">Login</button>
</form>
Note:
you can use django to render the form but you need to make some changes on form fields like password (adding PasswordInput widget)
Add block with form errors to your template
<h2>Login</h2>
<form method="post">
<!-- form errors -->
{% if login_form.errors %}
{% for field in login_form %}
{% for error in field.errors %}
<strong>{{ error|escape }}</strong>
{% endfor %}
{% endfor %}
{% for error in login_form.non_field_errors %}
<strong>{{ error|escape }}</strong>
{% endfor %}
{% endif %}
<!-- form errors -->
{% csrf_token %}
{{ login_form.username }}
<br>
{{ login_form.password }}
<br>
<button type="submit">Login</button>
</form>