簡體   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