tags:

views:

294

answers:

2

I have created a Profile model including the Gender info. There is also models called Dorm and Registration (not used for user registration) like this:

class Registration(models.Model):
user = models.ForeignKey(User)
pref1 = models.ForeignKey(Dorm, related_name="pref1",verbose_name=u"Preference 1",null=True)
...
friend1 = models.CharField(u"Friend 1", max_length=15,blank=True)

class Dorm(models.Model):
name = models.ForeignKey(Building)
gender = models.CharField(u"Gender", max_length=1, blank=True, choices=GENDER_CHOICES)

Now, i am trying to generate a form for this Registration model with forms.ModelForm like this:

class RegistrationForm(forms.ModelForm):
dorms = Dorm.objects.filter(gender='M')
pref1 = forms.ModelChoiceField(queryset=dorms, empty_label=None)
...
class Meta:
    model = Registration
    exclude = ('user')

as you can see in the second line, i am querying the dorms with a hardcoded gender value M. Instead of the hardcoded value, I need to get the users' gender, and query the database with that gender information.

I have searching the documentation but I could not find anything. Can you help me? How can I learn the logged-in User' profile information in Django Forms?

+2  A: 

Hi yigit,

James Bennett wrote a blog post that should explain perfectly what you need: So you want a dynamic form

Van Gale
+4  A: 

So without using some sort of monkeying around of the init function a "form_factory" is probably the best approach.

def RegFormFactory(user)

    dorms = Form.objects.filter(gender = "user.gender")
    class _RegistrationForm(forms.ModelForm):
     pref1 = forms.ModelChoiceField(queryset = dorms, empty_label=None)
     class Meta:
      model = Registration
      exclude = ('user')

    return _RegistrationForm

then use:

formclass = RegFormFactory(user)
form_inst = formclass()
...
form_inst = formclass(request.POST)

This is described very nicely in a blog post here: So you want a dynamic form.

JudoWill
obviously replace "user.gender" with whichever method you use to get gender from a user
JudoWill
thanks. it really helped.
yigit