简体   繁体   中英

Submit form is empty — Django

This is my template:

<form action="{% url "calculate" %}>    

    <label2>
        <select name="ASSETS_filn">
        <option selected>Files</option>

        {% for document in documents %}
        <option>{{ document.filename }}</option>
        {% endfor %}
        </select>
    </label2>
    <br>
    <label>Date</label>
    <input class="button3" type="text" name="DATE_val" />
    <input class="button3" type="submit" value="Calculate" />
</form>

label2 is a dropdown menu. My objective with this is: Enable the user to select an item from the dropdown menu and enter data into the Date box. This is the view that handles this:

def calculate(request):
    os.chdir(settings.PROJECT_PATH + '/calc/')
    f = open('calc_log.txt', 'w')   # Could change to 'a' for user activity log
    f.write("hehehehe")
    for key in request.POST:
        f.write(str(key) + " " + str(request.POST[key]) + '\n')
    f.write('\n\n')
    f.write("test")
    f.close()
    return render( #...

But all that is written to the .txt file is hehe and test . Is request.POST empty?

By default, the method of form submit is GET , and you intend to do a POST .

So, specify the method:

<form action="{% url 'calculate' %}" method="POST">

Also, it is a good idea to check for the method:

def calculate(request):
    if request.method == "POST":
        os.chdir(settings.PROJECT_PATH + '/calc/')

        f = open('calc_log.txt', 'w')   # Could change to 'a' for user activity log

        f.write("hehehehe")

        for key in request.POST:
            f.write(str(key) + " " + str(request.POST[key]) + '\n')

        f.write('\n\n')
        f.write("test")

        f.close()

    #...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM