vandelay
vandelay

Reputation: 2075

Form validate like GenericView

When using Generic views, you get the neat feature of django posting the error messages in the template such as "This field is required!".

From what I understand CreateView inherits a method called form_invalid which returns self.render_to_response(self.get_context_data(form=form)) And I'm just guessing that's what's doing the magic?

Now I'm writing a form, and was wondering if it's possible to use that feature aswell?

I have created a custom_user model, and trying to create a simple create functionality. So far I've got:

Models.py

class Custom_User(AbstractBaseUser):

    email = models.EmailField(max_length=250, unique=True)
    password = models.CharField(max_length=100)

    USERNAME_FIELD = 'email'

forms.py

class create_User_Form(forms.ModelForm):

    confirm_password = forms.CharField(widget = forms.PasswordInput(attrs={'class' :'form-control'}))

    class Meta:
        model = Custom_User
        fields = ['email', 'password']

        widgets = {
                   'email' : forms.TextInput(attrs={'class' :'form-control'}),
                   'password' : forms.PasswordInput(attrs={'class' :'form-control'}),
        }

    def clean(self):
        cleaned_data = super(create_User_Form, self).clean()
        password = cleaned_data.get("password")
        confirm_password = cleaned_data.get("confirm_password")

        if password != confirm_password:
            raise forms.ValidationError(
                "password and confirm_password does not match"
            )

        return self.cleaned_data

urls.py

urlpatterns = [
            url(r'^$', views.index, name='index'),    

            url(r'^create_user/$', views.create_user, name='create_user'),  
]

views.py

def create_user(request):

    form = create_User_Form(request.POST)

    if form.is_valid():
        print('valid')
    else:
        print('error')        

    return redirect('Eapp:index')

def index(request):

    create_user_form_ = create_User_Form()

    context = {
               'create_user_form' : create_user_form_,
    }

    return render(request, 'index.html', context)

Upvotes: 1

Views: 66

Answers (1)

e4c5
e4c5

Reputation: 53774

You seem to have mixed up function based views and class based view. What you have attempted is a function base view. To be complete it needs to look like this

def create_user(request):
    if request.method == 'POST':
        create_user_form_ = create_User_Form(request.POST)
        if form.is_valid():
            print('valid')
            return redirect('Eapp:index')
        else:
            print('error')        

    else:
        create_user_form_ = create_User_Form()

    context = {
               'create_user_form' : create_user_form_,
    }

    return render(request, 'index.html', context)

Note that this combines your index and create user methods because they contain functionality that needs to go together.

If on the other hand you want to use a CreateView your code becomes a lot shorter

class UserCreate(CreateView):
    model = Custom_User
    form_class = create_User_Form

That's it really. But you can add refinements.

As a side note. The standard way of naming classes in python is CreateUserForm

Upvotes: 2

Related Questions