На что ругается django?

413
11 июля 2017, 19:15

Подскажите, на что ругается django?

Ошибка:

ValueError at /account/register/
The view accounts.views.register didn't return an HttpResponse object. It returned None instead.
Request Method: POST
Request URL:    http://127.0.0.1:8000/account/register/
Django Version: 1.10.1
Exception Type: ValueError
Exception Value:    
The view accounts.views.register didn't return an HttpResponse object. It returned None instead.
Exception Location: /usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in _get_response, line 198
Python Executable:  /usr/bin/python
Python Version: 2.7.6
Python Path:    
['/home/gamzat/Django/tutorial',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-x86_64-linux-gnu',
 '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old',
 '/usr/lib/python2.7/lib-dynload',
 '/usr/local/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages/PILcompat',
 '/usr/lib/python2.7/dist-packages/gtk-2.0',
 '/usr/lib/python2.7/dist-packages/ubuntu-sso-client']
Server time:    Mon, 10 Jul 2017 02:32:27 +0000
forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class RegistrationForm(UserCreationForm):
    email = forms.EmailField(required=True)
    class Meta:
        model = User
        fields = (
            'username',
            'first_name',
            'last_name',
            'email',
            'password1',
            'password2'
        )
    def save(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.email = self.cleaned_data['email']
        if commit:
            user.save()
        return user
views.py
from django.shortcuts import render, redirect
from accounts.forms import RegistrationForm

# Create your views here.
def home(request):
    numbers = [1, 2, 3, 4, 5]
    name = 'Rasulov Gamzat'
    args = {'myName': name, 'numbers': numbers}
    return render(request, 'accounts/home.html', args)
def register(request):
    if request.method =='POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/account')
    else:
        form = RegistrationForm()
        args = {'form': form}
        return render(request, 'accounts/reg_form.html', args)
reg_form.html
{% extends 'base.html' %}
{% block body %}
<div class="container">
    <h1>Register</h1>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Submit</button>
    </form>
</div>
{% endblock %}
Answer 1

Когда форма невалидна, то возвращает None, вместо ответа, на что и ругается джанга.

Answer 2

Думаю, тут все просто. Ваш view ничего не вернул. Скорее всего, дело в том, что не проходит условие: if form.is_valid(). Т.е. вам необходимо вернуть Response с ошибками.

Answer 3

Попробуете вот так:

    if form.is_valid():
        form.save()
        return redirect('/account')
    else:
        return HttpResponse(u'Куда прёшь?', status_code=400)
READ ALSO
Очистка поля input при нажатии на checkbox

Очистка поля input при нажатии на checkbox

Есть поле изначально оно пустое, при добавления товара в него вписывается сумма, как сделать что бы при нажатии на кнопку сумма очищалась...

333
Регулярное выражение только 2 слова через пробел

Регулярное выражение только 2 слова через пробел

Нужно чтобы пользователь вводил имя и фамилию через пробелКак написать Регулярное выражение для HTML атрибута pattern?

204
Chekbox, чтобы включать и выключать input

Chekbox, чтобы включать и выключать input

Как сделать такое дополнение к input в виде checkbox, чтобы он выключал и включал input?

282