**forms.py** class KomForm(forms.ModelForm): class Meta: model = Kom fields = ('company', 'title',) **models.py** class Company(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title class Kom(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) company = models.ForeignKey(Company, on_delete=models.CASCADE) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title_ Tell me how you can when filtering a form to filter Company objects so that the user sees in the ModelChoiceField field only those companies (Company) that he created himself.
Thanks to the invaluable help of caring people, I solved this problem. The correct answer is Where Answer; the only thing was that I had to change something in some places. It turned out like this, and it works:
def __init__(self, *args, **kwargs): # вызываем конструктор формы и сохраняем пользователя if 'user' in kwargs and kwargs['user'] is not None: user = kwargs.pop('user') qs = Company.objects.filter(author__id=user.id) super(KommpredForm, self).__init__(*args, **kwargs) self.fields['company'].queryset = qs and in the submission it is necessary to indicate like this:
form = KommpredForm (request.POST, user = user)