我想在Form类中传递self.request个数据.我可以在视图中访问它,但不能在Form类中访问它.

class AttendanceCreateView(LoginRequiredMixin, CreateView):
    model = Attendance
    template_name = 'attendance/attendances_new.html'
    form_class = AttendanceForm

    def get_initial(self):
        initial = super().get_initial()
        initial['class_name'] = self.request.GET.get('class', '')
        return initial

我的表单类:

class AttendanceForm(forms.ModelForm):
    class_name = forms.ChoiceField(choices=CLASS_NAMES, disabled=True)
    teacher = forms.ModelMultipleChoiceField(
        queryset=Teacher.objects.all().order_by('id'))
    subject_name = forms.ChoiceField(choices=[])
    total_students = forms.IntegerField(initial=0)
    unique_code = forms.IntegerField(initial=0)

    class Meta:
        model = Attendance
        fields = ['class_name', 'teacher', 'subject_name',
                  'total_students', 'unique_code']

    def __init__(self, *args, **kwargs):
        super(AttendanceForm, self).__init__(*args, **kwargs)
        
        # This I need to be done
        # if self.request.GET.get('class', '') = 'class1':
        #    self.fields['subject_name'].choices = MY_CHOICES_1 
        # elif self.request.GET.get('class', '') = 'class2':
        #    self.fields['subject_name'].choices = MY_CHOICES_2
        

我想根据传递的请求值设置subject_name个选项.对于第一类,我想要不同的主题 Select .对于第二类,我想要不同的主题 Select 等等.因此,获取请求数据是很重要的.

有没有办法在直接视图中设置初始选项,就像我在class_name中所做的那样?或者对如何在形式上做到这一点有什么建议?

推荐答案

将请求传递给form_kwargs:

class AttendanceCreateView(LoginRequiredMixin, CreateView):
    model = Attendance
    template_name = 'attendance/attendances_new.html'
    form_class = AttendanceForm

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs['request'] = self.request
        return kwargs

    def get_initial(self):
        initial = super().get_initial()
        initial['class_name'] = self.request.GET.get('class', '')
        return initial

然后我们在下面的表单中处理:

class AttendanceForm(forms.ModelForm):
    # …

    def __init__(self, *args, request, **kwargs):
        self.request = request
        super().__init__(*args, **kwargs)
        if self.request.GET.get('class', '') == 'class1':
            self.fields['subject_name'].choices = MY_CHOICES_1
        elif self.request.GET.get('class', '') == 'class2':
            self.fields['subject_name'].choices = MY_CHOICES_2

Note:从PEP-3135 [pep]开始,如果第一个参数是在其中定义方法的类,第二个是函数的第一个参数(通常是self),则不需要使用参数调用super(…).

Django相关问答推荐

如何从Django';S模型中的方法中检索值?

如何在 gunicorn conf 文件中指定 uvicorn 工作人员

Django获取具有值的相关对象的计数并将其添加到注释中

关于Django中批量保存对象的问题

JSP模板继承

django 管理员登录突然要求 csrf 令牌

Django REST Framework - 将额外参数传递给操作

根据模型属性获取django对象id

如何从 django 自定义中间件类返回 rest_framework.response 对象?

Django SMTPAuthenticationError

如何迭代模板中 SelectField 的选项?

magic有什么问题?

使用 XMLHttpRequest 提示下载文件

创建新内容类型时出错.请确保在try 单独迁移应用程序之前迁移内容类型

如何验证对象是否存在于多线程中

Django ORM 能否以可靠的与后端无关的方式存储无符号 64 位整数(又名 ulong64 或 uint64)?

在 PyPy 下运行 Django 的缺点?

Django 模型方法 - create_or_update

在 Django 单元测试中使用 mock 修补 celery 任务

使用 Django REST 框架从多个模型返回结果