Django表单未使用自定义表单将数据保存到数据库

时间:2020-09-10 06:37:31

标签: django

我试图为用户创建一个停车场表格,该表格将输入他们的RFID卡,他们的日志历史记录,车牌,名称和有效与否,但是我无法获得Django表格将其保存到数据库

这是我的models.py

from django.db import models

class data(models.Model):
    RFID = models.CharField(max_length=10)
    Name = models.CharField(max_length=10)
    Log = models.TextField()
    License_Plate = models.CharField(max_length=10)
    Active = models.BooleanField(default=True) 

我的forms.py

from django import forms

from .models import data  # import data from models.py


class data_form(forms.ModelForm):
    class Meta:
        model = data
        fields = ['RFID',
                  'Name', 'Log', 'License_Plate', 'Active']

class data_custom_form(forms.Form):
    RFID = forms.CharField(
        widget=forms.TextInput(attrs={'id': 'user-rfid'}),
    )
    Name = forms.CharField(widget=forms.TextInput(
        attrs={'id': 'user-name',
               'cols': 40,
               'rows': 1
               }))
    Log = forms.CharField(
       widget=forms.TextInput(attrs={'id': 'user-log'})
    License_Plate = forms.DecimalField()
    Active = forms.BooleanField()

我的views.py

from django.shortcuts import render

# Create your views here.
from .models import data
from .forms import data_custom_form


def custom_form_view(request):
    custom_form = data_custom_form()
    if request.method == 'POST':
        custom_form = data_custom_form(request.POST)
        if custom_form.is_valid():
            print(custom_form.cleaned_data)
        else:
            print(custom_form.errors)
    info = {
        'form': custom_form
    }
    return render(request, 'parking.html', info)

还有我的模板

<DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>parking</title>
    </head>

    <body>
        <form method="POST">
            {% csrf_token %}
            {{ form.as_p }}
            <input type="submit" value="save">
        </form>
    </body>

    </html>

当我检查数据库时,它没有保存到数据库中,但是当我检查外壳程序时,它准确地打印出了我键入的内容 但是,如果我使用data_form并像这样编辑views.py

def custom_form(request):
    custom_form = data_form(request.POST or None)
    if custom_form.is_valid():
        custom_form.save()
        custom_form = data_form()
    info = {
        'form': custom_form
    }
    return render(request, 'parking.html', info)

它已保存到数据库。任何帮助都很好

1 个答案:

答案 0 :(得分:0)

FormModelForm背后的想法是不同的。 Form个对象没有save(),而ModelForm个对象没有。

每个ModelForm都有一个save()方法。此方法从绑定到表单的数据创建并保存数据库对象。

对于Form,您必须创建相应的模型对象并改为调用save()

def custom_form_view(request):
    custom_form = data_custom_form()
    if request.method == 'POST':
        custom_form = data_custom_form(request.POST)
        if custom_form.is_valid():
            print(custom_form.cleaned_data)
            obj = data(
                RFID = custom_form.cleaned_data['RFID'],
                Name = custom_form.cleaned_data['Name'],
                Log = custom_form.cleaned_data['Log'],
                License_Plate = custom_form.cleaned_data['License_Plate'],
                Active = custom_form.cleaned_data['Active']
            )
            obj.save()
        else:
            print(custom_form.errors)
    info = {
        'form': custom_form
    }
    return render(request, 'parking.html', info)

这里data_form()继承自ModelFromdata_custom_form()继承自Form。这意味着data_form()对象具有save(),而data_custom_form()没有。因此,当using data_custom_form()(根据您的情况)或每当使用Form时,都必须创建相应的模型对象(此处为data()),将值分配给字段,并且{{1} }