【问题标题】:How to get value from HTML user input in django view?如何从 django 视图中的 HTML 用户输入中获取价值?
【发布时间】:2021-09-29 11:49:21
【问题描述】:

大家好,我有一个 HTML 表单,如下所示: 单击帖子后,我将其重定向到views.py。谁能告诉我如何将表单所有字段的字段值获取到views.py中。 这是输出 我想要键值对中的字段值,如上图所示,即 API=hello&Area=hello1 等等...

我知道我们可以使用它来做到这一点 如果是 html:

<div class="form-group col-md-2">
                    <label for="param">TAF Parameter</label>
                    <input type="text" name="inputdata_API" class="form-control" id="inputapi_param" value="API" readonly>
                </div>

并查看:

def register(request):
    api = request.GET.get['inputdata_API']

但在这种情况下,我必须在我的视图中写下每个输入名称

【问题讨论】:

    标签: javascript html django


    【解决方案1】:

    为了在不单独访问的情况下获取表单输入,Django 提供了ModelForm

    简历:

    1. 定义一个模型来存储你的表单信息

      类 MyModel(models.Model): api = 模型.CharField() # ...

    2. 定义一个链接到之前模型的model form

       from django import forms
      
       class MyModelForm(forms.Form):
           class Meta:
               model = MyModel
               fields = ['api', # all others fields you want to display]
      
    3. views.py

       from django.http import JsonResponse
       from django.shortcuts import redirect
      
       def register(request):
           if request.method == 'POST':
                # Instanciate the form with posted data
                form = MyModelFor(request.POST)
                # Check if form is valid
                if form.is_valid:
                    # Create a new MyModel object if the form is valid
                    form.save()  # This is the most benefit line, save you from request.POST['field_name'] 
                    # You can eventually return to the same page
                    return redirect('.') 
                else:  # The form is invalid return a json response
                    return JsonResponse({"Error": "Form is invalid"}, status=400)
      
    4. 最后在模板中渲染表单字段,如下所示:

        <form action="{% url 'url_to_register' %}" method="post" novalidate>
           {% csrf_token %}
           {{ form.as_p }}
      
           <button type="submit" class="btn btn-success">Register</button>
        </form>
      

    但这种方法的缺点是前端表单的样式: 例如,您需要在正确的位置添加一些 Bootstrap 类以使其看起来不错,它是对应的...

    Django 表单documentation.

    【讨论】:

    • 嘿,我的 html 用户输入不需要任何模型
    • 我只想要视图中的 html 用户输入值
    • 然后使用request.POST.get('field_name') !我只是向你展示如何在 Django 中轻松处理大表单。
    猜你喜欢
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多