Home > Back-end >  Django forms: rendering different data in forms per users login
Django forms: rendering different data in forms per users login

Time:10-15

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',
    })
    )

CodePudding user response:

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)
  • Related