Friday, July 17, 2009

Foreign Key in Hidden Field

In order to have a hidden foreign key your in your form class you need to specify:
class PlanForm(forms.ModelForm):    
    owner = forms.ModelChoiceField(label="",queryset=Profile.objects.all(),widget=forms.HiddenInput())

Class definition order between two related classes

I ran into an issue where I wanted to have a foreign key to one class then over ride the save in the other class to update the current class. It would through and error because one of the classes was not defined. I finally found this post Class definition order between two related classes and see that you can but the models name in quotes in the foreign key. example:
class Foo(models.Model):
    bar = models.ForeignKey("Bar")
    name = models.CharField(max_length=100)

class Bar(models.Model):
    name = models.CharField(max_length=100)
    def save(self):
        foos = Foo.objects.filter(item=self)         
        super(Bar, self).save()