2017-06-15 53 views
0

我的程序的目標是在輸入時將姓氏和名字放入我的數據庫中,並且用戶點擊按鈕,這樣當我手動檢查Terminal我的數據庫中有什麼時,我可以看到用戶輸入了什麼並提交。我需要一些如何連接我的Submit按鈕到我的views.py文件,以便它可以通過,排序像onClick()但這一次,去一個.py文件。 (糾正我,如果我錯了這個思路)。如何將提交按鈕連接到我的.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

您的形式應該被聲明爲:

​​

和你<button type="submit">應該是裏面的<form></form>

由於相同的視圖處理GET和POST方法,您應該刪除action="#"屬性,這種方式操作將指向相同的視圖。

+0

完美,適合我。謝謝 – bojack

相關問題