Я пытаюсь сделать возможной регистрацию на главной странице, поэтому у меня нет отдельного URL-адреса для регистрации. Я пытаюсь отправить форму через get_context_data, но это не работает. Вот мой код:
forms.py
class UserRegistrationForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = [
'username',
'password',
]
views.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
base.html
{% csrf_token %}
{{ form.username }}
{{ form.password }}
Поэтому, когда я отправляю форму, она выдает эту ошибку: Метод не разрешен (POST): «POST / HTTP/1.1» 405 0
И он не создает нового пользователя. Есть идеи, в чем проблема?
EDIT: попробовал FormMixin, получил эту ошибку: представление app.views.BoxesView не вернуло объект HttpResponse. Вместо этого он вернул None.
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
Подробнее здесь: https://stackoverflow.com/questions/410 ... -1-1-405-0