向我建议在django中处理下拉列表的最佳方法

时间:2019-12-09 05:21:27

标签: python django forms django-models

我是django的新手,在开发过程中,我处于连锁下拉列表中。我尝试了几种方法,但没有为我工作。初始下拉字段可以是资产类型,并且在选择了下一个字段后即是。类别应根据资产类型填充,子类别和模型名称也应相同,反之亦然。任何人都可以帮助我解决此问题。下面,我分享我的代码供您参考。


models.py代码为

from django.db import models
from django.utils import timezone

# Create your models here.
class asset_type(models.Model):

    asset_type = models.CharField(max_length=252,unique=True)

    def __str__(self):
        return self.asset_type

class category(models.Model):
    asset_type = models.ForeignKey('asset_type', on_delete=models.CASCADE)
    category = models.CharField(max_length=252,unique=True)     

    def __str__(self):
        return self.category

class subcategory(models.Model):
    asset_type = models.ForeignKey('asset_type', on_delete=models.CASCADE)
    category = models.ForeignKey('category',on_delete=models.CASCADE)
    subcategory = models.CharField(max_length=50,unique=True)

    def __str__(self):
        return self.subcategory
class model_details(models.Model):
    asset_type = models.ForeignKey('asset_type', on_delete=models.CASCADE)
    category = models.ForeignKey('category',on_delete=models.CASCADE)     
    subcategory = models.ForeignKey("subcategory", on_delete=models.CASCADE)
    model_name = models.CharField(max_length=50)

    def __str__(self):
        return self.model_name


class stock_in(models.Model):
    id = models.AutoField(primary_key=True)
    #asset_id = models.ForeignKey(asset_master, on_delete=models.CASCADE)
    asset_type = models.CharField(max_length=252)
    category = models.CharField(max_length=252,null=True)
    subcategory = models.CharField(max_length=252)
    manufacturer = models.CharField(max_length=254)
    model_name = models.CharField(max_length=50)
    serial_no = models.CharField(max_length=254)
    invoice_date = models.DateField(default=timezone.now())
    warranty_date= models.DateField(default=timezone.now())
    vendor_name = models.CharField(max_length=254)
    price = models.IntegerField()
    created_on = models.DateTimeField(default=timezone.now())
    status=models.CharField(max_length=254,default='CURRENT')
    #author = models.CharField(max_length=254,blank=True)

    def __str__(self):
        return self.subcategory

forms.py代码是

class stock_inward(forms.ModelForm):
   asset_type = forms.ModelChoiceField(queryset=models.asset_type.objects.none(),empty_label="----SELECT----", widget=forms.Select())
   category = forms.ModelChoiceField(queryset=models.category.objects.none(),empty_label="----SELECT----", widget=forms.Select())
   subcategory = forms.ModelChoiceField(queryset=models.subcategory.objects.none(),empty_label="----SELECT----", widget=forms.Select())
   model_name = forms.ModelChoiceField(queryset=models.model_details.objects.none(),empty_label="----SELECT----", widget=forms.Select())
   #category = forms.ModelChoiceField(queryset=models.category.objects.none(), required=False,empty_label="----SELECT----", widget=forms.Select())
   #print(category)
   #subcategory = forms.ModelChoiceField(queryset=models.subcategory.objects.none(), required=False,empty_label="----SELECT----", widget=forms.Select())
   #model_name = forms.ModelChoiceField(queryset=models.model_details.objects.none(), required=False,empty_label="----SELECT----", widget=forms.Select())
   price = forms.FloatField()
   #subcategory = forms.ModelChoiceField(queryset=models.asset_master.objects.order_by().filter(category='SYSTEM').values_list('subcategory', flat=True).distinct(),empty_label='----SELECT----')
   class Meta:
      model = stock_in
      fields = ('asset_type','category','subcategory','model_name','manufacturer','serial_no','invoice_date','warranty_date','vendor_name','price')      
      widgets = {
         #'asset_type':forms.ModelChoiceField(queryset=models.asset_type.objects.all()),
         #'category': forms.TextInput(attrs={'class':'form_control','id':'id_category'}),
         #'subcategory': forms.TextInput(attrs={'class':'form_control','id':'id_subcategory'}),
         'manufacturer': forms.TextInput(attrs={'class':'form_control','id':'id_manufacturer','placeholder':'Made by..'}),
         #'model_name': forms.TextInput(attrs={'class':'form_control','id':'id_model_name','placeholder':'Ex:SANIAN7'}),
         'serial_no': forms.TextInput(attrs={'class':'form_control','id':'id_serial_no','placeholder':'Enter Serial No..'}),
         'warranty_date': forms.DateInput(attrs={'class':'form_control date','id':'id_warranty_date'}),
         'vendor_name': forms.TextInput(attrs={'class':'form_control','id':'vendor_name','placeholder':'Brought From..'}),
         'price': forms.NumberInput(attrs={'class':'form_control','id':'price','placeholder':'Each Price(Incl. GST)'})
   }
   def __init__(self,*args, **kwargs):
           super(stock_inward,self).__init__(*args, **kwargs)
           self.fields['asset_type'].choices = list(models.asset_type.objects.values_list('asset_type'))

views.py代码为

from django.shortcuts import render,redirect
from stock.forms import stock_inward
from django.http import HttpResponseRedirect,JsonResponse
from django.views.generic import ListView,CreateView,UpdateView
from django.urls import reverse_lazy
from stock import models

# Create your views here.
class StockIn_Form_View(CreateView):
     def get(self,request, *args, **kwargs):
       context = {'form': stock_inward()}
       return render(request, 'stock/stock_in.html', context)
     def post(self,request, *args, **kwargs):
        form = stock_inward()
        if request.method=='POST':
          print('POST ACCEPTED')
          form = stock_inward(request.POST)

          if form.is_valid():

               category = form.cleaned_data.get('asset_type')
               subcategory = form.cleaned_data.get('category')
               model_name = form.cleaned_data.get('model_name')

    #          print('value is '+str(category))
    #          print('validated')
               form.save()
    #          f.save()
               result = 'Success'
    #          #context = result
    #          #success_url = reverse_lazy('/stock_in/')
               return redirect('/stock_in/',result=result)
          else:
              result = 'Invalid Input'
              return HttpResponseRedirect('/stock_in/',{'result':result})

          return render(request,'stock/stock_in.html',{'form':form})

def stock_out(request):
    return render(request,'stock/stock_out.html')
def transfer(request):
    return render(request,'stock/transfer.html')

def index(request):
    return render(request,'stock/index.html')

def load_categories(request):
    asset_id = request.GET.get('asset_type')
    categories = models.categories.objects.filter(asset_type=asset_id).order_by('asset_type')
    return render(request, 'dropdown_list/category_options.html', {'categories': categories})

'''

**models.py code is **

    ```
    from django.db import models
    from django.utils import timezone

    # Create your models here.
    class asset_type(models.Model):

        asset_type = models.CharField(max_length=252,unique=True)

        def __str__(self):
            return self.asset_type

    class category(models.Model):
        asset_type = models.ForeignKey('asset_type', on_delete=models.CASCADE)
        category = models.CharField(max_length=252,unique=True)     

        def __str__(self):
            return self.category

    class subcategory(models.Model):
        asset_type = models.ForeignKey('asset_type', on_delete=models.CASCADE)
        category = models.ForeignKey('category',on_delete=models.CASCADE)
        subcategory = models.CharField(max_length=50,unique=True)

        def __str__(self):
            return self.subcategory
    class model_details(models.Model):
        asset_type = models.ForeignKey('asset_type', on_delete=models.CASCADE)
        category = models.ForeignKey('category',on_delete=models.CASCADE)     
        subcategory = models.ForeignKey("subcategory", on_delete=models.CASCADE)
        model_name = models.CharField(max_length=50)

        def __str__(self):
            return self.model_name


    class stock_in(models.Model):
        id = models.AutoField(primary_key=True)
        #asset_id = models.ForeignKey(asset_master, on_delete=models.CASCADE)
        asset_type = models.CharField(max_length=252)
        category = models.CharField(max_length=252,null=True)
        subcategory = models.CharField(max_length=252)
        manufacturer = models.CharField(max_length=254)
        model_name = models.CharField(max_length=50)
        serial_no = models.CharField(max_length=254)
        invoice_date = models.DateField(default=timezone.now())
        warranty_date= models.DateField(default=timezone.now())
        vendor_name = models.CharField(max_length=254)
        price = models.IntegerField()
        created_on = models.DateTimeField(default=timezone.now())
        status=models.CharField(max_length=254,default='CURRENT')
        #author = models.CharField(max_length=254,blank=True)

        def __str__(self):
            return self.subcategory 

'''

**Let me know if you need more information**

1 个答案:

答案 0 :(得分:0)

它可以与如下所示的Ajax调用一起使用

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script> 
 //category selection
$("#id_asset_type").change(function () {
  console.log('initiated')
  var url = $("#stockinForm").attr("data-categories-url");  // get the url of the `load_cities` view
  var asset_typeId = $(this).val();  // get the selected country ID from the HTML input
  console.log('asset_id'+asset_typeId)
  $.ajax({                       // initialize an AJAX request
    url: url,                    // set the url of the request (= localhost:8000/hr/ajax/load-cities/)
    data: {
      'asset_type': asset_typeId       // add the country id to the GET parameters
    },

    success: function (data) {   // `data` is the return of the `load_cities` view function
      $("#id_category").html(data);  // replace the contents of the city input with the data that came from the server
    }
  });

});

除了上述内容之外,我们还必须定义URL,渲染方法和显示列表的页面。