我有一个名为“ CarForm”的表格。我创建了一个“创建表格”,以使用脆皮表格创建汽车记录。我想问一下是否可以使用相同的表格显示详细信息并更新汽车记录?
这是CarForm的代码:
from .models import *
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit, HTML, Row, Column
from crispy_forms.bootstrap import PrependedAppendedText, PrependedText, FormActions
from django.urls import reverse
class CarForm(forms.ModelForm):
note = forms.CharField(widget=forms.Textarea())
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['note'].required = False
self.fields['policy_num'].required = False
self.helper = FormHelper()
self.helper.form_method = 'POST'
self.helper.form_action = reverse('create')
self.helper.layout = Layout(
Row(
Column('reg_num', css_class='form-group col-md-6 mb-0'),
Column('make', css_class='form-group col-md-6 mb-0'),
Column('year', css_class='form-group col-md-4 mb-0'),
Column('color', css_class='form-group col-md-4 mb-0'),
Column('cc', css_class='form-group col-md-4 mb-0'),
Column('engine_num', css_class='form-group col-md-6 mb-0'),
Column('chasis_num', css_class='form-group col-md-6 mb-0'),
css_class='form-row'
),
'note',
Row(
Column(PrependedAppendedText('price_buy', 'RM','.00'), css_class='form-group col-md-6 mb-0'),
Column(PrependedAppendedText('price_sell','RM','.00'), css_class='form-group col-md-6 mb-0'),
Column('policy_num', css_class='form-group col-md-12 mb-0'),
Column('owner_name', css_class='form-group col-md-4 mb-0'),
Column('owner_ic',css_class='form-group col-md-4 mb-0'),
Column('owner_phone', css_class='form-group col-md-4 mb-0'),
css_class='form-row'
),
FormActions(
Submit('submit', 'Create'),
)
)
class Meta:
model = Car
exclude = ['date']
views.py中的代码。
我已在编辑功能中添加了实例,但是所有字段this field is required
都存在错误
def edit(request,id):
car = Car.objects.get(id=id)
form = CarForm(request.POST,instance=car)
context = { 'car':car ,'form':form }
return render(request,'cars/edit.html',context)
def update(request,id):
car = Car.objects.get(id=id)
car.reg_num = request.POST['reg_num']
car.make = request.POST['make']
car.color = request.POST['color']
car.year = request.POST['year']
car.engine_num = request.POST['engine_num']
car.chasis_num = request.POST['chasis_num']
car.note = request.POST['note']
car.price_buy = request.POST['price_buy']
car.price_sell = request.POST['price_sell']
car.policy_num = request.POST['policy_num']
car.owner_name = request.POST['owner_name']
car.owner_ic = request.POST['owner_ic']
car.owner_phone = request.POST['owner_phone']
car.save()
messages.success(request,'Car "%s" updated successfully' % car.reg_num)
return redirect('/cars/list/')
这是edit.html的代码:
{% block title %}Edit Car Record{% endblock %}
{% load crispy_forms_tags %}
{% block content %}
<h1 align="center">Edit Car Record</h1>
{% crispy form %}
{% endblock %}