I have two models, Trade and Fill. A Trade can have many fills. Fill has a FK to Trade:
class Trade(models.Model): trade_date = models.DateField(auto_now_add=True, editable=False) side = models.CharField(max_length=12, choices=SIDE_CHOICES) inst = models.ForeignKey(Inst) class Fill(models.Model): trade = models.ForeignKey(Trade) quantity = models.DecimalField(max_digits=12,decimal_places=2) price = models.DecimalField(max_digits=13,decimal_places=6) fees = models.DecimalField (max_digits=10,decimal_places=2,blank=True,null=True) counterparty = models.CharField(max_length=12) time = models.TimeField() note = models.CharField(max_length=200, blank=True, null=True) I have a web page that shows information about a Trade along with a table of all the Fills for that trade. It also includes a form for adding new Fills. The problem I ran into was that in my view function for saving a new Fill, I need to have the Trade instance set for the form to validate. But it doesn't make sense for the user to edit the Trade since it's tied to the one on the page they were viewing, so the default ModelChoiceField doesn't work for this case. Instead I created a custom field that stores the FK Trade id in a hidden field and then resolves it back to the actual Trade instance in the clean method: class ModelField(forms.CharField): def __init__(self, rel, *args, **kwargs): super(ModelField, self).__init__( widget=forms.HiddenInput, *args, **kwargs) self.rel = rel self.queryset = self.rel.to._default_manager.complex_filter( self.rel.limit_choices_to) def clean(self, value): forms.Field.clean(self, value) if value in (None, ''): return None try: obj = self.queryset.get(pk=value) except self.queryset.model.DoesNotExist: raise ValidationError('Object not found for id: %s' % value) return obj (I stole most of this from ModelChoiceField). I use it like this: class FillForm(forms.ModelForm): trade = ModelField(Fill._meta.get_field('trade').rel) class Meta: model = Fill While this works, it feels like I'm digging into the internals of Django too much with the _meta.get_field() and use of rel and queryset in the ModelField. Does anyone see a simpler solution to this? I feel like I'm missing something obvious. Thanks, -Dave --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---