django - what goes into the form action parameter when view requires a parameter?

前提是你 提交于 2019-12-18 11:02:31

问题


This is what I have:

myview.py with a view that takes a parameter user:

def myview(request, user):
   form = MyForm(request.POST)
   ....
   return render_to_response('template.html',locals(), context_instance=RequestContext(request))

The user gets passed through an url.

urls.py:

...

urlpatterns += patterns('myview.views',
    (r'^(?P<user>\w+)/', 'myview'),
)

...

I also have a template.html with a form:

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

What goes in the the form action parameter if myview function requires a parameter?

Right now I have action="." . The reason I'm asking is because when I fill up the form In (templates.html) and click the submit button I see absolutely no field values passed from that form. It's almost like I'm passing an empty form when I click the submit button. Any ideas? Thank you!


回答1:


You are posting to the same view that also serves the form. So at first, the view is called and serves the form. When you post the form, the same view gets called but this time you process the form. That's why the action is empty.




回答2:


If you want to explicitly set the action, assuming you have a variable username in your template,

<form name="form" method="post" action="{% url myview.views username %}">

or you could assign a name for the url in your urls.py so you could reference it like this:

# urls.py
urlpatterns += patterns('myview.views',
    url(r'^(?P<user>\w+)/', 'myview', name='myurl'), # I can't think of a better name
)

# template.html
<form name="form" method="post" action="{% url myurl username %}">



回答3:


It should not require anything. Assuming you are at the following url:

www.yoursite.com/users/johnsmith/

Your form should be:

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

At this point, you are already in myview with user johnsmith. Your view should look like the following:

if request.method == 'POST':
    form = MyForm(request.POST)
    if form.is_valid():
        # you should be able to extract inputs from the form here
else:
    form = MyForm()



回答4:


You can use request.path and that will work in most cases.



来源:https://stackoverflow.com/questions/5467192/django-what-goes-into-the-form-action-parameter-when-view-requires-a-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!