如何获取选定项目的列表阶段并将其放入Django中的forms.ModelChoiceField中

2024-05-01 03:23:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个新产品,第一步是在第一个字段中选择一个项目,第二步是给出在第一个字段中选择的项目阶段列表。我怎么做到的

这是我的型号:

class Project(models.Model):
    STATUS_CHOICE = (
        ('En cours', 'En cours'),
        ('Arret', 'Arret'),
        ('Terminer', 'Terminer'),
    )
    CATEGORY_CHOICE = (
        ('Hydraulique Urbaine', 'Hydraulique Urbaine'),
        ('Assainissement', 'Assainissement'),
        ('Hydro Agricole', 'Hydro Agricole'),
        ('Step', 'Step'),
        ('Barrage', 'Barrage'),
        ('AEP', 'AEP'),
    )
    name = models.CharField(max_length=400, unique=True)
    delais = models.IntegerField()
    ods_demarage = models.DateField()
    montant_ht = models.DecimalField(decimal_places=2, max_digits=20)
    montant_ttc = models.DecimalField(decimal_places=2, max_digits=20)
    category = models.CharField(max_length=25, choices=CATEGORY_CHOICE)
    status = models.CharField(max_length=20, choices=STATUS_CHOICE)
    client = models.ForeignKey(Client, on_delete=models.CASCADE, null=True)

    def __str__(self):
        return self.name


class Phase(models.Model):
    name = models.CharField(max_length=200, unique=True)
    montant = models.DecimalField(max_digits=20, decimal_places=2)
    project = models.ForeignKey(Project, on_delete=models.CASCADE, null=True)

    def __str__(self):
        return self.name


class Production(models.Model):
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    phase = models.ForeignKey(Phase, on_delete=models.CASCADE)
    montant = models.DecimalField(max_digits=20, decimal_places=2)
    taux = models.DecimalField(max_digits=6, decimal_places=2)
    montant_prod = models.DecimalField(max_digits=20, decimal_places=2)
    date = models.DateField(auto_now_add=True)

这是我的视图方法:

def create_production(request):
    form = NewProductionForm()
    if request.method == 'POST':
        form = NewProductionForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/')

    context = {
        'production': form
    }
    return render(request, 'production/create_production.html', context)

我的表格

class NewProductionForm (forms.ModelForm):
    class Meta:
        model = Production
        fields = '__all__'