Answer the question
In order to leave comments, you need to log in
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__'
***
form.fields['discipline'].queryset = DiscList.objects.filter(username=request.user)
***
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question