Search code examples
djangoformsmodels

Django form field display name


I m trying to make a form on the basis of a model. Trouble is that when i create a category via django shell, let's say "Wedding" category, having id=1 and name = "weddings", when i display it in a dropdown(in html form) it shows as Categories object (1) and i would like it to be shown by the name, which is weddings.

As in the documentation i understand that i can attach labels when in the Meta form class but i don't fully understand how i can display dynamically all the category names instead of Categories object 1,2,3,4.

Models.py

class categories(model.Model):
    id = models.AutoField(primary_key =True)
    name = models.Charfield(max_length = 50)

class Event(models.Model):
    id = models.AutoField(primary_key =True)
    category = models.ForeignKey(Categories,on_delete=models.SET_NULL,null = True)
    owner = models.Charfield(max_length = 50)

Forms.py

class EventForm(forms.ModelForm):
class Meta:
    model = Event
    fields = ['category','person','owner']

So the actual result when rendering the form is :

Category:(dropdown) - Categories object (1)

Desired result:

Category:(dropdown) - weddings

Solution

  • class categories(model.Model):
        id = models.AutoField(primary_key =True)
        name = models.Charfield(max_length = 50)
    
        def __str__(self):
            return self.name
    
    class Event(models.Model):
        id = models.AutoField(primary_key =True)
        category = models.ForeignKey(Categories,on_delete=models.SET_NULL,null = True)
        owner = models.Charfield(max_length = 50)
    
    
        def __str__(self):
            return self.owner
    

    just add this little magic functions to your model classes.