Как исправить «SignUpView не хватает набора запросов».
В моем веб-приложении django я пытаюсь создать приложение Newspaper, на главной странице, когда я нажимаю на SIGN UP
кнопку, я получаю ошибку «ImproperlyConfigured at /accounts/signup/»,
Я не смог понять, в чем проблема.
forms.py:
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm): #Creation of CustomUser
class Meta:
model = CustomUser
fields = UserCreationForm.Meta.fields + ("age",)
class CustomUserChangeForm(UserChangeForm): #Modifying existing users
class Meta:
model = CustomUser
fields = UserChangeForm.Meta.fields
и models.py:
from django.contrib.auth.models import AbstractUser #username, pw1, pw2
from django.db import models
class CustomUser(AbstractUser):
age = models.PositiveIntegerField(null=True, blank=True)
urls.py:
from django.urls import path
from .views import SignUpView
#Accounts/urls.py : Handles only registrations URLs!!
urlpatterns = [
path('signup/', SignUpView.as_view(), name='signup'),
]
и views.py:
from django.urls import reverse_lazy
from django.views.generic import CreateView
from .forms import CustomUserCreationForm
class SignUpView(CreateView):
from_class = CustomUserCreationForm
success_url = reverse_lazy('login')
template_name = 'registration/signup.html'
signup.html:
{% extends 'base.html' %}
{% block title %}Sign Up{% endblock title %}
{% block content %}
<h2>Sign Up</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Sign Up</button>
</form>
{% endblock content %}
Я пытался изменить поля в forms.py
с помощью:
fields = (
"username",
"email",
"age",)
но упоминать не о чем
The culprit is a typo: to from_class
form_class
:
from django.urls import reverse_lazy
from django.views.generic import CreateView
from .forms import CustomUserCreationForm
class SignUpView(CreateView):
form_class = CustomUserCreationForm
success_url = reverse_lazy('login')
template_name = 'registration/signup.html'
But I think it is interesting to know why this then raises this error: if you don't provide a .form_class
[Django-doc] to a CreateView
, a CreateView
will try to make its own form, for that it can work with the modelform_factory(…)
[Django-doc], but for that it needs to know the model.
It tries to determine the model in three possible ways: first by looking if the view has a .model
attribute, if not if it has an .object
attribute (for an UpdateView
the form can be implied by the object to update), and finally it runs the .get_queryset()
method [Django-doc] to obtain the model of the QuerySet
, and since none of these work with this SignUpView
, we thus get that error.