我有一个字段,用户可以在其中选择车辆的车牌,根据这个选择,我希望从车辆表(查询:)中填充一个表单vehicle = Vehicles.objects.get(plate=plate)
。我用这个视图管理这个:
def vehicles_archive(request):
user = request.user
user_id = user.id
u_id = user_id
vehicles = Vehicles.objects.filter(own_id1 = u_id)
if request.method == 'POST':
plate = request.POST.get('searchPlate')
vehicle = Vehicles.objects.get(plate=plate)
form = VehiclesForm(data=request.POST, instance=vehicle, own_id=u_id)
if form.is_valid():
form.save()
return render_to_response('success.html', locals(), context_instance= RequestContext(request))
else:
vehicles = Vehicles.objects.filter(own_id1 = u_id)
vehicle = Vehicles.objects.get(plate=plate)
form = VehiclesForm(instance=vehicle, own_id=u_id)
return render_to_response('vehiclesArchive.html', locals(), context_instance= RequestContext(request))
一切似乎都工作正常,但是当我编辑表单字段并尝试提交我得到的表单时:车辆匹配查询不存在。并表示用车牌查询。我使用的逻辑一定有错误,但我该如何解决?或者有没有更好的方法来实现上述功能?
编辑:
class Vehicles(models.Model):
id = models.DecimalField(primary_key=True, unique=True, max_digits=127, decimal_places=0)
plate = models.CharField(max_length=80, unique=True)
tempflag = models.BooleanField()
vht_id = models.ForeignKey('Vehtypes', null=True, db_column='vht_id', blank=True)
vlength = models.DecimalField(null=True, max_digits=127, decimal_places=0, blank=True)
vwidth = models.DecimalField(null=True, max_digits=127, decimal_places=0, blank=True)
vheight = models.DecimalField(null=True, max_digits=127, decimal_places=0, blank=True)
vnetweight = models.DecimalField(null=True, max_digits=127, decimal_places=0, blank=True)
vmaxload = models.DecimalField(null=True, max_digits=127, decimal_places=0, blank=True)
axleno = models.DecimalField(null=True, max_digits=127, decimal_places=0, blank=True)
chassis = models.CharField(max_length=160, blank=True)
man_id = models.ForeignKey('Manufacturers', null=True, blank=True, db_column='man_id')
own_id1 = models.ForeignKey('Owners', null=True, db_column='own_id1', related_name='veh_own_id1', blank=True)
own_id2 = models.ForeignKey('Owners', null=True, db_column='own_id2',related_name='veh_own_id2', blank=True)
ins_id = models.ForeignKey('Insurancecompanies', null=True, blank=True, db_column='ins_id')
modelno = models.CharField(max_length=160, blank=True)
checkflag = models.BooleanField()
def __unicode__(self):
return self.plate
class Meta:
db_table = u'vehicles'
ordering = ['plate']
而 searchPlate 是一个随机字段,仅用于获取用户的选择。我认为所有者模型定义并不重要。