简体   繁体   English

Django:返回带有POST参数的模板

[英]Django: Returning a template with POST parameters

I have a table with multiple rows, each of which has an 'edit' button. 我有一个包含多行的表,每行都有一个“编辑”按钮。 On clicking this button, the user should redirect to a form with his details already prefilled. 单击此按钮时,用户应重定向到已预先填写其详细信息的表单。 Now, I have defined data attributes inside the 'edit' button's definition: 现在,我已经在“编辑”按钮的定义内定义了数据属性:

<a href='#' class="edit-user" data-email="abc@gmail.com">edit</a>

Using JQuery, I'm deriving the value of the 'email' data attribute and passing it in a POST request to /add-edit-user , which is also mapped to the page which has my form: 使用JQuery,我派生了'email'数据属性的值,并将其在POST请求中传递给/add-edit-user ,它也映射到具有我的形式的页面:

$( ".edit-user" ).click(function() 
    {   
        var url = base_url + '/add-edit-user/';
        var data = {
            'email': $(this).data('email'),
            'csrfmiddlewaretoken': csrftoken,
        };
        // $.post(url, data);
        $.post(url, data).done(function(result) {
            console.log(result);
        }).fail(function(error) {
            console.log(error);
        });
    });

The /add-edit-user URL maps to the following view where I'm trying to define my form object and pass on as a context variable to my template file: /add-edit-user URL映射到以下视图,在该视图中我试图定义表单对象并将其作为上下文变量传递到模板文件:

def add_edit_users(request):
    form = AddUpdateForm(request.POST or None)
    data = {'form': form}

    return render(request, 'add_edit_users.html', data)

Now, my assumption was that if the user clicks on the 'edit' button, I'd set the 'email' parameter in a data attribute and pass it on in my POST request to /add-edit-user URL, after which I'll render my form template with the form object as a context variable which will display the form with email field already prefilled. 现在,我的假设是,如果用户单击“编辑”按钮,我将在数据属性中设置“电子邮件”参数,并将其在我的POST请求中传递给/add-edit-user URL,之后我将使用表单对象作为上下文变量来呈现我的表单模板,该模板将显示带有已预先填写的email字段的表单。

However, on clicking of the edit link, the page is not redirected to the form page, but I do get the entire form page's HTML in my response. 但是,单击edit链接后,页面不会重定向到表单页面,但是我的确获得了整个表单页面的HTML。 How can I redirect the flow to my form's template so that my input fields are prefilled from the POST variables? 如何将流程重定向到表单模板,以便从POST变量中预填充我的输入字段?

What you want to achieve can be done by creating a form like this: 您想要实现的目标可以通过创建如下形式来完成:

<form method='post' action='/add-edit-user/'>
   {% csrf_token %}
   <input type="email" name="email" value="abc@gmail.com" hidden> 
   <button class="edit-user" type="submit">Edit</button>
</form>

This form sends value of the email field in post data to the url : /add-edit-user/ . 此表单将帖子数据中电子邮件字段的值发送到url: / add-edit-user / Resulting in redirecting to the url with the email field prefilled. 结果是重定向到带有电子邮件字段的URL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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