Search code examples
djangodjango-generic-views

Add Queryset to django updateview


I have an updateview in which a manager can go and edit all the fields for the associate. Looks like this:(requirement is to add associate_mgr in the as a dropdown in the updateview)enter image description here

views.py

class ReallocationTeam(LoginRequiredMixin,UpdateView):
  model = UserDetails
  form_class = ViewEditSample
  def get_success_url(self):
    return reverse('UserProfile:index')

forms.py

class ViewEditSample(ModelForm):

    class Meta:

        model = UserDetails
        fields = ['associate_name','client','lob','associate_mgr']

The manager should be able to edit the "assciate_mgr" of that associate too. models.py

    associate_name = models.CharField(max_length=200)
    associate_nbr = models.CharField(max_length=8, primary_key=True)
    associate_email = models.EmailField()
    associate_department_id = models.CharField(max_length=50)
    associate_mgr = models.CharField(max_length=100,blank=True, null=True)
    associate_exec = models.CharField(max_length=100,blank=True, null=True)
    associate_org = models.CharField(max_length=100,blank=True,null=True)
    title = models.CharField(null=True, blank=True, max_length=100)
    date_of_service = models.CharField(null=True,blank=True,max_length=11)
    is_manager = models.BooleanField(default=False)
    is_exec = models.BooleanField(default=False)
    is_team_lead = models.BooleanField(default=False)

but associate_mgr is not a choice field in my db. I need to add a dropdown that contains associate_mgr in my UpdateView. How do I go about implementing that? Should I go about writing a query to get all managers and populate them i a dropdow: like this mgr = UserDetails.objects.filter(is_manager=True) But then how do i store the selected in associate_mgr field in db?


Solution

  • You can override your form field in your ModelForm to be a ChoiceField with a list of choices: UserDetails.objects.filter(is_manager=True).values_list('name').

    associate_mgr = forms.ChoiceField(choices=
        UserDetails.objects.filter(is_manager=True).values_list('associate_name', 'associate_name')
    )
    

    Then the choice will automatically be saved (the 'associate_name' field value).

    But it would probably be a better idea to use a ForeignKey on your model, rather than a CharField. That would enforce the values to be other UserDetails rather than just a string.