Django forms: rendering different data in forms per users login

Question:

Hello i’m currently making a webiste in Django, is it possible to render different select fields by querying the objects atributed in user via request.user.id to obtain and get the datas inputted by the user instead of all data gathered on all users? thank you so much

class clientforms(forms.Form):
  projectfield = forms.ModelChoiceField(queryset= Project.objects.all(),
    widget=forms.Select(attrs={
        'class' : 'form-control',
    })
    )

Asked By: se6

||

Answers:

credits to original answer :
Django forms: rendering different data in forms per users login

based on the previous answer on the link you must override the original forms

forms.py

class clientforms(forms.Form):
 projectfield = forms.ModelChoiceField(queryset= Project.objects.all().filter(profile=1),
    widget=forms.Select(attrs={
        'class' : 'form-control',
    })
    )
    #add the overriding function
    def __init__(self, user, *args, **kwargs):
        super(clientforms, self).__init__(*args, **kwargs)
        self.fields['projectfield'].queryset=Project.objects.all().filter(profile=Profile.objects.get(user_id=user.id))

on your views.py

# add the request.user on your forms
user = request.form
form = clientforms(user)
Answered By: ubuntuMAN
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.