My views-
from django.shortcuts import render, redirect
from .AuthForms import registerUserForm
from django.contrib import messages
from django.contrib.auth import login, authenticate
def registerUsers(request):
if request.method == 'POST':
ucf = registerUserForm(request.POST)
if ucf.is_valid():
ucf.save()
new_user = authenticate(username = ucf.cleaned_data['username'], password = ucf.cleaned_data['password1'])
login(request, new_user)
return redirect('content')
else:
ucf = registerUserForm()
return render(request, 'LoginAndSignUp/SignUpPage.html', {'ucf': ucf})
My form -
I have extended the usercreationform
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm , PasswordResetForm
from django import forms
class registerUserForm(UserCreationForm):
email = forms.EmailField(widget = forms.EmailInput(attrs={'placeholder':'Email', 'autocomplete':'off'}))
username = forms.CharField(widget= forms.TextInput(attrs={'placeholder':'Username','autocomplete':'off',}))
password1 = forms.CharField(widget= forms.PasswordInput(attrs={'placeholder':'Password'}))
password2 = None
class meta:
model = User
fields = ['username', 'email', 'password1']
class userLoginForm(AuthenticationForm):
username = forms.CharField(widget= forms.TextInput(attrs={'placeholder':'Username','autocomplete':'off'}))
password = forms.CharField(widget= forms.PasswordInput(attrs={'placeholder':'Password'}))
class userPasswordResetEmailForm(PasswordResetForm):
email = forms.EmailField(widget = forms.EmailInput(attrs={'placeholder':'Enter your email', 'autocomplete':'off',}))
class Meta:
model = User
fields = '__all__'
Here is my template. I suppose everything is correct but still its not saving the email
<form novalidate action="" method="post">
{%csrf_token%}
<div class="fieldWrapper">
{{ucf.email.errors}}
{{ucf.email}}
</div>
<div class="fieldWrapper">
{{ucf.username.errors}}
{{ucf.username}}
</div>
<div class="fieldWrapper">
{{ucf.password1.errors}}
{{ucf.password1}}
</div>
<div style="margin-bottom: 4%;">
<span class="director">Already with us? Log In</span>
<div class="director">
<i class="fa fa-compass"></i> Explore anonymously
</div>
</div>
<button class="primaryButton" type="submit">Sign Up</button>
</form>
The email field is not saving the email to database wherease the username and password is correctly being saved. Someone please help
Your code seems to be fine. I recreated your project and it works as intended. username, password and email are saved to the auth_user table. This is what mine looks like:
urls.py
urlpatterns = [
// other urls
path('users/', register_users, name='create_user')
]
views.py
from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate
from users.forms import RegisterUserForm
def register_users(request):
if request.method == 'POST':
ucf = RegisterUserForm(request.POST)
if ucf.is_valid():
ucf.save()
new_user = authenticate(username=ucf.cleaned_data['username'], password=ucf.cleaned_data['password1'])
login(request, new_user)
return redirect('content')
else:
ucf = RegisterUserForm()
return render(request, 'users/sign_up_page.html', {'ucf': ucf})
forms.py
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django import forms
class RegisterUserForm(UserCreationForm):
email = forms.EmailField(widget=forms.EmailInput(attrs={'placeholder': 'Email', 'autocomplete': 'off'}))
username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Username', 'autocomplete': 'off'}))
password1 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password'}))
password2 = None
class Meta:
model = User
fields = ['username', 'email', 'password1']
sign_up_page.html
<form novalidate action="" method="post">
{% csrf_token %}
<div class="fieldWrapper">
{{ ucf.email.errors }}
{{ ucf.email }}
</div>
<div class="fieldWrapper">
{{ ucf.username.errors }}
{{ ucf.username }}
</div>
<div class="fieldWrapper">
{{ ucf.password1.errors }}
{{ ucf.password1 }}
</div>
<div style="margin-bottom: 4%;">
{# <span class="director">Already with us? Log In</span>#}
<div class="director">
{# <i class="fa fa-compass"></i> Explore anonymously#}
</div>
</div>
<button class="primaryButton" type="submit">Sign Up</button>
</form>
Related
When I try to click on login button it always execute the invalid credentials instead of redirect to the index page.. What I did is that in database create table name signup and wants to validate all the data from that table.. Here signup_data function is works well but in login_data cannot authenticate the user.
Models.py
from django.db import models
class signup(models.Model):
username = models.CharField(max_length=10)
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
email = models.EmailField()
password = models.CharField(max_length=10)
Forms.py
from django.forms import ModelForm
from . models import signup
from django import forms
class signupform(ModelForm):
username= forms.CharField(max_length=10,widget=forms.TextInput(attrs={'class':'form-control'}))
first_name = forms.CharField(max_length=20, widget=forms.TextInput(attrs={'class': 'form-control'}))
last_name = forms.CharField(max_length=20,widget=forms.TextInput(attrs={'class': 'form-control'}))
email = forms.EmailField(max_length=20,widget=forms.EmailInput(attrs={'class': 'form-control'}))
password = forms.CharField(max_length=10,widget=forms.PasswordInput(attrs={'class':'form-control'}))
class Meta:
model = signup
fields = '__all__'
Views.py
from django.shortcuts import render,redirect
from . forms import signupform
from . models import signup
from django.contrib import messages
from django.contrib.auth import login,authenticate
def index(response):
return render(response,'login_module/index.html')
def signup_data(response):
if response.method == 'POST':
form = signupform(response.POST)
if form.is_valid():
username = form.cleaned_data['username']
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
email = form.cleaned_data['email']
password = form.cleaned_data['password']
if signup.objects.filter(username=username).exists():
# messages.add_message(response,messages.WARNING,'Username is already taken')
messages.error(response,'Username is already taken')
return redirect('signup')
elif signup.objects.filter(email=email).exists():
messages.error(response,'Email is already taken')
# messages.add_message(response,messages.WARNING,'Email is already taken')
return redirect('signup')
else:
register_instance = signup(username=username, first_name=first_name, last_name=last_name, email=email, password=password)
register_instance.save()
messages.success(response,'Registered Successfull')
return redirect('signup')
else:
form = signupform()
return render(response,'login_module/signup.html',{'form':form, 'message': messages})
def login_data(request):
form = signupform(request.POST or None)
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
login(request,user)
return redirect('index')
else:
messages.error(request,'Invalid Credentials')
return redirect('login')
else:
return render(request,'login_module/login.html',{'form':form, 'message': messages})
Login.html
{% extends 'login_module/base.html' %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-md-12 text-center mt-50">
<h1>Login Page</h1>
</div>
</div>
<div class="row">
<div class="col-md-4 offset-md-4 ">
<form method="post" action="{% url 'login' %}">
{% csrf_token %}
<div class="form-group rounded-top">
{{ form.username.label_tag }} {{ form.username }}
</div>
<div class="form-group rounded-top">
{{ form.password.label_tag }} {{ form.password }}
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary">Login</button>
</div>
</form>
</div>
</div>
<div class="text-center mt-50">
{% if messages %}
{% for message in messages %}
<div class="alert alert-danger" role="alert">
{{ message }}
{% endfor %}
{% endif %}
</div>
</div>
{% endblock %}
Login Page
As far as I can tell you are creating a signup object when signing up, but when trying to login with authenticate django is looking for the generic User model. You have to create a User in the database rather than a signup object to use authenticate.
This is a registration page function
def register(request):
if request.method=="POST":
username= request.POST['username']
email= request.POST['email']
password= request.POST['password']
password2= request.POST['password2']
if password == password2:
if User.objects.filter(email=email).exists():
messages.info(request,'Email Already Used')
return redirect('register')
elif User.objects.filter(username=username).exists():
messages.info(request,'Username Already Used')
return redirect('register')
else:
user=User.objects.create_user(username=username,email=email,password=password2) #create_user not working
user.save()
return redirect('login')
else:
messages.info(request,'password not same')
return redirect('register')
else:
return render(request,'register.html')
this is the register.html file
<h1>SIGN UP HERE</h1>
<style>
h5 {
color: red
}
</style>
{% for message in massages %}
<h5>{{message}}</h5>
{% endfor %}
<form method="POST" action="register">
{% csrf_token %}
<p>Username(admission number):</p>
<input type="text" name="username" />
<P>Email</P>
<input type="email" name="email" />
<p>Password:</p>
<input type="password" name="password" />
<p>Repeat password</p>
<input type="password" name="password2" /><br>
<input type="submit" />
</form>
I have imported User model for create_user method
from django.contrib.auth.models import User
but its not working
I don't know why you would want to create a function-based view for User creation. A much simpler way to do this is to build a class-based view using django's User model:
from users.models import User
from .forms import RegisterForm
from django.views import generic
class UserRegistration(generic.CreateView):
form_class = RegisterForm
template_name = 'register.html'
success_url = reverse_lazy('home')
In your forms.py file (in whichever app you are creating the users) you add the RegisterForm:
from django.contrib.auth.models import User
from django import forms
from django.contrib.auth.forms import UserCreationForm
class RegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2')
username, password1, and password2 are already built in fields for django Users, so it's already done for you.
Then in your register.html file all you need is to add the from:
<h1>SIGN UP HERE</h1>
<style>
h5 {
color: red
}
</style>
{% for message in massages %}
<h5>{{message}}</h5>
{% endfor %}
<form method="POST" action="register">
{% csrf_token %}
{{form.as_p}}
</form>
{{form.as_p}} renders all the fields in the order they appear in in your RegisterForm.
I am trying to create a student register page that allows the student to upload a profile photo. I am using Django User model and a StudentProfile model that has a OneToOne relation with User. Here are my codes:
student\models.py:
from django.db import models
from django.contrib.auth.models import User
class StudentProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,)
avatar = models.ImageField(upload_to='student_profile/', null=True, blank=True)
def __str__(self):
return self.user.username
students/form.py:
from django import forms
class ImageUploadForm(forms.Form):
profile_photo = forms.ImageField()
eLearning/views.py:
from django.contrib.auth import authenticate, login, get_user_model
from django.http import HttpResponse
from django.shortcuts import render, redirect
from .forms import LoginForm, RegisterForm
from students.forms import ImageUploadForm
from students.models import StudentProfile
User = get_user_model()
def register_page(request):
register_form = RegisterForm(request.POST or None)
photo_upload_form = ImageUploadForm(request.POST, request.FILES)
context = {
"register_form": register_form,
"photo_upload form": photo_upload_form
}
if register_form.is_valid():
# print(register_form.cleaned_data)
username = register_form.cleaned_data.get("username")
first_name = register_form.cleaned_data.get("first_name")
last_name = register_form.cleaned_data.get("last_name")
email = register_form.cleaned_data.get("email")
password = register_form.cleaned_data.get("password")
new_user = User.objects.create_user(
username, email, password,
first_name=first_name,
last_name=last_name,
)
if photo_upload_form.is_valid():
user = username
avatar = photo_upload_form.cleaned_data.get("profile_photo")
new_user_profile = StudentProfile.objects.create(user, avatar)
print(new_user)
return render(request, "auth/register.html", context)
auth/register.html:
{% extends "base.html" %}
{% load static %}
{% block content %}
{% load crispy_forms_tags %}
<div class="container">
<div class="row my-4">
<div class="col-5">
<form action="" method="post" class="form-control">
{% csrf_token %}
{{ register_form|crispy }}
<input type="submit" class="btn btn-default" value="Submit">
</form>
</div>
<div class="col-5">
<form method="post" enctype="multipart/form-data" class="form-control">
{% csrf_token %}
<input id="id_image" type="file" class="my-2" name="image">
{{ photo_upload_form|crispy }}
</form>
</div>
</div>
</div>
{% endblock %}
I am facing 2 problems:
1) The ImageUploadForm is not rendering on to register.html
2) A StudentProfile is not being created. User is being created fine.
I also tried replacing form with ModelForm for ImageUploadForm but I get a NULL constraint for student_user since Django doesn't what user for StudentProfile is.
I have been looking through Stack Overflow. All solutions are about how to upload a user image to Django admin but I haven't found anything that shows how to associate the uploaded image to User model during registration. Forgive me if this is a repeated question. Thanks.
In your eLearning/views.py:
the context you are passing to the html page the _ is missing
context = {
"register_form": register_form,
"photo_upload form": photo_upload_form
}
This will be the reason for the ImageUploadForm is not rendering on to register.html
It's should be like
context = {
"register_form": register_form,
"photo_upload_form": photo_upload_form
}
So I figured it out. The real issue was with the register.html code. The submit button only worked for the register_form so the photo upload form was not validating, hence student profile entry was not being created. Here's the updated code:
eLearning/views.py:
from students.forms import ImageUploadForm
from students.views import upload_pic
def register_page(request):
register_form = RegisterForm(request.POST or None)
photo_upload_form = ImageUploadForm(request.POST, request.FILES)
context = {
"register_form": register_form,
"photo_upload_form": photo_upload_form
}
if register_form.is_valid():
username = register_form.cleaned_data.get("username")
first_name = register_form.cleaned_data.get("first_name")
last_name = register_form.cleaned_data.get("last_name")
email = register_form.cleaned_data.get("email")
password = register_form.cleaned_data.get("password")
new_user = User.objects.create_user(
username, email, password,
first_name=first_name,
last_name=last_name,
)
upload_pic(request, photo_upload_form, username=username)
return render(request, "auth/register.html", context)
students/views.py:
from django.contrib.auth import get_user_model
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect, HttpResponse
from .models import StudentProfile
from .forms import ImageUploadForm
def upload_pic(request, form, username):
if request.method == 'POST':
if form.is_valid():
User = get_user_model()
user = User.objects.get(username=username)
avatar = form.cleaned_data.get('profile_photo')
new_user_profile = StudentProfile.objects.create(user=user, avatar=avatar)
new_user_profile.save()
register.html:
{% extends "base.html" %}
{% load static %}
{% block content %}
{% load crispy_forms_tags %}
<div class="container">
<div class="row my-4">
<div class="col-5">
<form action="" method="post" enctype="multipart/form-data" class="form-control">
{% csrf_token %}
{{ register_form|crispy }}
{{ photo_upload_form|crispy }}
<input type="submit" class="btn btn-default" value="Submit">
</form>
</div>
</div>
</div>
{% endblock %}
You have to make sure enctype="multipart/form-data" is inside your tags or the image upload form will not get validated. I would also recommend adding an image validation method to your form.py. Something Sachin pointed out earlier: image form and validation. Hope this helps.
I am new to django, I created my custom user(auth_user) model. I need to create student registration form using custom user model according to my custom object
I have two models Title, User like this:
from django.db import models
#from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from django.db.models.signals import post_save
from django.contrib.auth.models import AbstractUser
class Title(models.Model):
value = models.CharField(max_length=100, null=True, blank=True)
def __str__(self):
return self.value
class Meta:
db_table = 'title'
class User(AbstractUser):
title = models.ForeignKey(Title, on_delete=models.CASCADE, null=True, blank=True)
class Meta:
db_table = 'user'
settings.py:
AUTH_USER_MODEL = 'student.User'
Here i have ForeignKey title field and User default fields first_name, last_name, email,password
My forms.py:
from django import forms
from django.contrib.auth.models import User
from django.forms import ModelForm
from django.core import validators
from student.models import User
from student.models import Title
class StudentRegistrationForm(forms.Form):
filenumber = forms.CharField(label='Filenumber', max_length=45)
class StudentNewRegistrationForm(forms.ModelForm):
title = forms.CharField(required=True)
username = forms.CharField(required=True)
first_name = forms.CharField(required=True)
last_name = forms.CharField(required=True)
email = forms.EmailField(required=True)
password1 = forms.CharField(required=True)
password2 = forms.CharField(required=True)
def __init__(self, *args, **kwargs):
super(StudentNewRegistrationForm, self).__init__(*args, **kwargs)
self.fields['title'] = forms.ModelChoiceField(queryset=Title.objects.all(), empty_label='Choose a title',required=False)
class Meta:
model = User
fields = ['title','username', 'first_name', 'last_name','email' 'password1', 'password2']
def save(self, commit=True):
user = super(StudentNewRegistrationForm, self).save(commit=False)
user.username = self.cleaned_data['username']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
user.title = self.cleaned_data['title']
user.password1 = user.set_password(self.cleaned_data['password1'])
user.password2 = user.set_password(self.cleaned_data['password2'])
if commit:
user.save()
return user
Here i have api response like below:
{"candidate":{"firstname":"Testuser","lastname":"test","salutation":10000,"email":"testing#gmail.com","username":"test"}}
This response coming form studentregistrationview:
from django.shortcuts import render, redirect
from django.urls import reverse
from student.forms import RegistrationForm
from django.contrib.auth import get_user_model
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.decorators import login_required
from .forms import StudentRegistrationForm, StudentNewRegistrationForm
import requests
from django.http import JsonResponse
from django.http import HttpResponse
#from django.contrib.auth import get_user_model
from student.models import User
from student.models import Title
import json
import urllib
from django.conf import settings
from django.contrib import messages
def studentregistration(request):
form = StudentRegistrationForm()
if request.method == 'POST':
form = StudentRegistrationForm(request.POST)
if form.is_valid():
data = form.cleaned_data
inputdata = data.get('filenumber')
url = 'https://myapiurl/' + inputdata
result = requests.get(url)
finalresult = result.json()
studentapires = {'studentres': finalresult}
request.session['studentapires'] = studentapires
return redirect('/student/studentnewregistration')
else:
form = StudentRegistrationForm()
return render(request, 'student/studentregister.html', {'form': form})
I am creating new user object like below and i tried to persist object, here issue object is not persisting to user table
student_new_registration view i tried to create new User object like below
student_new_registration.py:
def student_new_registration(request):
studentapires = request.session.get('studentapires', None)
jsonresult = studentapires['studentres']['candidate']
user = User()
if jsonresult['salutation'] == 100000000:
salutation = 'Mister'
elif jsonresult['salutation'] == 100000002:
salutation = 'Madam'
title = Title.objects.get(value=salutation)
user.title = title
user.first_name = jsonresult['firstname']
user.last_name = jsonresult['lastname']
user.email = jsonresult['email']
user.username = jsonresult['username']
if request.method == 'POST':
form = StudentNewRegistrationForm(request.POST, instance=user)
if form.is_valid():
form.save()
return HttpResponse("Registration Completed")
return HttpResponse("Please Check Your Registration Form")
else:
form = StudentNewRegistrationForm(instance=user)
args = {'form': form}
return render(request, 'student/studentnewregistrationform.html', args)
Error:
full_clean() missing 1 required positional argument: 'self', form is not submitting (means form not going inside form.is_valid())
studentnewregistrationform.html:
{% extends 'base.html' %}
{% block head %}
<title>Student Profile Form</title>
{% endblock %}
{% block body %}
<div class="container">
<form method="post">
{% csrf_token %}
<div class="row">
<div class="col-sm-4">
<h3> Student Profile Form</h3>
</div>
</div>
<br>
<div class="row">
<div class="col-sm-2">{{ form.title.label }}</div>
<div class="col-sm-3">{{ form.title }}</div>
<div class="col-sm-4">{{ form.title.errors }}</div>
</div>
<br>
<div class="row">
<div class="col-sm-2">{{ form.first_name.label }}</div>
<div class="col-sm-3">{{ form.first_name }}</div>
<div class="col-sm-4">{{ form.first_name.errors }}</div>
</div>
<br>
<div class="row">
<div class="col-sm-2">{{ form.last_name.label }}</div>
<div class="col-sm-3">{{ form.last_name }}</div>
<div class="col-sm-4">{{ form.last_name.errors }}</div>
</div>
<br>
<div class="row">
<div class="col-sm-2">{{ form.email.label }}</div>
<div class="col-sm-3">{{ form.email }}</div>
<div class="col-sm-4">{{ form.email.errors }}</div>
</div>
<br>
<br>
<div class="row">
<div class="col-sm-2">{{ form.username.label }}</div>
<div class="col-sm-3">{{ form.username }}</div>
<div class="col-sm-4">{{ form.username.errors }}</div>
</div>
<br>
<div class="row">
<div class="col-sm-2"><label for="{{ form.password1.label }}">Password</label></div>
<div class="col-sm-3">{{ form.password1 }}</div>
<div class="col-sm-4">{{ form.password1.errors }}</div>
</div>
<br>
<div class="row">
<div class="col-sm-2"><label for="{{ form.password2.id_for_label }}">ConfirmPassword</label></div>
<div class="col-sm-3">{{ form.password2 }}</div>
<div class="col-sm-4">{{ form.password2.errors }}</div>
</div>
<br><br>
<div class="row">
<div class="col-sm-2 col-sm-offset-2"> <input type="submit" name="submit" value="Submit" class="btn btn-primary"/></div>
<div class="col-sm-2"></div>
</div>
</form>
</div>
{% endblock %}
here issue is i am able to render all fields to registration form but i am not able to persist data and while persisting custom object i am getting this error
Manager isn't available; 'auth.User' has been swapped for 'student.User'
please help me any one, Thanks in advance...
You need to change User model inside your views.py file and in any other files where you are using User class. To new model. For this try to add following import:
from django.contrib.auth import get_user_model
User = get_user_model()
Instead of
from django.contrib.auth.models import User
When I try to test my form with an email which has already been entered into the database it doesn't give the error message like it should, it redirects back to the homepage.
My views.py file looks like this:
from django.shortcuts import render
from .forms import LotteryForm
from django.http import HttpResponseRedirect
# Create your views here.
def lottery_list(request):
return render(request, 'lottery/lottery.html', {})
def lottery_new(request):
if request.method == 'POST':
form = LotteryForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('lottery_submitted')
else:
return render(request, 'lottery/lottery.html' {'form': LotteryForm()})
else:
form = LotteryForm()
return render(request, 'lottery/lottery.html', {'form': LotteryForm()})
My form is:
from django import forms
from django.db import models
from django.forms import ModelForm
from .models import Lottery
from .models import Lottery_user
from django.core.exceptions import ValidationError
class LotteryForm(forms.ModelForm):
lottery_type = forms.ModelChoiceField(queryset = Lottery.objects.all(), empty_label=None)
first_name = forms.CharField(required=True)
last_name = forms.CharField(required=True)
lottery_numbers = forms.CharField(max_length=12, required=True)
email = forms.EmailField(required=True)
telephone = forms.CharField(max_length=18,
error_messages={'invalid':'Enter a valid mobile number',
'required':'Enter a valid mobile number'})
def clean_email(self):
email = self.cleaned_data['email']
if Lottery_user.objects.filter(email=email).exists():
raise ValidationError("Email already exists")
return email
if Lottery_user.objects.filter(email=self.cleaned_data['email']).exists():
raise ValidationError("You've already entered")
return email
class Meta:
model = Lottery_user
fields = ['lottery_numbers', 'lottery_type', 'first_name', 'last_name', 'email', 'telephone',]
Template form:
<form action="{% url 'lottery_new' %}" method="post">
{% csrf_token %}
<div class="fieldWrapper">
<label for="lotterytype">Choose a lottery:</label>
{{ form.lottery_type }}
<p>See <a href=lottery_instructions>instructions and rules</a></p>
</div>
<div class="fieldWrapper">
<label for="lotterynumbers">Lottery Numbers:</label>
{{ form.lottery_numbers }}
</div>
<div class="fieldWrapper">
<label for="firstname">First name:</label>
{{ form.first_name }}
</div>
<div class="fieldWrapper">
<label for="lastname">Last name:</label>
{{ form.last_name }}
</div>
<div class="fieldWrapper">
{{ form.email.errors }}
{{ form.email.non_field_errors }}
<label for="email">Email:</label>
{{ form.email }}
</div>
<div class="fieldWrapper">
<label for="phonenumber">Telephone Number:</label>
{{ form.telephone }}
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
I want a user to not be able to enter twice with the same email, so it should error when the user clicks submit with a used email address.
Also, does anyone know how to get the error messages to show before the user submits rather than afterwards?
You return a newly instantiated form when the form is invalid, when you should instead return the invalid form (with the errors). Try:
def lottery_new(request):
if request.method == 'POST':
form = LotteryForm(request.POST)
if form.is_valid():
....
else:
return render(request, 'lottery/lottery.html' {'form': form})