如何将“提交”按钮连接到我的.py文件?

时间:2017-06-15 17:39:07

标签: python django

我的程序的目标是在输入数据时将名字和姓氏放入我的数据库,并由用户点击Submit按钮,这样当我手动检入Terminal数据库中的内容时,我可以看到用户输入和提交的内容。我需要了解如何将我的Submit按钮连接到我的views.py文件以便它可以通过,排序类似于onClick(),但这次要转到.py文件。 (如果我对这段思路错了,请纠正我。)

我将如何实现这一目标?

这是我的views.py文件:

from django.http import HttpResponse
from django.shortcuts import render
from .models import Person

def index(request):
    if request.method == 'POST':
        first_name = request.POST.get('firstName')
        last_name = request.POST.get('lastName')
        if first_name and last_name:
            user = Person.objects.create(firstName=first_name, lastName=last_name)
            user.save()
    return render(request, 'music/index.html')

def detail(request, user_id): # Testing out page 2
    return HttpResponse("<h2>Page # (testing this out) " + str(user_id) + "</h2>")

这是我的index.html文件:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>The Page</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <link rel="stylesheet" href="index.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body>
    <div class="container">
        <form action="#">
            <div class="form-group">
                <label for="firstName">First Name:</label>
                <input type="email" class="form-control" id="firstName" placeholder="Enter first name" name="firstName">
            </div>
            <div class="form-group">
                <label for="">Last Name:</label>
                <input type="email" class="form-control" id="lastName" placeholder="Enter last name" name="lastName">
            </div>
        </form>
            <div class="checkbox">
                <label><input type="checkbox" name="remember">Remember me</label></div></br>
                <button type="submit" class="btn btn-default">Submit</button>
            </div>
    </div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

您的表单应声明为:

<form method="POST">

,您的<button type="submit">应位于<form></form>

由于同一视图处理GET和POST方法,您应该删除action="#"属性,这样操作将指向同一视图。