A
A
AlexNest2021-01-14 22:24:34
Django
AlexNest, 2021-01-14 22:24:34

How to limit select options by user in django?

There is a third model - disciplines, a list of disciplines and lectures, the last two are associated with the first foreign key.
In the list of disciplines, the disciplines allowed for the user, on which he can write lectures.
You need to limit the value in the form.

class Discipline(models.Model):
    name = models.CharField('Название дисциплины', max_length=50)

class DiscList (models.Model):
    Discipline = models.ForeignKey(Discipline, on_delete=models.CASCADE, null=False)
    username = models.ForeignKey(User,on_delete=models.CASCADE,null=True)


    def __str__(self):
        return self.Discipline.name

    class Meta:
        verbose_name = 'Список дисциплин'
        verbose_name_plural = 'Списки дисциплин'
        unique_together = ('username', 'Discipline')

class Lecture(models.Model):
    User = models.ForeignKey(User,on_delete=models.PROTECT,null=True)
    discipline = models.ForeignKey(Discipline,on_delete=models.PROTECT,null=True)
    title = models.CharField('Название лекции', max_length=150)
    text = models.TextField('Текст лекции')
    date = models.DateField('Дата публикации',auto_now=True)

    class Meta:
        verbose_name = 'Лекция'
        verbose_name_plural = 'Лекции'

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return '/editor/'

Форма
class LectureForm(ModelForm):
    text = forms.CharField(widget=CKEditorWidget())
    class Meta:
        model = Lecture
        fields = ['discipline','title', 'text']
        widgets = {
           'title' : TextInput(attrs={
                'class': 'lect_edit',
                'placeholder' : 'Название'
            }),
            'discipline':Select(attrs={
                'class':'lect_edit'
            }),
        }

class SheludeForm(ModelForm):
    class Meta:
        model = Shelude
        fields = '__all__'

In views, I'm trying to substitute values ​​from the second table
***
 form.fields['discipline'].queryset = DiscList.objects.filter(username=request.user)
***

but the output is
Exception Type: ValueError at /editor/
Exception Value: Cannot assign "": "Lecture.discipline" must be a "Discipline" instance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2021-01-14
@bacon

Cannot assign "": "Lecture.discipline" must be a "Discipline" instance.
What do you not understand about this sentence?
ZY and fields for ForeignKey, in most cases, it is customary to name the same as the class to which they refer, but with a small letter.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question