[英]How can I choose which choice to show up in django form field?
I am trying to dynamically change the viewable choices in a django form choice field depending on the user.我正在尝试根据用户动态更改 django 表单选择字段中的可见选项。 Here is my form:
这是我的表格:
SubmitForm(forms.ModelForm):
class Meta:
model = Lesson
fields = (
"status",
)
Here is my models.py for Lesson
:这是我的
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,
)
So, basically I want to be able to select which choices to show for each type of user.所以,基本上我希望能够为每种类型的用户选择要显示的选项。 In order to do this, I hope you guys could also show how I could access the
request.user
information in my form.为了做到这一点,我希望你们也可以展示我如何在我的表单中访问
request.user
信息。 Thank you, and please ask me any questions you have.谢谢,有什么问题可以问我。
Here is a part of the view as some of you requested:以下是你们中一些人要求的部分视图:
class SubmitView(generic.UpdateView):
template_name = "agents/submit_form.html"
queryset = Lesson.objects.all()
context_object_name = "lesson"
form_class = SubmitForm
I have tried and failed to get this working with a ModelForm.我已经尝试过但未能通过 ModelForm 实现此功能。 I think your best answer is to retreat to using a vanilla Form, and manually update the object.
我认为你最好的答案是退回到使用原版表单,并手动更新对象。 Something like
就像是
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.