如何在编辑过程中加载动态保存的下拉菜单

时间:2019-01-15 13:46:35

标签: ajax python-3.x django-models django-forms django-views

在我的应用程序中,我有一个链接的下拉列表,其中我通过jquery ajax获得了第二个下拉列表,效果很好。所以我试图编辑此保存的数据并将其加载回编辑表单,但是下拉列表是显示为空。这是我到目前为止所做的

这是我的模特。py

$ npm run i18n

forms.py

class SchoolFees(models.Model):
  fid = models.ForeignKey(FacultyData, on_delete= models.SET_NULL, null=True)
  did = models.ForeignKey(DepartmentData, on_delete= models.SET_NULL, null=True)
  sid = models.ForeignKey(SessionData, on_delete= models.SET_NULL, null=True)
  amount = models.CharField(max_length=30)

  def __str__(self):
     return self.amount

这是我的观点。py

class FeesCreationForm(forms.ModelForm):
   fid = forms.ModelChoiceField(queryset=FacultyData.objects.all(), empty_label="--Select Faculty--",
                             widget=forms.Select(attrs={'class': 'form-control'}))

   did = forms.ModelChoiceField(queryset=DepartmentData.objects.all(), empty_label="--Select Faculty First--",
                             widget=forms.Select(attrs={'class': 'form-control'}))

   sid = forms.ModelChoiceField(queryset=SessionData.objects.all(), empty_label="--Select Session--",
                             widget=forms.Select(attrs={'class': 'form-control'}))

   class Meta:
     model = models.SchoolFees
     fields = ['sid', 'fid', 'did', 'amount']

     widgets = {
        'amount': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Amount'})

    }

   def __init__(self, *args, **kwargs):
     super(FeesCreationForm, self).__init__(*args, **kwargs)
     self.fields['did'].queryset = DepartmentData.objects.none()

    # Get did queryset for the selected fid
     if 'fid' in self.data:
        try:
            fd = int(self.data.get('fid'))
            self.fields['did'].queryset =  DepartmentData.objects.filter(fid_id=fd).order_by('id')
        except (ValueError, TypeError):
            pass # invalid input from the client; ignore and use empty queryset

我希望保存的值与已经显示的其他表单字段一起传递给下拉列表

1 个答案:

答案 0 :(得分:0)

经过this post之后,我在阅读评论时能够解决它。我所需要做的只是向我的init函数添加一个向后关系。

class FeesCreationForm(forms.ModelForm):
  fid = forms.ModelChoiceField(queryset=FacultyData.objects.all(), empty_label="--Select Faculty--",
                             widget=forms.Select(attrs={'class': 'form-control'}))

  did = forms.ModelChoiceField(queryset=DepartmentData.objects.all(), empty_label="--Select Faculty First--",
                             widget=forms.Select(attrs={'class': 'form-control'}))

  sid = forms.ModelChoiceField(queryset=SessionData.objects.all(), empty_label="--Select Session--",
                             widget=forms.Select(attrs={'class': 'form-control'}))

  class Meta:
     model = models.SchoolFees
     fields = ['sid', 'fid', 'did', 'amount']

     widgets = {
        'amount': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Amount'})

    }

  def __init__(self, *args, **kwargs):
     super(FeesCreationForm, self).__init__(*args, **kwargs)
     self.fields['did'].queryset = DepartmentData.objects.none()

     # Get did queryset for the selected fid
     if 'fid' in self.data:
        try:
            fd = int(self.data.get('fid'))
            self.fields['did'].queryset =  DepartmentData.objects.filter(fid_id=fd).order_by('id')
        except (ValueError, TypeError):
            pass # invalid input from the client; ignore and use empty queryset
    elif self.instance.pk:
        self.fields['did'].queryset = self.instance.fid.departmentdata_set.order_by('id')
        #backward relation - for this faculty selected, check its deparm
        #every department has its faculty
        # #in other word, which dept has their foreign key pointing to the current instance of faculty