Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Labels for Django select form field

I am using ModelForms to make forms for a website, but I want more control of what text is displayed in the Select box.

An example model could look like this

class Test(models.Model)
    ID = IntegerField()
    Label = CharacterField()
    recipient = ForeignKey(Person)
    product = ForeignKey(Product)

So, my problem is, that when I make a modelForm of this model, the foreign key fields are made into select fields, that has the primary key of the object in the underlying value, and the text displayed is the text from the objects __unicode__() method. In this case, only the product ID is displayed (this is a serial code number, which makes no sense to the user). I would like to be able to make a custom label like "[serial], [product name]".

I can't seem to find any pointers on the official Django documentation, so i wondered if anyone would help? :)

like image 642
Eldamir Avatar asked Aug 16 '12 06:08

Eldamir


People also ask

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

What is label in Django?

label is used to change the display name of the field. label accepts as input a string which is new name of field. The default label for a Field is generated from the field name by converting all underscores to spaces and upper-casing the first letter.

How do I make a field optional in Django?

By default all fields are required. In order to make a field optional, we have to say so explicitly. If we want to make the pub_time field optional, we add blank=True to the model, which tells Django's field validation that pub_time can be empty.


1 Answers

Check out the Django docs regarding the ModelChoiceField. Quote:

The __unicode__ method of the model will be called to generate string representations of the objects for use in the field's choices; to provide customized representations, subclass ModelChoiceField and override label_from_instance. This method will receive a model object, and should return a string suitable for representing it. For example:

class MyModelChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
        return "My Object #%i" % obj.id
like image 188
Torsten Engelbrecht Avatar answered Oct 18 '22 17:10

Torsten Engelbrecht