【问题标题】:How to load a dynamic saved dropdown during edit如何在编辑期间加载动态保存的下拉菜单
【发布时间】:2019-01-15 13:46:35
【问题描述】:

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

这是我的model.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

forms.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

这是我的观点.py

def edit_fee(request, pk):
   app = settings.CONFIG
   post = get_object_or_404(SchoolFees, pk=pk)
   if request.method == 'POST':
     form = FeesCreationForm(request.POST, instance=post)
     if form.is_valid():
        form.save()
        messages.add_message(request, messages.WARNING, "Fees record updated successfully")
        return redirect('bursary:create_fee')

   else:
     # bring edit form out
     form = FeesCreationForm(instance=post)
     table = FeesTable(SchoolFees.objects.all())
     RequestConfig(request, paginate={'per_page': 10}).configure(table)
     context = {"form": form, "fees": table, 'app': app}


return render(request, 'editfee.html', context)

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

【问题讨论】:

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


    【解决方案1】:

    通过this post 之后,我在阅读 cmets 时能够解决它。我所需要的只是向我的 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-15
      • 2011-04-19
      • 2018-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-24
      相关资源
      最近更新 更多