我想在添加薪水的同时根据雇员保存的银行详细信息显示其银行帐号。但是现在我正在获取所有员工的银行帐号,而不仅仅是选择一个。下面是我的forms.py
我试图在Forms.py中设置该字段,但是我不知道如何在其中使用员工ID进行过滤。
class SalaryCreateForm(forms.ModelForm):
class Meta:
model = Salary_Rotation
fields = ('Sal_Emp_Desig', 'Payment_Mode_of_Salary', 'Emp_Acc_number', 'Cheque_Number', 'Transaction_Number', 'P_Tax', 'Salary_Amount', 'Salary_Date')
def __init__(self, *args, **kwargs):
super(SalaryCreateForm,self).__init__(*args, **kwargs)
self.fields['Sal_Emp_Desig'].queryset = Designation.objects.filter(Is_Del=0)
self.fields['Emp_Acc_number'].queryset = Employee_Bank_Detail.objects.filter(Is_Del=0)
下面是我的模板
<form class="form-group" method="POST">
{% csrf_token %}
<label class="control-label"> Employee Name:- </label>
<input class="form-control" value="{{emp.Emp_Name}}" type="text" name="compnay" readonly/ >
<label class="control-label"> Company Name:- </label>
<input class="form-control" value="{{emp.Emp_company}}" type="text" name="compnay" readonly/ >
<label>Bank Account</label>
<select id="id_Emp_Acc_number" name="Emp_Acc_number" class="form-control" >
<option value="" selected="">---------</option>
{% for acc_num in bank_acc_numbers %}
<option value="{{acc_num.id}}" >{{ acc_num.Emp_Acc_num }}</option>
{% endfor %}
</select>
{%endfor%}
{{ form|crispy }}
<button class="btn btn-rounded btn-success" type="submit">Add Experience</button>
{% for emp in employees%}
<a href="{% url 'employee-detail' emp.id %}" class="btn btn-rounded btn-brand ml-4">Cancel</a>
{%endfor%}
</form>
下面是我的view.py
class SalaryCraeteView(LoginRequiredMixin,SuccessMessageMixin,CreateView):
#permission_required = 'Company.add_company'
model=Salary_Rotation
success_message = " Salary added successfully!"
reverse_lazy('employee-detail')
login_url= "login"
template_name = 'employee_salary_form.html'
form_class = SalaryCreateForm
def form_valid(self,form,**kwargs):
form.instance.Sal_Crt_By = self.request.user
form.instance.Is_Del =0
def get_context_data(self, **kwargs):
kwargs['employees'] = Employee.objects.filter(pk=self.kwargs['pk'])
kwargs['bank_acc_numbers'] = Employee_Bank_Detail.objects.filter(Emp_Bank_id=self.kwargs['pk']).filter(Is_Del=0)
return super(SalaryCraeteView, self).get_context_data(**kwargs)
我想根据员工的银行业务详细信息而不是所有员工的银行业务详细信息显示下拉列表中的值。
答案 0 :(得分:1)
您可以使用get_form_kwargs()方法将视图中的used_id发送到表单,例如
class SalaryCreateView(...):
...
def get_form_kwargs(self):
kwargs = super(SalaryCreateView, self).get_form_kwargs()
kwargs['user_id'] = self.request.user.pk
return kwargs
并在过滤器中应用此user_id,例如
class SalaryCreateForm(forms.ModelForm):
...
def __init__(self, *args, **kwargs):
self.user_id=kwargs.pop('user_id')
self.fields['Emp_Acc_number'].queryset = Employee_Bank_Detail.objects.filter(Is_Del=0, <user_id_field>=self.user_id)