我怎样才能自动将这些名字和姓氏存储在数据库中?

时间:2017-06-14 17:17:39

标签: python django

我目前正在教自己Django,我想知道如何在数据库的相应列中存储名字和姓氏。我熟悉SQL命令。我知道如何使用SQL命令使用models.py文件中的代码将它们手动存储在数据库中,但这一次,我想要在用户点击时将这些名字和姓氏存储在数据库中{ {1}}填写完文本字段后,下次当我手动查找数据库中的内容时,我会看到用户提交的内容。

我将如何开始这个?

这是我的Submit文件:

urls.py

这是我的from django.conf.urls import url from . import views urlpatterns = [ # /music/ url(r'^$', views.index, name='index'), # /music/71 url(r'^(?P<user_id>[0-9]+)/$', views.detail), ] 文件:

views.py

这是我的from django.http import HttpResponse from django.template import loader def index(request): template = loader.get_template('music/index.html') return HttpResponse(template.render()) 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"> <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> 文件:

models.py

1 个答案:

答案 0 :(得分:0)

您可以像这样编写视图,

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 = User.objects.create(first_name=first_name, last_name=last_name)
        else:
            return Httpresponse('Not Done!')
    return render(request, 'music/index.html')