python - 如何根据用户在表单中选择的 ForeignKey 从模型中获取选项?
问题描述
一般来说,我对 Python 和 Django 有点陌生,我正在尝试创建一个表单来将一些汽车添加到我的数据库中,问题是我有一个模型“Coche”,其中包含另外 2 个模型的 2 个外键,BrandCoche 和 ModelCoche同时,ModelCoche 拥有 BrandCoche 的外键。
我需要的是,每次我选择一个品牌时,表格中的模型字段都会更新,因此它只显示该品牌可用的 ModelCoches,而现在,它显示所有模型,而不管选择的品牌是什么。
我的猜测是可以进行某种查询,但到目前为止我一直在搜索并且没有找到任何可能的方法。非常感谢任何帮助^^
模型.py
class BrandCoche(models.Model):
brand = models.CharField(primary_key=True, max_length=20, verbose_name="Marca", validators=[MinLengthValidator(limit_value=3), RegexValidator(regex='^[a-zA-Z ][-]?[a-zA-Z ]+$')]) #PK
def __str__(self):
return self.brand
class ModelCoche(models.Model):
model = models.CharField(primary_key=True, max_length=30, verbose_name="Modelo", validators=[MinLengthValidator(limit_value=2), RegexValidator(regex='^[a-zA-Z0-9 ][-]?[a-zA-Z0-9 ]+$')]) #PK
brand = models.ForeignKey(to=BrandCoche, on_delete=models.CASCADE) #FK con BrandCoche
def __str__(self):
return self.model
class Coche(models.Model):
#PK
matricula = models.CharField(primary_key=True, max_length=8, verbose_name="Matrícula",
validators=[RegexValidator(regex='^[0-9]{4}[-][A-Z]{3}$', message='Error, la matrícula debe seguir el siguiente patrón: '
+ '0000-AAA')])
#FKs
concesionario = models.ForeignKey(Concesionario, on_delete=models.CASCADE) #Relacion 1-N con el CIF de tabla Concesionario
brand = models.ForeignKey(to=BrandCoche, on_delete=models.CASCADE) #Relacion 1-N con Brand de tabla CocheBrand
model_name = models.ForeignKey(to=ModelCoche, on_delete=models.CASCADE) #Relacion 1-N con model_name de tabla CocheModelo
car_type = models.ForeignKey(to=TypeCoche, on_delete=models.CASCADE) #Relacion 1-N con type de tabla CocheType
location = models.ForeignKey(to=Localidad, on_delete=models.CASCADE) #Relacion 1-N con Nombre de tabla Localidad
warranty = models.ForeignKey(Warranty, on_delete=models.CASCADE, verbose_name="Garantía") #FK
doors = models.ForeignKey(Doors, on_delete=models.CASCADE, verbose_name="Puertas") #FK
gearshift = models.ForeignKey(to=Gearshift, on_delete=models.CASCADE, verbose_name="Marchas") #FK
#Attributes
rebaja = models.IntegerField(verbose_name="Rebaja", default=0, validators=[RegexValidator(regex='^[10-80]', message="La rebaja debe de ser entre 10 y 80%"), validate_rebaja])
precio = models.DecimalField(verbose_name="Precio",max_digits= 11, decimal_places= 5, validators=[RegexValidator(regex='^[0-9]{0,6}\.?\d{2}?'), validate_precio])
precioFinal = models.DecimalField(verbose_name="Precio Final", max_digits=11, decimal_places=5)
kilometres = models.IntegerField(verbose_name="Kilómetros", validators=[RegexValidator(regex='[0-300000]', message="Kms entre 0 y 300k"), validate_km])
years = models.IntegerField(verbose_name="Años", validators=[RegexValidator(regex='[0-30]', message="Años entre 0 y 30"), validate_ano])
horsepower = models.IntegerField(verbose_name="Caballos", validators=[validate_horsepower])
description = models.TextField(max_length=512, verbose_name="Descripción", validators=[MinLengthValidator(limit_value=20)])
reserved = models.BooleanField(verbose_name="Reservado?")
sold = models.BooleanField(verbose_name="Vendido?")
created_at = models.DateField(auto_now_add=True, verbose_name="Fecha Creación")
def __str__(self):
return self.matricula
def dateFormat(self):
"""
Formato para la fecha
"""
return self.created_at.strftime('%d - %b - %y')
表单.html
{% extends 'base.html' %}
{% block content %}
<form action="" method="POST">
{% csrf_token %}
<h2 class="m-0">[PH] Title</h2>
{% for field in form.visible_fields %}
<div class="form-control">
{{field.label_tag}}
{{field}}
{% if field.help_text %}
<small class="form-text text-muted">{{field.help_text}}</small>
{% endif %}
</div>
{% endfor %}
<div class="form-control">[PH] Precio Final:<span id="precFinal"></span></div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">
<strong> {{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}
{% endblock %}
{% block script %}
{{block.super}}
{% endblock %}
视图.py
def crearCocheConcesionario(request, cif):
form = CrearCocheConcesionario()
if request.method == 'POST':
form = CrearCocheConcesionario(request.POST)
if form.is_valid():
matricula = form.cleaned_data.get('matricula')
#Precio
precio = float(form.cleaned_data.get('precio'))
rebaja = float(form.cleaned_data.get('rebaja'))
float_precio = round(precio, 5)
#float_rebaja = float(rebaja)
calc = float_precio - (rebaja/100)*float_precio
precioFinal = round(calc, 5)
#-/
brand = form.cleaned_data.get('brand')
model_name = form.cleaned_data.get('model_name')
car_type = form.cleaned_data.get('car_type')
location = form.cleaned_data.get('location')
warranty = form.cleaned_data.get('warranty')
doors = form.cleaned_data.get('doors')
gearshift = form.cleaned_data.get('gearshift')
kilometres = form.cleaned_data.get('kilometres')
years = form.cleaned_data.get('years')
horsepower = form.cleaned_data.get('horsepower')
description = form.cleaned_data.get('description')
concesionario = Concesionario.objects.get(cif=cif)
coche = Coche(matricula=matricula, brand=brand, car_type=car_type, warranty=warranty, doors=doors, gearshift=gearshift,
concesionario=concesionario, model_name=model_name, location=location, rebaja=rebaja, precio=precio, precioFinal=precioFinal,
kilometres=kilometres, years=years, horsepower=horsepower, description=description, reserved=False, sold=False)
coche.save()
messages.success(request, 'El coche se ha añadido correctamente.')
return redirect('addCoche', cif)
context = {'form': form}
return render(request, 'WallaCarApp/coche_form.html', context)
解决方案
推荐阅读
- c# - 如何在通用 Windows 平台 (UWP) 的任何控制下呈现 MS-Word 文件,而不是在单独的文件中打开它?
- java - BASIC,在调用 %d%n 后不能再输出任何字符串?
- tensorflow - @tf.custom_gradient 处于急切模式,参数复杂
- python - 在 tmux 窗口中生成输出时无法滚动 Ipython(不是笔记本!)
- python - 构建分层字符串
- python - 解包元组返回错误的结果
- node.js - 我如何获得由 discord bot 制造商创建的 Discord Bot 以在 Heroku 上工作
- c - A mm:ss 定时器 C
- subdomain - Asp Net Core 2、IIS Express 和子域
- c# - windows 包可以包含在安装程序中吗?