Shortcuts for Django form fields

I use ModelForms to create forms for a website, but I want to have more control over what text is displayed in the selection box.

An example model might look like this:

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

So, my problem is that when I create a model model of this model, the foreign key fields are produced in the selection fields, which have the primary key of the object in the base value, and the text is displayed as text from __unicode__() objects. In this case, only the product identifier is displayed (this is the serial number of the code that does not make sense to the user). I would like to be able to create a custom shortcut, for example "[serial], [product name]".

I don't seem to see pointers to the official Django documentation, so I was wondering if anyone would help? :)

+7
source share
1 answer

Check out the Django docs regarding ModelChoiceField . Quote:

The __unicode__ method of the model will be called to generate a string of representations of objects for use in field options; to provide customized views, 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 
+7
source

All Articles