1. 程式人生 > >Django-form元件中過濾當前使用者資訊

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中的條件