【问题标题】:django: how to display choices in form's ChoiceField depending on the current user's datadjango:如何根据当前用户的数据在表单的 ChoiceField 中显示选择
【发布时间】:2019-04-24 10:55:33
【问题描述】:

我有以下包含 4 个字段的表单:

from django import forms
from django.apps import apps

from .models import Task

CustomUser = apps.get_model('users', 'CustomUser')

students = CustomUser.objects.filter(status='student')
students_choices = [(student.username, student) for student in students]


class AddTaskForm(forms.ModelForm):
    class Meta:
        model = Task
        fields = ('title', 'description', 'deadline', 'student')
        widgets = {
            'deadline': forms.SelectDateWidget(),
        }

    student = forms.ChoiceField(choices=students_choices)

“学生”字段将显示所有状态为“学生”的用户的选择。但是如果我希望查询集是:

students = CustomUser.objects.filter(status='student', username__in=user.students.split())

我怎样才能在这里获得用户?

【问题讨论】:

    标签: django django-forms


    【解决方案1】:

    首先,不要在模块级别进行查询:

    students = CustomUser.objects.filter(status='student')
    

    这一行将只执行一次(在应用程序启动时)。

    所以回答你的问题:

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['student'] = forms.ChoiceField(choices=((student.id, student.username) for student in custom_queryset))
    

    这当然是 AddTaskForm init

    想知道这是否是某种学生任务;) 编码愉快。

    【讨论】:

    • 我以前试过这个,但是因为我不知道在赋值之前必须调用 super() ,所以出错了。无论如何,谢谢。
    猜你喜欢
    • 2016-04-09
    • 2021-11-17
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多