Skip to content
Advertisement

I am trying to add a new field to the default Django Form and am getting an error when I’m trying to import a class from a forms.py file I made

The error is occurring in views.py file in which when I try to import the form class I made from my forms .py file I get an error of…

Import ".forms" could not be resolved

Here is what my views.py file looks like:

    from django.shortcuts import render, redirect
from .forms import RegisterForm
# Create your views here.

def register(response):
    if response.method == "POST":
        form = RegisterForm(response.POST)
        if form.is_valid():
            form.save()

        return redirect("/home")
    else:
        form = RegisterForm()

    return render(response,"register/register.html",{"form":form})

And here is my forms.py file

    from django import forms
from django.contrib.auth import login, authenticate
from django.contrib.auth import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

class RegisterForm(UserCreationForm):
    email = forms.EmailField()

    class Meta: 
        model = User
        fields = ["username", "email", "password1", "password2"]

Why am I getting that error/what am I missing?

Advertisement

Answer

You problem comes from importing “from django.contrib.auth import forms” so i figure out that when you comment it out or just delete it, everything should work fine!.

from django import forms
from django.contrib.auth import login, authenticate
# This is where your problem stems "from django.contrib.auth import forms"
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User


class RegisterForm(UserCreationForm):
    email = forms.EmailField()

    class Meta: 
        model = User
        fields = ["username", "email", "password1", "password2"]

Well in your view the conditional statement wasn’t meeting the condition after the form is saved and so it wouldn’t redirect to the home page, you needed to put the redirect right below the form.save() for it to meet the condition as in what i have done.

def register(request):
    if request.method == "POST":
        form = RegisterForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect("/home")
    else:
        form = RegisterForm()

    return render(request,"register/register.html",{"form":form})
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement