0

(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")
John Roger
  • 13
  • 2
  • You need to include the form errors when you render the `notcreated.html` template. You will need to use [`form.errors`](https://docs.djangoproject.com/en/1.11/ref/forms/api/#django.forms.Form.errors). That link describes the format of `form.errors`. – FamousJameous Apr 18 '17 at 17:49
  • I can use the notcreated.html to show the error message, but that deletes everything the user as typed in the form, so i am just using that as a substitution for now. I am trying to get the username to be validated before it even processes to views.py – John Roger Apr 18 '17 at 18:59
  • The normal way to do what you describe is to have a single view. On POST, if the form fails to validate, the form object is passed back to the original template. The form object contains the user's previous input. For examples see: https://docs.djangoproject.com/en/1.10/topics/forms/ or http://stackoverflow.com/a/14647770/3901060. – FamousJameous Apr 18 '17 at 19:40
  • Thank you, I understand now. I thought there a way to do it with forms.py alone but i guess server wouldn't be able to get the username without the information going through POST first. – John Roger Apr 19 '17 at 02:55

0 Answers0