(New at Django)I've tried everything and spent the whole day trying to get this to work. I am trying to check if user exists and display ValidationError if it already exists. Right now, i am using views.py to show template that says account not created because the validation error that forms.py should be taking care of is not showing.
forms.py
from django.contrib.auth.models import User
from django import forms
class UserForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(UserForm, self).__init__(*args, **kwargs)
self.fields['email'].required = True
password = forms.CharField(widget=forms.PasswordInput)
def clean_username(self):
username = self.cleaned_data['username']
if User.objects.filter(username=username).exists():
raise forms.ValidationError("That user is already taken")
return username
class Meta:
model = User
fields = ['username', 'password', 'email']
labels = {
"email": "Email"
}
# including my login form too just in case
class LoginForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'password']
labels = {
"email": "Email"
}
views.py
from django.shortcuts import render, redirect
from .forms import UserForm
def index(request):
if request.user.is_authenticated:
return redirect('/myaccount')
else:
title = "welcome"
form = UserForm()
context = {
"template_title": title,
"form": form
}
return render(request, "index.html", context)
def new_user(request):
if request.method == "POST":
form = UserForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
email = form.cleaned_data.get("email")
form.save()
return render(request, "created.html")
return render(request, "notcreated.html")