Django我的表单没有保存在django db中?

时间:2018-08-19 18:37:13

标签: python django django-forms

我是新手,并且在阅读了django的文档后。我做了表格,但是我的表格没有保存到我的数据库中,也没有显示在我的数据库中。请帮我,我尝试了很多办法,但是仍然不能省。我为此有驱动程序,我想注册他们。但它没有保存到我的数据库。而且我认为它没有将数据发布到我的数据库中。 请帮助我。

Views.py

def driver_form(request):
    args = {}
    template = Template.objects.get(template_default__exact=1)
    template_page = template.template_alias + str("/rentacar/rentacar_driver_form.html")#sir this ?
    return render(request, template_page, args)




def driver_save(request):
    args = {}
    if request.POST:

        driver_firstname = request.POST.get('driver_firstname')
        driver_lastname = request.POST.get('driver_lastname')

        driver_save_form = DriverForm(request.POST)
        if driver_save_form.is_valid():
            new_driver = driver_save_form.save(commit=False)
            new_driver.driver_firstname = driver_firstname
            new_driver.driver_lastname = driver_lastname
            new_driver.save()
            template = Template.objects.get(template_default__exact=1)
            template_page = template.template_alias + str("/rentacar/rentacar_driver_form.html")
            return render(request, template_page, args)
        else:
            return HttpResponseRedirect('/')
    else:
        return HttpResponseRedirect('/')

rentacar_driver_form

<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<title></title>

</head>
<body>
<div class="container">
<form method="POST" action="/rentacar/driver-save/">
{% csrf_token %}
<label>
  First Name<br>
  <input type="text" name="driver_firstname" required>
</label>
<br>
<label>
  Last Name<br>
  <input type="text" name="driver_lastname" required>
</label>
<br>

<input type="submit" class='btn btn-primary' value="Submit">
</form>
</div>
</body>

</html>

Forms.py

from __future__ import unicode_literals
from django import forms
from rentacar.models import *

class DriverForm(forms.ModelForm):
    class Meta:
        model = BookingApproval
        exclude = (
            'driver_firstname',
            'driver_lastname',
        )

2 个答案:

答案 0 :(得分:-1)

只是改变

if request.POST:
    ...

在driver_save视图内

if request.method == "POST":
    ...

答案 1 :(得分:-1)

尝试更改:

driver_firstname = request.POST.get('driver_firstname')
driver_lastname = request.POST.get('driver_lastname')

至:

driver_firstname = request.POST['driver_firstname']
driver_lastname = request.POST['driver_lastname']