Django ModelForm外键下拉

Django ModelForm Foreign Key Dropdown

我遇到了问题,我找不到错误。 我的外键下拉列表显示“客户端对象 (1)”,但我的模型、视图和表单对于具有相同情况的所有视图都是相似的。

型号:

class Cliente(models.Model):
    nome = CharField(max_length=50)
    cnpj = IntegerField()
    
    dateCriacao = DateTimeField(auto_now_add=True)
    
    def __self__(self):
        return self.nome

产品型号:

class ProdutoCliente(models.Model):
    def filePath(produto, file):
        return os.path.join('produtos', produto, file) 
    numeroSerie = CharField(max_length=30, null=True)
    produto = CharField(max_length=30)
    file = FileField(upload_to=filePath)
    cliente = ForeignKey(Cliente, on_delete=CASCADE)
    dateCriacao = DateTimeField(auto_now_add=True)
    def __self__(self):
        return self.id

观看次数:

def NewCustomerProducts(request):
    createCustomerProducts = CustomerProductsForm()
    if request.method == 'POST':
        createCustomerProducts = CustomerProductsForm(request.POST or None)
        if createCustomerProducts.is_valid():
            createCustomerProducts.save()
            return redirect('products:Customer_Products')
    else:
        createCustomerProducts = CustomerProductsForm()
    context = {'createCustomerProducts' : createCustomerProducts}
    return render(request, 'produtos/NewCustomerProducts.html', context)

表格:

class CustomerProductsForm(ModelForm):
    numeroSerie = fields.CharField (blank=True)
    class Meta:
        model = ProdutoCliente
        fields = [
            'numeroSerie',
            'produto',
            'cliente',
            'file'
        ]
        
        labels = {
            'numeroSerie': ('Número de Série'),
            'produto': ('Produto'),
            'cliente': ('Cliente'),
            'file': ('Arquivo')
        }     

结果: https://imgur.com/Cft5AOW

在模型文件中使用 __str__ 而不是 __self__

def __str__(self):
    return self.nome

查看 Django 文档: https://docs.djangoproject.com/en/4.0/ref/models/instances/#str