Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: HttpResponseRedirect is not defined

Tags:

python

django

I finally managed to POST data from a form to a database in django, however when I press the submit button on my form I get the error:

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

Relevant 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/')

Relevant 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")
]

Other note:

  • The data is successfully posted if I press the back button to view the new updated data passed from the model to the template, or if I use the admin interface to simply view the data
like image 371
DJANGOMANGO Avatar asked Dec 07 '17 09:12

DJANGOMANGO


2 Answers

you need to import HttpResponseRedirect

so at the top

from django.http import HttpResponseRedirect
like image 50
Exprator Avatar answered Nov 15 '22 08:11

Exprator


You need to import that first:

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/')
like image 1
Jahongir Rahmonov Avatar answered Nov 15 '22 10:11

Jahongir Rahmonov