当前位置: 动力学知识库 > 问答 > 编程问答 >

python - Django redirects to different view when form action is set to "."

问题描述:

I am lost here. I am quite new to django and maybe this is a newbie question.

I have a very simple list view , which shows the records in the database and a create view to add these objects :

@login_required

def list_view(request):

objects = Foo.objects.all()

ctx = {'objects': objects}

return render_to_response('main/foos.html', ctx,

context_instance=RequestContext(request))

@login_required

def create_view(request):

if request.method == 'POST':

form = FooForm(request.POST)

if form.is_valid():

form.save()

return redirect('/foos/')

else:

form = FooForm()

ctx = {'form': form}

return render_to_response('main/foo_form.html', ctx,

context_instance=RequestContext(request))

The foo_form.html template looks like this:

<!DOCTYPE html>

<html>

<head>

<title>Club</title>

</head>

<body>

<form action="." method="post">

{% csrf_token %}

{{ form.as_p }}

<input type="submit" value="Confirm/>

</form>

</body>

</html>

Url settings:

urlpatterns = patterns('',

url(r'^foos/$', 'list_view'),

url(r'^foos/new$', 'create_view'),

)

When I type the url "localhost:8000/foos/new", the create view gets the GET request as expected. The problem is, upon submitting the form, I am redirected to the list (using a debugger I found out the request is getting to the list_view), even when form action is set to "."

What am I doing wrong? The create_view view should receive the POST request .

Any help is appreciated! Again, I am sorry if this is a newbie question

网友答案:

You haven't finished the regex string in the second url

url(r'^foos/new$', 'create_view')

so "." will use the current url to POST the form. Django takes the url '/foos/new' and matches it against the regex. It matches the first regex, as it finds a match for 'foos', so goes to the 'list_view'. Just finish your regex correctly and it will work.

url(r'^foos/new/$', 'create_view')
网友答案:

Leave the form action as "" to post to the same url rather than having a .

So in this case

    <form action="" method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="Confirm/>
    </form>
分享给朋友:
您可能感兴趣的文章:
随机阅读: