views:

57

answers:

2

Hello, I wonder if is it possible to add some conditional fields in django. Say I have a category model which has an ID, name and description fields. What I would like is to add a many-to-many field in my Product model that links it with the Category ID model... and as a helping reference show what the name of that Category would be. I know I could just link it to the category name, but my real scenario is a bit more complex and I would really need to display a second field based on the selection in another !

Many thanks!

A: 

That's not a conditional field. If I understand you correctly, all you really need is to customise the display of the related item, so that it shows the name field rather than the raw ID. Luckily, that is what Django will do by default if you define a __unicode__ method on the Category model, which returns the value you want to display instead of the ID.

Daniel Roseman
umh... Im not sure I explained myself correctly: I need this to happen in the admin site. Im still at the very beginning of my django experience, but I thinh the __unicode__ method is to use in templates and other documents but not in the admin panel. THANSK
mαττjαĸøb
No, that works wherever you have a foreign key, including the admin site.
Daniel Roseman
+1  A: 

In addition to Daniel's answer: If you just want to customize the representation of the objects in a ModelChoiceField (and not change it in general what you would do with the __unicode__ method): The field class has method label_from_instance, which returns by default the object's unicode value, but you can override it as you like:

class CategoryChoiceField(forms.ModelChoiceField):

     def label_from_instance(self, obj):
         return "%s %s" % obj.pk, obj.name
lazerscience
does this work in the admin site? that's where I need this info to be displayed... I need some fields to be filled automatically based on the value of some other fields. thanks
mαττjαĸøb