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

后端 未结 4 1195
后悔当初
后悔当初 2020-12-13 18:30

This is what I have:

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

def myview(request, user):
   form = MyForm(reques         


        
相关标签:
4条回答
  • 2020-12-13 19:00

    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.

    0 讨论(0)
  • 2020-12-13 19:02

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

    0 讨论(0)
  • 2020-12-13 19:10

    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 %}">
    
    0 讨论(0)
  • 2020-12-13 19:19

    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()
    
    0 讨论(0)
提交回复
热议问题