Форум сайта python.su
2
FishHookSorrowFuckМне дико интересно, а что вернет вьюха, если форма не свалидируется?from django import forms from django.contrib.auth.forms import UserCreationForm from django.http import HttpResponseRedirect from django.shortcuts import render_to_response def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): new_user = form.save() return HttpResponseRedirect("/reg/") else: form = UserCreationForm() return render_to_response("registration.html", { 'form': form, })
Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: CSRF token missing or incorrect.
Офлайн
568
SorrowFuckМожет быть я плохо вкурил Ваш код, но попробую размышлять логически и последовательно
Возвращается следующее:
Офлайн
2
FishHookSorrowFuckМожет быть я плохо вкурил Ваш код, но попробую размышлять логически и последовательно
Возвращается следующее:
1. def register(request):
Тут все понятно, вызвана функция в нее переданы параметры
2. if request.method == ‘POST’:
Ага, тут тоже понятно, проверяем что произошло, либо юзер просто загрузил страничку по адресу (GET) либо нажал сабмит формы (POST)
3. if form.is_valid():
Великолепно, проверяем валидность данных и в случае, если форма свалидировалась записываем данные в базу и возвращаем клиенту новый адрес.
4. Пришли не корректные данные
Поток выполнения Вашей программы дошел до места if request.method == ‘POST’, условие выполнилось, проверяем form.is_valid() - условие не выполнилось, дальше этого условия в ифе “верхнего уровня” у Вас ничего нет, значит мы выходим из if request.method == ‘POST’, видим else, которая не отработает, потому что отработал иф, а дальше пустота, что вернет функция? Правильно None. А должна вернуть Response.
from django import forms from django.contrib.auth.forms import UserCreationForm from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): new_user = form.save() return HttpResponseRedirect("/reg/") else: return HttpResponseRedirect("/") else: form = UserCreationForm() return render_to_response("registration.html", { 'form': form,
Офлайн
568
Вместо
else: return HttpResponseRedirect("/")
else: return render_to_response("registration.html", { 'form': form})
Отредактировано FishHook (Окт. 11, 2012 07:15:01)
Офлайн
2
FishHook
ВместоСделайelse: return HttpResponseRedirect("/")else: return render_to_response("registration.html", { 'form': form})
Увидишь с какими ошибками у тебя не валидируется форма
from django import forms from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render_to_response from django.template import RequestContext def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): new_user = form.save() return render_to_response("done.html") else: return render_to_response("registration.html", { 'form': form}, context_instance=RequestContext(request)) else: form = UserCreationForm() return render_to_response("registration.html", { 'form': form, }, context_instance=RequestContext(request))
Отредактировано SorrowFuck (Окт. 11, 2012 07:53:55)
Офлайн
568
SorrowFuckну и слава богу
Все работает.
Офлайн
16
Из djangobook:
After the e-mail is sent, we redirect to aНе критично конечно, но после успешного POST запроса желательно редиректить пользователя, а не просто вызывать render_to_response()
“success” page by returning an
HttpResponseRedirect object. We’ll leave
the implementation of that “success” page
up to you (it’s a simple view/URLconf/
template), but we should explain why we
initiate a redirect instead of, for example,
simply calling render_to_response()
with a template right there.
The reason: if a user hits “Refresh” on a
page that was loaded via POST , that
request will be repeated. This can often
lead to undesired behavior, such as a
duplicate record being added to the
database – or, in our example, the e-mail
being sent twice. If the user is redirected to
another page after the POST, then there’s
no chance of repeating the request.
You should always issue a redirect for
successful POST requests. It’s a Web
development best practice.
Офлайн
2
GaiveR
Из djangobook:After the e-mail is sent, we redirect to aНе критично конечно, но после успешного POST запроса желательно редиректить пользователя, а не просто вызывать render_to_response()
“success” page by returning an
HttpResponseRedirect object. We’ll leave
the implementation of that “success” page
up to you (it’s a simple view/URLconf/
template), but we should explain why we
initiate a redirect instead of, for example,
simply calling render_to_response()
with a template right there.
The reason: if a user hits “Refresh” on a
page that was loaded via POST , that
request will be repeated. This can often
lead to undesired behavior, such as a
duplicate record being added to the
database – or, in our example, the e-mail
being sent twice. If the user is redirected to
another page after the POST, then there’s
no chance of repeating the request.
You should always issue a redirect for
successful POST requests. It’s a Web
development best practice.
Офлайн