1. 程式人生 > >django淺談 過濾欄位內容

django淺談 過濾欄位內容

views.py

class ConsultRecordModelForm(forms.ModelForm):


class Meta:
model = ConsultRecord
# fields = "__all__"

exclude=['delete_status']



def __init__(self,request, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['consultant'].queryset=UserInfo.objects.filter(pk=request.user.pk)

print(request.user)

# self.fields['customer'].queryset=Customer.objects.filter(consultant__pk=request.user.pk)
self.fields['customer'].queryset=Customer.objects.filter(consultant=request.user) #正想查詢按欄位,反向查詢按表名,filter裡面也可以比較物件的,表名和對應物件,欄位和對應物件
for filed in self.fields.values():
filed.widget.attrs.update({'class': 'form-control'})


class AddEditConsultRecordView(View):
def get(self, request, id=None):
obj = ConsultRecord.objects.filter(pk=id).first()
form = ConsultRecordModelForm(request,instance=obj)
return render(request, 'edit_add_record.html', {'form': form, 'obj': obj})

def post(self, request, id=None):
obj = ConsultRecord.objects.filter(pk=id).first()
if reverse('add_consult_records')==request.path:
print(22222)
form = ConsultRecordModelForm(request.POST, instance=obj)

if form.is_valid():
form.save()
return redirect(reverse("customers_record"))
else:
return render(request, "edit_add_record.html", {"form": form, "obj": obj})
else:
# 刪除 ajax
obj.delete()
res={'state':'刪除成功'}
return JsonResponse(res)



class EnrollViewModelForm(forms.ModelForm):
class Meta:
model=Enrollment
# fields="__all__"
exclude=['delete_status']

def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
for field in self.fields.values():
field.widget.attrs.update({'class':"form-control"})