【问题标题】:View won't pick up post查看不会捡起帖子
【发布时间】:2011-03-09 15:16:23
【问题描述】:

谁能告诉我为什么下面的视图不会收到一个 POST 请求:

# Loads all the latest phone numbers for the models.py file
def client_phones_form_view(request, clientKEY):
    try:
        i_clientKEY = int(clientKEY)
    except ValueError:
        raise Http404()
    phones = []
    # Populates a list with the latest phone numbers for ALL types of phone
    for k, v in PHONE_CHOICES:
        try:
            phones.append(ClientPhone.objects.filter(client=i_clientKEY, phone_type=k).latest('id'))
        except ClientPhone.DoesNotExist:
            pass
    if request.method == 'POST':
        formPhone = ClientPhoneForm(request.POST)
        if formPhone.is_valid() and formPhone.number.clean(formPhone.number):
            c = Client.objects.get(id=i_clientKEY)
            formPhone.CustomSave(c, request.user)
            return render_to_response(...)
        else:
            return render_to_response(...)
    else:
        formPhone = ClientPhoneForm()
        return render_to_response(...)

我知道当我提交表单时它正在重新加载,但它总是重新加载底部render_to_response

编辑:

javascript 看起来像这样:

$( "#newPhoneDialog" ).dialog({
    autoOpen: false,
    height: 200,
    width: 350,
    modal: true,
    buttons: {
        "Add New Phone Number": function() {
            var bValid = true;
            //alert($('#id_number').val()+" - "+$('#id_phone_type').val());

            bValid = bValid && checkNumberLength( phoneNumber, "the phone number", 11, 15 );

            bValid = bValid && checkNumberRegexp( phoneNumber, /^([0-9])|( \t)+$/, "The phone number may only consist of numbers and spaces");

            if ( bValid ) {
                $('.error').hide(); // hide the error div
                $('.success').hide(); // hide the success div
                $('.info').hide(); // hide the information div
                $.ajax({ // create an AJAX call...
                    data: $('#newPhoneForm').serialize(), // get the form data
                    type: 'POST', // GET or POST
                    url: 'client/form/phones/1/', // the file to call
                    success: function(response) { // on success..
                        $('#clientPhonesForm').html(response); // update the main phones DIV
                    }
                });
                $( this ).dialog( "close" );
                //return false; // cancel original event to prevent form submitting
            }
        },
        Cancel: function() {
            // reloads the phone div because re-selecting the first item in the options doesn't work
            $('#clientPhonesForm').load('{% url client.views.client_phones_form_view clientKEY %}');
            $( this ).dialog( "close" );
        }
    },
    close: function() {
        // reloads the phone div because re-selecting the first item in the options doesn't work
        //$('#clientPhonesForm').load('{% url client.views.client_phones_form_view clientKEY %}');
    }
});

而 HTML 是这样的:

<div id="newPhoneDialog" title="Create New Phone Number">
        Please enter a valid phone number:
    <div id="container">
        <form action="{% url client.views.client_phones_form_view clientKEY %}" method="POST" id="newPhoneForm">
            <table>
            {% for field in formPhone %}
            <tr><td>{{ field.label_tag }}</td><td>{{ field }}</td></tr>
            {% endfor %}
            </table>
        </form>
    </div>
</div>

编辑

也许这个问题会更好,如果它说 'How do I (jquery ajax) submit a form when a button is clicked'

【问题讨论】:

  • 你能告诉我开发服务器中有多少请求通过或记录尝试吗?当您单击按钮时,会发生什么?开发服务器是否注册了 POST,然后使用 GET 重新加载页面?它是否注册了 GET 并且页面不会重新加载?
  • 开发服务器仅在 POST 请求中显示
  • 当我注释掉 formPhone.number.clean(formPhone.number) 时,一切似乎都正常。 formPhone.number 使用来自 djangosnippets.org/snippets/1207UKPhoneNumberField()
  • 这意味着视图正在到达那条干净的线,这意味着它正在检测request.method == 'POST'!这意味着您的问题严格来说是if 条件:if valid and formPhone.number.clean()。您的问题听起来好像只有最底层的 render 函数被调用,而 django 忽略了 if request.method 行。为什么你甚至需要那条线?如果 UKPhoneNumberField() 被定义为表单的一部分,如果字段验证失败,form.is_valid() 将返回 False
  • 开发服务器也开始处理Http 500,这就是我尝试清理号码的原因

标签: django jquery django-views html-post


【解决方案1】:

这是一个防弹条件:if request.method == 'POST',所以我将开始研究为什么您不生成 POST 请求,而不是视图。

你能确定你是从你的表格发帖吗?

&lt;form method="post"&gt;

开发服务器是否注册了 POST 请求?应该说"GET /...""POST /..."


更新:好的,这是一个 ajax 请求表单。最近 SO 上有另一个人遇到了类似的问题,因为 AJAX 请求将原始表单作为 GET 请求触发。

我看到你注释掉了return false——这可能是问题所在吗?其实没关系,我认为对话框按钮不会干扰。

那么更重要的是:什么是开发服务器记录?一个POST然后一个GET?一个GET?

【讨论】:

  • 我尝试了以下pastebin.com/few79mwX,它仍然使用最后一个render_to_response :(
  • 通过输出request.method我发现这是一个POST方法
【解决方案2】:

以下似乎是答案。对不对我不知道:

# Loads all the latest phone numbers for the models.py file
def client_phones_form_view(request, clientKEY):
    try:
        i_clientKEY = int(clientKEY)
    except ValueError:
        raise Http404()
    phones = []
    # Populates a list with the latest phone numbers for ALL types of phone
    for k, v in PHONE_CHOICES:
        try:
            phones.append(ClientPhone.objects.filter(...).latest('id'))
        except ClientPhone.DoesNotExist:
            pass
    if request.method == 'POST':
        formPhone = ClientPhoneForm(request.POST)
        if formPhone.is_valid():
            try:
                n = formPhone.cleaned_data['number']
            except ValidationError:
                return render_to_response(...)
            c = Client.objects.get(id=i_clientKEY)
            formPhone.CustomNumberSave(c, n, request.user)
            return render_to_response(...)
        else:
            return render_to_response(...)

    else:
        formPhone = ClientPhoneForm()
        return render_to_response(...)

【讨论】:

    猜你喜欢
    • 2020-06-16
    • 2019-02-22
    • 2013-09-03
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多