Home > front end >  Django ModelForm Foreign Key Dropdown
Django ModelForm Foreign Key Dropdown

Time:01-08

I'm having a problem and I couldn't find the error. My dropdown with foreign key is showing "Client object(1)", but my models, views and forms is similar for all views that have the same situation.

Model:

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

Model for product:

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

Views:

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)

forms:

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')
        }     

result: https://imgur.com/Cft5AOW

CodePudding user response:

Use __str__ instead of __self__ in your models file:

def __str__(self):
    return self.nome

Check out the Django docs: https://docs.djangoproject.com/en/4.0/ref/models/instances/#str

  •  Tags:  
  • Related