I have a generic UpdateView where the leaders can manage the settings of the users whom connected to the leaders's company.
I like to have only that values in the select field where the company_id is equal to the the company_uuid in the url.
Now the leader who want to set the team can access to all of the companies teams.
Thank you in advance
models.py
class Company(models.Model):
def __str__(self):
return str(self.company_name)
def generate_uuid():
return uuid.uuid4().hex
company_name = models.SlugField(max_length=100)
company_uuid = models.CharField(default=generate_uuid, editable=True, max_length=40)
class Team(models.Model):
def __str__(self):
return str(self.team)
team = models.CharField(max_length=200, blank=True, null=True)
company = models.ForeignKey(Company, null=True, blank=True, on_delete=models.CASCADE)
class Profile(models.Model):
def __str__(self):
return str(self.user)
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
date = models.DateField(auto_now_add=True, auto_now=False, blank=True)
company = models.ForeignKey('Company', on_delete=models.CASCADE, blank=True, null=True)
team01 = models.ForeignKey('Team', on_delete=models.CASCADE, null=True, blank=True, related_name="eteam")
views.py
class UpdateProfileView(SuccessMessageMixin, UpdateView):
model = Profile
form_class = UpdateProfileForm
template_name = 'users/management/update_profile.html'
success_message = 'Változtatások mentve'
def get_success_url(self):
return self.request.META.get('HTTP_REFERER')
urls.py
...
path('management/update_profile/<pk>/<uuid>', login_required(UpdateProfileView.as_view()), name='UpdateProfile'),
...
In the forms I don't using any widget.
Would be good to see your forms.py as well just to make sure this is correct, but if it's all set up as standard then this should work:
To filter the choices of the team01 field based on the company_uuid in the URL, you should override the get_form()
method in your UpdateProfileView
. In this method, you alter the queryset for the team01 field to include only the teams associated with the specified company.
See below:
views.py
class UpdateProfileView(SuccessMessageMixin, UpdateView):
model = Profile
form_class = UpdateProfileForm
template_name = 'users/management/update_profile.html'
success_message = 'Változtatások mentve'
def get_form(self, form_class=None):
form = super().get_form(form_class)
company_uuid = self.kwargs.get('uuid')
company = get_object_or_404(Company, company_uuid=company_uuid)
form.fields['team01'].queryset = Team.objects.filter(company=company)
return form
def get_success_url(self):
return self.request.META.get('HTTP_REFERER')
Hope this helps, let me know if not (as said, would be good to see the form as well but if you've done it normally the above fix should be fine)