Django:没有定义HttpResponseRedirect

时间:2017-12-07 09:08:29

标签: python django

我终于设法将数据从表单发布到django中的数据库,但是当我按下表单上的提交按钮时,我收到错误:

Request Method:     POST
Request URL:    http://127.0.0.1:8000/post_url/
Django Version:     1.11.2
Exception Type:     NameError
Exception Value:    

name 'HttpResponseRedirect' is not defined

Exception Location:     /home/xxxx/Desktop/123/src/exercises/views.py in post_treasure, line 26
Python Executable:  /home/xxxx/Desktop/123/bin/python

相关views.py:

def post_treasure(request):
    form = TreasureForm(request.POST)
    if form.is_valid():
        treasure = Treasure(name = form.cleaned_data['name'],
                            value = form.cleaned_data['value'],
                            material = form.cleaned_data['material'],
                            location = form.cleaned_data['location'],
                            img_url = form.cleaned_data['img_url'])
        treasure.save()
    return HttpResponseRedirect('/numbers/')

相关的urls.py:

urlpatterns = [
    url(r'^post_url/', post_treasure, name='post_treasure'),
    url(r'^admin/', admin.site.urls),
    url(r'^numbers/', numbers, name="numbers"),
    url(r'^about/', about, name="about")
]

其他说明:

  • 如果我按后退按钮查看从模型传递到模板的新更新数据,或者我使用管理界面查看数据
  • ,则数据成功发布

2 个答案:

答案 0 :(得分:8)

您需要导入HttpResponseRedirect

所以在顶部

from django.http import HttpResponseRedirect

答案 1 :(得分:1)

您需要先导入它:

from django.http import HttpResponseRedirect

def post_treasure(request):
    form = TreasureForm(request.POST)
    if form.is_valid():
        treasure = Treasure(name = form.cleaned_data['name'],
                        value = form.cleaned_data['value'],
                        material = form.cleaned_data['material'],
                        location = form.cleaned_data['location'],
                        img_url = form.cleaned_data['img_url'])
        treasure.save()
    return HttpResponseRedirect('/numbers/')