访问模板中的ModelForm queryset对象字段

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了访问模板中的ModelForm queryset对象字段相关的知识,希望对你有一定的参考价值。

在我的ModelForm中,我将project_users过滤为所有用户的特定集合。如何自定义复选框以显示用户的名字和姓氏?

当前显示其电子邮件地址作为复选框标签。

models.py

class Project(models.Model):
    project_business_profile = models.ForeignKey(BusinessProfile, on_delete=models.CASCADE)
    project_users = models.ManyToManyField(User, related_name='project_users')
    ...

    def __str__(self):
        return str(self.project_name)

views.py

class EditProject(LoginRequiredMixin, View):
    login_url = '/signin'
    redirect_field_name = 'signin'

    def get(self, request, project_id):
        ...
        form = EditProjectForm(instance=project)
        ...

forms.py

class EditProjectForm(ModelForm):
    project_users = forms.ModelMultipleChoiceField(
                    widget = forms.CheckboxSelectMultiple,
                    queryset = User.objects.none()
    )

    class Meta:
        model = Project
        fields = ['project_users']

    def __init__(self, *args, **kwargs):
        super(EditProjectForm, self).__init__(*args, **kwargs)
        current_project = self.instance
        current_business = current_project.project_business_profile
        users = current_business.business_users.all()
        self.fields['project_users'].queryset = current_business.business_users.all() 
        // Spits out the correct users however I need to access other user fields of User in template. Name etc

模板

form.as_p
答案

我不确定我是否完全理解,您是否只想更改显示您的用户的标签?如果是这样的话,可能会起作用:

forms.py

class EditProjectForm(ModelForm):
    project_users = forms.ModelMultipleChoiceField(
                    widget = forms.CheckboxSelectMultiple,
                    queryset = User.objects.none()
    )

    class Meta:
        model = Project
        fields = ['project_users']

    def __init__(self, *args, **kwargs):
        super(EditProjectForm, self).__init__(*args, **kwargs)
        current_project = self.instance
        current_business = current_project.project_business_profile
        users = current_business.business_users.all()
        self.fields['project_users'] = UserChoiceField(queryset=users)
        // Spits out the correct users however I need to access other user fields of User in template. Name etc

class UserChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        user = User.objects.get(id=obj.id)
        return user.get_full_name()

以上是关于访问模板中的ModelForm queryset对象字段的主要内容,如果未能解决你的问题,请参考以下文章

在 django 模板中索引 QuerySet 数组

如何在 Django 的 ModelForm 中使用请求

带有Queryset的Django Form ChoiceField

无法将 ModelForm 中的表单属性传递给模板

在 django 模板中使用聚合 QuerySet 中的字段

使用 Django,如何在模板中动态设置 ModelForm 字段值?