[英]How to let not all the data show up using a choice field but only the ones related to the choice field in Django?
[英]How can I choose which choice to show up in django form field?
我正在尝试根据用户动态更改 django 表单选择字段中的可见选项。 这是我的表格:
SubmitForm(forms.ModelForm):
class Meta:
model = Lesson
fields = (
"status",
)
这是我的Lesson
models.py:
CLASS_STATUS = (
('Attended', 'Attended'),
('Absent', 'Absent'),
('Teacher Postponed', 'Teacher Postponed'),
('Student Postponed', 'Student Postponed'),
)
status = models.CharField(
max_length=30,
choices=CLASS_STATUS,
null=True,
blank=True,
)
所以,基本上我希望能够为每种类型的用户选择要显示的选项。 为了做到这一点,我希望你们也可以展示我如何在我的表单中访问request.user
信息。 谢谢,有什么问题可以问我。
以下是你们中一些人要求的部分视图:
class SubmitView(generic.UpdateView):
template_name = "agents/submit_form.html"
queryset = Lesson.objects.all()
context_object_name = "lesson"
form_class = SubmitForm
我已经尝试过但未能通过 ModelForm 实现此功能。 我认为你最好的答案是退回到使用原版表单,并手动更新对象。 就像是
class Status_form( forms.Form):
status = forms.ChoiceField( choices=Lesson.STATUS_CHOICES)
class UpdateLessonView( FormView):
form_class = Status_form
template_name = "agents/submit_form.html"
def form_valid( self, form):
self.lesson.status = form.cleaned_data['status']
self.lesson.save()
return redirect(
'lessons:lesson_detail', lesson=self.lesson.pk )
def get_form( self, form_class=None):
self.lesson = get_object_or_404( Lesson, id=self.kwargs['lesson'] )
self.initial = { 'status': self.wafer.status }
form = super().get_form( form_class)
# modify choices depending on user
if self.request.user ... :
status_choices=( (..., ...), ... )
form.fields['status'].choices = status_choices
return form
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.