0

I am having trouble to find a way to make it work; I need to get the queryset with a list of the team created by the current logged in user.

My form look the following :

from django import forms
from django.contrib.auth.models import User
from registration.models import MyUser
from .models import Project, Team
from django.contrib.auth import get_user_model

User = get_user_model()



class EditSelectTeam(forms.Form):

    team_choice = forms.ModelChoiceField(widget=forms.RadioSelect, queryset=Team.objects.all().filter(team_hr_admin=request.User))
    #team_id = forms.ChoiceField(queryset = Team.objects.filter(team_hr_admin= MyUser))

    def team_select(self):
        data = self.cleaned_data['team_choice']
        return data

views.py:

def TeamSelect(request):
    if request.method == "POST":
        select_form = EditSelectTeam(request.POST)
        print('sucess')

    else:
        select_form = EditSelectTeam(request)
    return render(request,'link_project.html',
                            {'select_form':select_form })

I get the error that request is not define

Ben2pop
  • 746
  • 1
  • 10
  • 26
  • Possible duplicate of [Creating a dynamic choice field](https://stackoverflow.com/questions/3419997/creating-a-dynamic-choice-field) – georgeofallages Sep 25 '17 at 20:34
  • I suck at using SO, but I think you can find your answer in that other question. Can you override your EditSelectTeam constructor to take store the user for team_choice filtering? – georgeofallages Sep 25 '17 at 20:37

1 Answers1

0

you can pass the request using init method like:

class EditSelectTeam(forms.Form):

    team_choice = forms.ModelChoiceField(widget=forms.RadioSelect, queryset=None)

    def __init__(self, request, *args, **kwargs):
        super(EditSelecTeam, self).__init__(*args, **kwargs)
        self.fields['team_choice'].queryset = Team.objects.all().filter(team_hr_admin=request.User))

    def team_select(self):
        data = self.cleaned_data['team_choice']
        return data

Remember pass in your form the request like:

form = your_form(request)
Mauricio Cortazar
  • 4,049
  • 2
  • 17
  • 27
  • Hi Mauricio thx for your answer. Now when I try the POST in my form it say that QueryDict' object has no attribute 'user'. I updated my question with the view. Any Idea ? – Ben2pop Sep 26 '17 at 06:51
  • select_form = EditSelectTeam(request, request.POST try with that and tell me – Mauricio Cortazar Sep 26 '17 at 15:07