我创建了多个输入字段,当我单击“提交”时,我需要通过我创建的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
答案 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
文件,只做了很小的更改:
TextFields
,我想CharField
就足够了Car
模型,则不必在每个名称前加上car
(例如,最好写成model
而不是carmodel
)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()
现在,已经准备好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
文件中添加新功能:
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
文件中:
from django.urls import path
from myapp import views
urlpatterns = [
# ...
# your other urls
# ...
path('add-car', views.add_car, name='add_car'),
]
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
并查看详细信息。