tags:

views:

195

answers:

1

I have foreign key entries in my model that I'd like to use for my choicefields...now I'm not so sure how to go about this....my model file can be found here Basically I want have a choicefield for vehicle make, model, year, body style, exterior color and transmission. Since all of them work in the same way I just need someone to point me in the right direction then I'm all set.

class Model(models.Model):
   model = models.CharField(max_length=15, blank=False)
   manufacturer = models.ForeignKey(Manufacturer)
   date_added = models.DateField()
   def __unicode__(self):
       name = ''+str(self.manufacturer)+" "+str(self.model)
       return name 

class BodyStyle(models.Model):
   doors = models.PositiveSmallIntegerField()
   passengers = models.PositiveSmallIntegerField()
   style = models.CharField(max_length=15, blank=False)
   def __unicode__(self):
       name = str(self.doors)+" Door / "+str(self.passengers)+" Passenger / "+str(self.style)
       return name
+2  A: 

Perhaps you're looking for ModelChoiceField ?

To use it, you would write something like:

class VehicleForm(forms.Form):
   series = ModelChoiceField(queryset=Series.objects.all()) # Or whatever query you'd like

Then do the same for the other fields.

Of course, you would probably use a ModelForm but that's just an example. Is that what you're looking for?

Bartek
I think this is more of what I want....let me try it out in a couple of minutes then I'll see if it works.
it works fine :) just one issue though...there body style and model model doesn't return just the model name e.g. MDX in my model unicode...it gives the make plus model, so this is what I get in my form but I want only the model. The same for style...see my edit above for the model definition
I'm not sure I fully understand what you're saying (I'm sick so my perception is off .. :)) but I think what you want is to use `label_from_instance` which allows you to modify the output of the field. If you google that, you should find some examples.
Bartek
thnx Bartek...gotten the label_from_instance solution :)
one more question...can I have the drop down menus being populated with existing records only e.g. I might have Acura, Honda, and Nissan but if only the first two have records associated with them then I'll avail only Acura and Honda for selection...is this possible
Of course it is, just apply a filter to the queryset. However, if you want it to be dynamically populated while the user is on the page then you will need to do some AJAX work which calls a view of yours with what the user has selected and then returns some data with the specified filters. I hope that makes sense.
Bartek
I think I'd prefer the filter option...how should I go about this? I want to check if for example, there is a certain record associated with a given foreign key, say for the body style....have a look at my models to get a better picture of the question. thnx