Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何根据用户在表单中选择的外键从模型中获取选项?_Python_Html_Django_Templates - Fatal编程技术网

Python 如何根据用户在表单中选择的外键从模型中获取选项?

Python 如何根据用户在表单中选择的外键从模型中获取选项?,python,html,django,templates,Python,Html,Django,Templates,一般来说,我对Python和Django有点陌生,我正在尝试创建一个表单,将一些汽车添加到我的DB中,问题是我有一个模型“Coche”,它有两个外键,分别指向另外两个模型BrandCoche和ModelCoche,同时ModelCoche有一个指向BrandCoche的外键 我需要的是,每次我选择一个品牌时,模型字段都会在表单中更新,因此它只显示该品牌可用的模型,而现在,它会显示所有模型,而不管选择的品牌是什么 我的猜测是可以进行某种查询,但到目前为止,我一直在搜索,还没有找到任何可能的方法。非

一般来说,我对Python和Django有点陌生,我正在尝试创建一个表单,将一些汽车添加到我的DB中,问题是我有一个模型“Coche”,它有两个外键,分别指向另外两个模型BrandCoche和ModelCoche,同时ModelCoche有一个指向BrandCoche的外键

我需要的是,每次我选择一个品牌时,模型字段都会在表单中更新,因此它只显示该品牌可用的模型,而现在,它会显示所有模型,而不管选择的品牌是什么

我的猜测是可以进行某种查询,但到目前为止,我一直在搜索,还没有找到任何可能的方法。非常感谢您的帮助^^

models.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')
form.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 %}
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)