所以我有这个表格扩展了用户,我只想让学生创建和帐户,并能够从课程列表中选择课程。但是当我尝试时,我得到错误:
__init__() takes 1 positional argument but 2 were given
我还没有找到任何解决方案。我需要一些建议。 这些是我的文件:
{% block body %}
<div class="row">
<div class="col-md-8 col-sm-10 col-12">
<h2>Sign up as a {{ user_type }}</h2>
<form method="post" novalidate>
{% csrf_token %}
<input type="hidden" name="next" value="{{ next }}">
{{ form }}
<button type="submit" class="btn btn-success">Sign up</button>
</form>
</div>
</div>
{% endblock %}
class User(AbstractUser):
is_student = models.BooleanField(default=False)
is_teacher = models.BooleanField(default=False)
path('signup/', views.StudentSignUpView, name='signup')
class StudentSignUpForm(UserCreationForm):
attended_courses = forms.ModelMultipleChoiceField(
queryset=Course.objects.all(),
widget=forms.CheckboxSelectMultiple,
required=True
)
class Meta(UserCreationForm.Meta):
model = User
@transaction.atomic
def save(self):
user = super().save(commit=False)
user.is_student = True
user.save()
student = Student.objects.create(user=user)
student.attended_courses.add(*self.cleaned_data.get('attended_courses'))
return user
class StudentSignUpView(CreateView):
model = User
form_class = StudentSignUpForm
template_name = 'signup_form.html'
def get_context_data(self, **kwargs):
kwargs['user_type'] = 'student'
return super().get_context_data(**kwargs)
def form_valid(self, form):
user = form.save()
login(self.request, user)
return redirect('index')
答案 0 :(得分:3)
需要在urls.py中通过as_view
方法引用基于类的视图。
path('signup/', views.StudentSignUpView.as_view(), name='signup')