On Mon, 2008-12-08 at 17:46 -0800, Steven Skoczen wrote: > Hi everyone, > > Have run into either a bug or a lack of documentation, and wanted to > see the consensus here before posting a ticket. > > When using a Model with an string foreign key (ie. for a second model > that appears after the referencing model), there's no way to make a > modelform work if it's placed before the second model. > > For example, > > from django.db import models > from django.forms import ModelForm > > class Foo(models.Model): > bars = models.ForeignKey('Bar') > > class FooForm(ModelForm): > class Meta: > model = Foo > > class Bar(models.Model): > ibbity = models.CharField(max_length=255) > > Will error with "AttributeError: 'str' object has no attribute > '_meta'" > > > However, this will work perfectly fine: > > class Foo(models.Model): > bars = models.ForeignKey('Bar') > > class Bar(models.Model): > ibbity = models.CharField(max_length=255) > > class FooForm(ModelForm): > class Meta: > model = Foo > > > > Why this doesn't work makes sense to me, but it seems like it's either > missing in the docs (I couldn't find anything on this effect), or a > bug (if abstracted keys are ok for Foo, that ok should carry over to > FooForm). > > Thoughts?
This is really one of those cases where the documentation doesn't (and probably shouldn't attempt to) address every possible alternative version of code layout. On a technical level, this won't work because the "string" version of foreign keys need to do something after the second model has been created -- it kind of suspends finishing up the internals of some of hte first model's data structures until the second model is finished. So you can't use the first model until that point. On a more pragmatic level, this isn't really an issue. Declaring forms in the same file as models is not a particularly sustainable programming style. They have different roles to play (one is storage level, the other is presentational) and although you may think "I'll only ever have one form related to this model", that will turn out not to be the case more often than you suspect. So, yes, the documentation doesn't address this. Whether it's worth doing so (thereby making the docs longer to avoid something that is going to be fairly unnatural to most experienced programmers anyway), is a separate issue. The problem with addressing every single point on that level is, of course, that the documentation becomes much, much longer and the really important content is lost in the sea of small stuff. Regards, Malcolm --~--~---------~--~----~------------~-------~--~----~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---