yigit
yigit

Reputation: 382

How to get logged-in user info in Django's forms.py

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 been 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?

Upvotes: 0

Views: 2292

Answers (2)

JudoWill
JudoWill

Reputation: 4811

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.

Upvotes: 4

Van Gale
Van Gale

Reputation: 43912

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

Upvotes: 2

Related Questions