繁体   English   中英

使用表单输入重定向到 Django 中的 url 的正确方法

[英]Proper way of using form input to redirect to a url in Django

我设法从 HTML 表单获取值到 URL 模式,但这不是解决问题的优雅方式。 所以我在问什么是更好的方法,因为我再次面临同样的问题。

这是我所拥有的简化版本:

我的HTML 表单

<form method='post' action={% url 'pressed_button' %}>
  <button name="choice" value="Correct-Button"> Click Me </button>
  <button name="choice" value="Wrong-Button"> Dont Click Me </button>
</form>

这是我的urls.py

url(r'^PressedButton/$', views.PressedButtonView.as_view(), name='pressed_button'),
url(r'^PressedButton/(?P<choice>\w+)$', views.PressedButtonView.as_view(), name='pressed_button_with_user_choice'),

和视图类PressedButtonView

class PressedButtonView(View):
    def get(self, request, choice):
        return render(request, 'weirdapp/buttonclicked.html', {'button': choice})

    def post(self, request):
        choice = request.POST['choice']

        return redirect(reverse('pressed_button_with_user_choice', kwargs={'choice': choice}))

现在,我想如果我可以在表单的“action”属性中发送按下按钮的值

<form method='post' action={% url 'pressed_button_with_user_choice' 'pressedButtonValue' %}>

这将是更好的代码。

另外,如果我能得到我次要但相关的问题的答案, return redirect(reverse())中的 reverse 方法有什么作用? 为什么不直接重定向到 URL 模式名称?

谢谢。

为什么不为每个按钮制作具有适当action单独表单?

我可以建议另一种方法吗? 也许在表格post后验证正确/不正确的选择会更好? form_valid您可以根据正确/不正确的选择重定向到另一个页面吗?

换句话说,如果你在 HTML 中添加类似class=Correct-choice提示,你可能会遇到一些作弊者:P

过了一会儿我回来回答我自己的问题,因为我想到了一个很好的解决方案。

使用Javascript,我们可以使用从按下的按钮中获取的值将表单数据的POST请求发送到我们想要的url。 就是这样:

HTML:

<form id="my-form">
 Age: <input name="age" value="31"/>
</form>

<button class="form-submitter" data-choice="Correct-Button"> Click Me </button>
<button class="form-submitter" data-choice="Wrong-Button"> Dont Click Me </button>

Javascript:

(function(){
  $('.form-submitter').on('click', function(e){
    let formData = new FormData(document.getElementById('my-form'));
    let buttonChoice = $(this).data('choice');

    $.ajax({
      url: '/PressedButton/ + buttonChoice',
      data: formData,
      method: 'POST',
      processData: false,
      contentType: false,
      success: function(response){
        console.log("successful communication", response);
      },
    });

  });  
})();

网址.py:

url(r'^PressedButton/(?P<choice>\w+)$', views.PressedButtonView.as_view(), name='pressed_button'),

在视图类PressedButtonView 中:

class PressedButtonView(View):
    def post(self, request, choice):
        #age = request.POST['age']
        return render(request, 'weirdapp/buttonclicked.html', {'button': choice})

这是javascript工作的更多文档JSFiddle。 JSFiddle

暂无
暂无

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

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