我试图使注册成为可能的主页,所以我没有一个单独的网址来处理注册。我试图通过get_context_data
发送表单,但它不工作。以下是我的代码:
- 表单. py**
class UserRegistrationForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = [
'username',
'password',
]
- 查看次数. py**
class BoxesView(ListView):
template_name = 'polls.html'
def get_context_data(self):
context = super(BoxesView, self).get_context_data()
# login
if self.request.method == 'POST':
form = UserRegistrationForm(self.request.POST or None)
context['form'] = form
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = User.objects.create_user(username=username, password=password)
user.save()
return redirect('/')
else:
print(form.errors) #doesn't print anything
print(form.non_field_errors()) #doesn't print anything
print('Errors') #doesn't print anything
else:
form = UserRegistrationForm()
context['form'] = form
return context
def get_queryset(self):
pass
- 基本. html**
<form action="" enctype="multipart/form-data" method="post">{% csrf_token %}
<div class="registerBox">
{{ form.username }}
{{ form.password }}
<input type="submit" value="register"/>
</div>
</form>
因此,当我提交表单时,它给出了以下错误:Method Not Allowed (POST): "POST / HTTP/1.1" 405 0
而且它没有创建一个新的用户。你知道问题出在哪里吗?
编辑:尝试FormMixin,出现此错误:The view app.views.BoxesView didn't return an HttpResponse object. It returned None instead.
class BoxesView(ListView):
template_name = 'polls.html'
form_class = UserRegistrationForm
def post(self, request, *args, **kwargs):
form = self.get_form()
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = User.objects.create_user(username=username, password=password)
user.save()
return redirect('/')
def get_context_data(self):
context = super(BoxesView, self).get_context_data()
context['form'] = self.get_form()
return context
def get_queryset(self):
pass
2条答案
按热度按时间8fsztsew1#
好的,我看到了问题,修复了缩进,你的if语句应该在get_context_data函数里面,而不是外面;)
n53p2ov02#
您需要将
post()
方法和FormMixin
添加到CBV中,如下所示: