首页 > 解决方案 > 在同一个 HTML 文件中使用文本字段的值

问题描述

我想在同一个 HTML 文件中使用 name='t0' 的输入文本的值。

这是代码 -

<!DOCTYPE html>
<head>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
    <title>Insert Account</title>
</head>

<body>
    <form action="{% url 'account_select' %}" method="GET">
        <div class="text-center">
            Id: <input type="text" name="t0"><br>
            <div class="one">
                <button type="submit" class="btn btn-outline-primary" name="b1" value="Select">Select</button>
            </div>
        </div>
    </form>
</body>

</html>

我想使用插入的值

<input type="text" name="t0">

代替“这里”

<form action="{% url 'account_select' "HERE" %}" method="GET">

值必须在同一个 HTML 文件中使用,因为它将被定向到链接。

标签: htmldjangoformsbootstrap-4

解决方案


由于您在这个问题中放置了 django,因此您必须创建一个模型,然后从该模型创建一个表单,然后将其放置在您的 html 文件中,并带有视图功能请求。

这是一个例子:

模型.py

from django.db import models

class AccountSelect(model.Model):
    name = models.CharField(max_lenght=50)

     def __str__(self):
        return self.name

迁移模型以创建表并添加表单(您需要在要创建表单的应用程序中创建此文件):

表格.py

from .models import AccountSelect
from django import forms

class AccountSelectForm(forms.ModelForm):
    """model to select accounts """
    class Meta:
        model = AccountSelect
        fields = ('name')

视图.py

def account(request):

    if request.method == "POST":
        # call the form that will be used
        account_select_form = AccountSelectForm(request.POST)

         if account_select_form.is_valid():
             account_select = account_select_form.save(commit=False)
             account_select.save()
 
    # if a GET (or any other method) we'll create a blank form
    else:
        account_select_form = AccountSelectForm()

    return render(request, 'account_select.html'{'account_select':account_select})

您的模板:

{% load static %}
<!DOCTYPE html>
<head>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
    <title>Insert Account</title>
</head>

<body>
    <form method="post">
            <div class="form-group">
              {{ account_select_form | as_bootstrap }}
              {% csrf_token %}
            </div>
            <button type="submit" class="btn btn-info">Submit</button>
          </form>
</body>

</html>

推荐阅读