0
我有以下型號。django - 動態字段 - 錯誤:選擇一個有效的選項。該選擇不是可用選項之一
class Category(MPTTModel):
name=models.CharField(max_length=75,null=False,blank=False, unique=True)
parent=TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)
class ProductGroup(models.Model):
name = models.CharField(max_length=30,null=False, blank=False)
category=TreeForeignKey('category.Category', null=False,blank=False)
class Product(models.Model):
product_group=models.ForeignKey('productgroup.ProductGroup', null=False,blank=False)
manufacturer=models.ForeignKey(Manufacturer, null=False,blank=False)
product_type=models.CharField(max_length=2, choices=PRODUCT_TYPE,)
opening_stock=models.PositiveIntegerField(default=0)
這是我的觀點和形式。在product_form.html
class CreateProduct(CreateView):
model=Product
form_class=ProductForm
class ProductForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
user = kwargs.pop('user','')
super(ProductForm, self).__init__(*args, **kwargs)
self.fields['category']=TreeNodeChoiceField(queryset=Category.objects.all())
self.fields['category'].required = False
self.fields['product_group']=forms.ModelChoiceField(queryset=ProductGroup.objects.none())
original_fields = self.fields
new_order = OrderedDict()
for key in ['category','product_group', 'manufacturer', 'product_type', 'wheel_position', 'opening_stock']:
new_order[key] = original_fields[key]
self.fields = new_order
class Meta:
model = Product
fields=['product_group', 'manufacturer', 'product_type', 'wheel_position', 'opening_stock']
GetProductGroups阿賈克斯查看
def GetProductGroups(request):
product_groups=ProductGroup.objects.filter(category__id=request.GET.get('id'))
to_json = []
for pg in product_groups:
# for each object, construct a dictionary containing the data you wish to return
mydict = {}
mydict['id'] = pg.id
mydict['name'] = pg.name
to_json.append(mydict)
response_data = json.dumps(to_json)
return HttpResponse(response_data, content_type="application/json")
jQuery的AJAX查詢
<script>
$("#id_category").change(function() {
var category = $(this).val();
$.ajax({
method:'get',
url: '/ajax/get_product_groups/',
data: {
'id': category
},
dataType: 'json',
success: function (data) {
$('#id_product_group').empty()
$('#id_product_group').append(
$('<option></option>').val(0).html('------------')
);
$.each(data, function(key, value){
$('#id_product_group').append(
$('<option></option>').val(value.id).html(value.name)
);
});
}
});
});
</script>
新的url-pattern
url(r'ajax/get_product_groups/', GetProductGroups, name='ajax_get_product_groups'),
jquery腳本完美獲取類別選擇上的數據,然而當按下提交按鈕時我得到以下驗證錯誤 - 跨產品組提交。
選擇一個有效的選項。該選擇不是可用的 選項之一。
..並且相應的下拉列表也被清空。
任何人都可以告訴我我的代碼有什麼問題嗎?
謝謝。
screenshot of the form after submit