The problem is that trade is required so is_valid will fail.
On Dec 13, 5:01 pm, Daniel Roseman <roseman.dan...@googlemail.com>
wrote:
> On Dec 13, 9:30 pm, DavidA <david.avraami...@gmail.com> wrote:
>
>
>
> > 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:
>
> <snip interesting code>
>
> > 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
>
> Well, this does seem like a bit of overkill for what is after all a
> fairly common use case, if I'm understanding you correctly.
>
> Perhaps a better way would be not bother setting the FK value in the
> form at all, but to grab it from the request inside the view and use
> it there. For example:
>
> def add_fill(request, trade_id):
> trade = get_object_or_404(Trade, trade_id)
> if request.method == 'POST':
> form = AddFillForm(request.POST)
> if form.is_valid():
> new_fill = form.save(commit=False)
> new_fill.trade = trade
> new_fill.save()
> ... etc ...
>
> Does that work for you?
> --
> DR.
--~--~---------~--~----~------------~-------~--~----~
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
-~----------~----~----~----~------~----~------~--~---