Django-form组件中过滤当前用户信息

Posted jiaqi-666

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django-form组件中过滤当前用户信息相关的知识,希望对你有一定的参考价值。

在model中通过limit_choices_to过滤

limit_choices_to={
"pk": 3})

过滤出主键为3的用户,但是这样的问题是不能动弹的过滤出实时登录的用户,因此

在form中过滤

class ConsultRecord(models.Model):
    """
    跟进记录表
    """
    customer = models.ForeignKey(
        ‘Customer‘,
        verbose_name="所咨询客户",
        on_delete=models.CASCADE)
    note = models.TextField(verbose_name="跟进内容...")
    status = models.CharField(
        "跟进状态",
        max_length=8,
        choices=seek_status_choices,
        help_text="选择客户此时的状态")
    consultant = models.ForeignKey(
        "UserInfo",
        verbose_name="跟进人",
        related_name=‘records‘,
        on_delete=models.CASCADE)
    date = models.DateTimeField("跟进日期", auto_now_add=True)
    delete_status = models.BooleanField(verbose_name=‘删除状态‘, default=False)

    def __str__(self):
        return str(self.customer) + str(self.consultant)

form

class ConsultRecordModelForm(forms.ModelForm):
    class Meta:
        model = ConsultRecord
        exclude = ["delete_status"]
        error_messages = {
            ‘customer‘: {‘required‘: ‘客户名不能为空‘},
            ‘note‘: {‘required‘: ‘内容不能为空‘},
            ‘status‘: {‘required‘: ‘内容不能为空‘},
            ‘consultant‘: {‘required‘: ‘内容不能为空‘},
        }

    def __init__(self, request, edit_record, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 根据所实例的编辑记录所属客户id进行过滤
        if edit_record:
            self.fields[‘customer‘].queryset = Customer.objects.filter(pk=edit_record)
            self.fields[‘consultant‘].queryset = UserInfo.objects.filter(pk=request.user.id)
        else:
            self.fields[‘customer‘].queryset = Customer.objects.filter(consultant=request.user.id)
            self.fields[‘consultant‘].queryset = UserInfo.objects.filter(pk=request.user.id)
        for field in self.fields.values():
            field.widget.attrs.update({‘class‘: ‘form-control‘})

实例化时传入当前用户的主键

class AddEditConsultRecords(View):

    # edit_id为空则是添加,不为空则为编辑
    def get(self, request, edit_id_record=None):
        edit_obj = ConsultRecord.objects.filter(pk=edit_id_record).first()
        edit_record = edit_obj.customer.pk  # 当前编辑的记录所属客户的id
        form = ConsultRecordModelForm(request, edit_record, instance=edit_obj)  # 实例化转给form
        return render(request, ‘consultrecord_add_edit.html‘, {‘form‘: form, "edit_obj": edit_obj})

    def post(self, request, edit_id_record=None):
        edit_obj = ConsultRecord.objects.filter(pk=edit_id_record).first()
        edit_record = edit_obj.customer.pk  # 当前编辑的记录所属客户的id
        form = ConsultRecordModelForm(request, edit_record, request.POST, instance=edit_obj)  # 实例化转给form
        if form.is_valid():
            form.save()
            return redirect(request.GET.get("next"))
        else:
            return render(request, ‘consultrecord_add_edit.html‘, {‘form‘: form, "edit_obj": edit_obj})
self.fields[‘A‘].queryset = B.objects.filter(条件)

A为B表中字段,filter中的条件

 

以上是关于Django-form组件中过滤当前用户信息的主要内容,如果未能解决你的问题,请参考以下文章

Python学习-django-Form组件

python3-开发进阶Django-form组件中model form组件

django-form组件

Django-form组件补充

Django-Form组件之字段

Django-Form