'How do I fix the error of my django form not having cleaned_data attribute?
I have this form:
class RegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ["username", "email", "password1",
"pass"]
And this View:
def register(req):
if req.method == 'POST':
form = RegisterForm(req.POST)
print('yaml')
if form.is_valid():
form.save()
return redirect("/home")
else:
form = RegisterForm()
form.save()
return render(req, "users/register.html", {"form":form})
But when I visit the url
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("main.urls")),
path('register/', userViews.register, name="register"),
path('', include("django.contrib.auth.urls")),
]
I keep getting this error:
Internal Server Error: /register/
....
AttributeError: 'RegisterForm' object has no attribute 'cleaned_data'
Please I need some help.
Solution 1:[1]
Remove the form.save()
in case of a GET request: you can only save an object in case it is bounded and valid, so:
def register(request):
if request.method == 'POST':
form = RegisterForm(request.POST, request.FILES)
if form.is_valid():
form.save()
# only redirect when the POST is successful
return redirect('home') # ? use the name of a view
else:
form = RegisterForm() # no form.save()
return render(request, 'users/register.html', {'form': form})
Solution 2:[2]
First thing, pass
is no field in inbuilt User
model, there are two fields related to passwords which are password1
and password2
, unless and until you haven't changed it in original django code.
There no need for redirection, please remove form.save()
in else condition.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Willem Van Onsem |
Solution 2 | Sunderam Dubey |