Skip to content Skip to sidebar Skip to footer

Access Request From The Forms.form To Get Data From Db Related To User

So basic task is: add the template name and text to the choices in the ChoiceField with Selector widget to the form using the data from dB linked to the authenticated User only. Te

Solution 1:

You can pass request to your form by changing your __init__ method like this :

classInformForm(forms.Form):
...
   def__init__(self, user=None,*args, **kwargs):
        super(InformForm, self).__init__(**kwargs)
        if user:  
            self.fields['somefield'] = forms.ChoiceField()                  
            self.fields['somefield'].widget = forms.Select()
            self.fields['somefield'].queryset = Someobject.objects.filter(User=user)
...

If the User is linked to other object in db by Foreign key, then you will get all the values of other object as select items.

Also , when creating form you could pass user like this :

form= InformForm(user=request.user,data=request.POST)

Post a Comment for "Access Request From The Forms.form To Get Data From Db Related To User"