从html文件获取数据并将其保存到django模型

时间:2018-08-04 19:18:09

标签: django

我创建了多个输入字段,当我单击“提交”时,我需要通过我创建的models.py将这些数据保存到我的数据库中。但是我不明白如何将数据从html重定向到Django。

这是我的html文件

<!DOCTYPE html>

<head>
    <meta charset="utf-8" />
    <title>Cars</title>
    <h1> Enter sales data to store</h1>
</head>

<body>

<div>
    <form method="post">
        {% csrf_token %}
        <label for="billingnumber">Billing Number:</label>
        <input type="number" id="billingnumber" name="billingnumber"><br/>
        <label for="customername" >Customer Name :</label>
        <input type="text" id="customername" name="customername"><br/>
        <label for="purchasedate">Purchase Date:</label>
        <input type="date" id="purchasedate" name="purchasedate"><br/>
        <label for="price">Price:</label>
        <input type="number" id="price" name="price" ><br/>
        <label for="carcompany">Car Company:</label>
        <input type="text" id="carcompany" name="carcompany"><br/>
        <label for="carmodel">Car Model:</label>
        <input type="text" id="carmodel" name="carmodel"><br/>
        <label>Car Serial Number:</label>
        <input type="number" id="carserial" name="carserial"><br/>
        <label for="mfgdate">Car Manufacturing Date:</label>
        <input type="date" id="mfgdate" name="mfgdate"><br/>
        <label for="shippingdate">Shipping Date:</label>
        <input type="date" id="shippingdate" name="shippingdate"><br/>
        <button type="submit" value="submit">Submit</button>
        </form>
</div>
<a href="/">Home<a>
</body>
</html>

这是我的模型。py

class cars(models.Model):
    billingnumber = models.BigIntegerField(primary_key=True)
    customer = models.TextField()
    price = models.IntegerField()
    purchasedata = models.DateTimeField()
    carcompany = models.TextField()
    carmodel = models.TextField()
    carserialnumber = models.BigIntegerField()
    carmfgdate = models.DateTimeField()
    shippingdate = models.DateTimeField()

这些是我的网址格式

urlpatterns = [
    url(r"^$", TemplateView.as_view(template_name="index.html"), name="home"),
    url(r"^store/$", TemplateView.as_view(template_name="store.html"), name="store"),
    url(r"^access/$", TemplateView.as_view(template_name="access.html"), name="access"),
    url(r"^about/$", TemplateView.as_view(template_name="about.html"), name="about"),
    ]

我无法理解如何编写views.py,但这是我尝试获取数据的方式

from django.shortcuts import render
from django.views.generic import TemplateView
from django.http import HttpResponseRedirect

# Create your views here.
from .forms import myform
from .models import cars

def get_data(request):
        if request.method=="POST":
            form = myform(request.POST)
            if form.is_valid():
                cars.billingnumber(form)
                cars.save()
                return HttpResponse('<html><body>Data Saved</body></html>')
        else:
            form = myform()
            return render(request, 'sample.html', {'form': form})

forms.py

from django import forms

class myform(forms.Form):
    billingnumber = forms.CharField(label="billing number")

我如何更改这些文件,我是新手,正在考虑django

2 个答案:

答案 0 :(得分:0)

您应该使用ModelForm而不是form并将其绑定到您的汽车模型。这样,所有模型字段都可以通过表单使用。

from django.forms import ModelForm
from .models import cars

class myform(ModelForm):
    class Meta:
        model = cars

比在您的html中只显示所有表单字段。您可以使用form.as_p完成此操作,也可以在所需的html元素内分别渲染每个字段。检查Django form rendering以获得有关表单呈现的更多信息。

<div>
    <form method="post">
        {% csrf_token %}

        {{ form.as_p }}

        <button type="submit" value="submit">Submit</button>
    </form>
</div>

答案 1 :(得分:0)

在django中,有一个ModelForm可以根据模型自动创建表单。

models.py

这是models.py文件,只做了很小的更改:

  • 类名应位于PascalCase
  • 您可能不需要TextFields,我想CharField就足够了
  • 如果我们使用的是Car模型,则不必在每个名称前加上car(例如,最好写成model而不是carmodel li>
  • 使用下划线分隔多字变量(例如,用shipping_date代替shippingdate

因此有一个文件:

from django.db import models


class Car(models.Model):
    billing_number = models.BigIntegerField(primary_key=True)
    customer = models.CharField(max_length=100)
    price = models.IntegerField()
    purchase_date = models.DateTimeField()
    company = models.CharField(max_length=100)
    model = models.CharField(max_length=100)
    serial_number = models.BigIntegerField()
    mfg_date = models.DateTimeField()
    shipping_date = models.DateTimeField()

forms.py

现在,已经准备好Car模型,我们可以创建ModelForm。就这么简单:

from django.forms import ModelForm
from .models import Car

class CarForm(ModelForm):
    class Meta:
        model = Car
        exclude = ()  # this says to include all fields from model to the form

如果要在表单中显示有限数量的字段,可以编写:

class CarForm(ModelForm):
    class Meta:
        model = Car
        fields = ('customer', 'price', 'model')  # this would only display 3 fields on the form

views.py

我们拥有创建视图以处理模型创建表单所需的一切。

views.py文件中添加新功能:

from django.http import HttpResponse
from django.shortcuts import render
from .forms import CarForm


def add_car(request):
    if request.method == 'POST':  # data sent by user
        form = CarForm(request.POST)
        if form.is_valid():
            form.save()  # this will save Car info to database
            return HttpResponse('Car added to database')
    else:  # display empty form
        form = CarForm()

    return render(request, 'add_car.html', {'car_form': form})

urls.py

将此新视图添加到urls.py文件中:

from django.urls import path
from myapp import views

urlpatterns = [
    # ...
    # your other urls
    # ...
    path('add-car', views.add_car, name='add_car'),
]

templates / add_car.html

add_car视图使用的模板:

<form action="{% url 'add_car' %}" method="post">
    {% csrf_token %}
    {{ car_form.as_p }}
    <input type="submit" value="Save new car">
</form>

重要的行是<form action="{% url 'add_car' %}" method="post">。这表示将POST请求发送到add_car网址。网址名称在此处定义:path('add-car', views.add_car, name='add_car')name参数)。

应用这些更改之后,您应该可以访问/add-car并填写一个表格,该表格会将新记录添加到数据库中。

显示存储的记录

要显示数据库中的记录,您必须:

  • 添加新网址
  • 创建新视图以获取记录
  • 创建新模板以列出汽车

urls.py-将此行添加到urlpatterns

path('cars', views.car_list, name='car_list'),

查看:

def car_list(request):
    return render(request, 'car_list.html', {
        # this will fetch all cars from database
        'cars': Car.objects.all()
    })

现在创建template car_list.html,您可以在其中显示所有汽车

<ul>
    {% for car in cars %}
        <li>{{ car.model }}</li>
    {% endfor %}
</ul>

显示单个记录的详细信息

urls.py添加新行:

path('car/<int:car_billing_number>', views.car_details, name='car_details'),

views.py检索单个模型信息也很简单

def car_details(request, car_billing_number):
    return render(request, 'car_details.html', {
        'car': Car.objects.get(billing_number=car_billing_number)
    })

最后-car_details.html模板。

<table style="border: 1px solid black">
    <tr><td>Billing number</td><td>{{ car.billing_number }}</td></tr>
    <tr><td>Model</td><td>{{ car.model }}</td></tr>
    <tr><td>Company</td><td>{{ car.company }}</td></tr>
    <tr><td>Price</td><td>{{ car.price }} $</td></tr>
    {# and so on #}
</table>

现在,当您拥有帐单号为123的汽车时,您可以访问网站car/123并查看详细信息。