码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-11-13 16:12:45      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:choices   条件   view   通过   error   mes   records   ons   ali   

在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组件中过滤当前用户信息

标签:choices   条件   view   通过   error   mes   records   ons   ali   

原文地址:https://www.cnblogs.com/jiaqi-666/p/9952361.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!