【问题标题】:How to pass data from html to django view to use in URL?如何将数据从 html 传递到 django 视图以在 URL 中使用?
【发布时间】:2020-03-17 00:54:21
【问题描述】:

我在使用 django url 时遇到错误。我想在点击提交按钮后传递名称输入字段的值。

假设我有这个 html 表单-

<form method='POST' action="{% url 'submittedform' slug=[firstname] %}">
                        {% csrf_token %}
                        <div>
                            <label for="name">Name</label>
                            <input type="text" name="firstname" id="name">
                        </div>

                        <div>
                            <label for="email">Email</label>
                            <input type="email" name="useremail" id="email">
                        </div>

                        <div>
                            <label for=phone>Phone</label>
                            <input type="text" name="phonenumber" id="phone" maxlength="12" pattern="[0-9]{10}">
                        </div>

                        <input type="submit" name="" id="btn" value="Submit">
                    </form>

这是我的处理方式-

def submittedform(request, slug):

    if request.method == 'POST':
        # do something here
        return render(request,'myapp/welcome.html')

    return render(request,'myapp/welcome.html')

这是我处理它的观点-

urlpatterns = [
    path('index/',views.index ,name='index'),
    path('welcome/<slug:slug>/',views.submittedform, name='submittedform')
]

我没有使用 django 表单。我怎样才能获得欢迎/名称工作。

【问题讨论】:

    标签: html django view


    【解决方案1】:

    如果要将变量传递给 URL,则需要使用值重定向:

    from django.shortcuts import redirect
    
    return redirect("/welcome/%s/" % slug)
    

    【讨论】:

      【解决方案2】:

      更改以下行

      <!-- Removed the bracket -->
      <form method='POST' action="{% url 'submittedform' slug=firstname %}">
          <!-- Children tags here -->
      </form>
      

      现在可以在视图中访问变量

      def submittedform(request, slug):
      
          if request.method == 'POST':
              name = request.POST['name']
              # and more variables as you need
              # do something here
      
              # do redirect here or give some message that their form has been
              # submitted for their confirmation 
              return render(request,'myapp/welcome.html')
      
          return render(request,'myapp/welcome.html')
      

      【讨论】:

      • 它没有用。我在 /geeks/index/ 收到错误 NoReverseMatch。未找到关键字参数“{'slug':''}' 的'submittedform' 的反向。尝试了 1 种模式:['geeks/welcome/(?P[-a-zA-Z0-9_]+)$']
      • 我在访问变量时没有问题。我对如何将这些输入字段中的任何一个值传递给 'welcom/xyx/' url 感到困惑。
      猜你喜欢
      • 1970-01-01
      • 2021-03-26
      • 1970-01-01
      • 2020-06-15
      • 1970-01-01
      • 2021-11-18
      • 2013-06-24
      • 2020-03-19
      • 2019-02-16
      相关资源
      最近更新 更多