我有以下代码来实现级联选择框(因为字段contract_mod是OneToOneField我不能使用django-smart-choices或django-ajax-select)。
当我创建一个包含我想要显示的字段的字段集时,我必须放置contracts_from_selected以便在管理界面中查看结果(因为在应用代码后contract_mod仍然处于禁用状态。)。
fieldsets = [
[ None,
{
"fields" : [
("contracts_from_selected")
]
}
]
所以我想我应该将contract_from_selected的值复制到另一个字段,以便在fieldset中使用。
有什么建议吗?
模型
class Person(models.Model):
name = models.CharField(max_length=20)
def __unicode__(self):
return self.name
def get_name(self):
return self.name
class Contract(models.Model):
person = models.ForeignKey(Person) #person hired
contract_mod = models.OneToOneField('self', blank = True, null = True)
contract_name = models.CharField(max_length=20) #just for testing
def __unicode__(self):
return self.get_name() + " " +self.contract_name
def get_name(self):
return self.person.get_name() #to make sure you get the person name in the admin
def contract_mod_name(self):
if self.contract_mod:
return self.contract_mod.contract_name
else:
return ""
管理
class SelectField(forms.ChoiceField):
def clean(self, value):
return value
class ContractForm(forms.ModelForm):
contracts_from_selected = SelectField()
class Meta:
model = Contract
widgets = { 'contract_mod' : forms.widgets.Select(attrs={'hidden' : 'true'}) }
class ContractAdmin(admin.ModelAdmin):
form = CForm
list_display = ('contract_name','get_name','contract_mod_name')#what you like
def save_model(self, request, obj, form, change):
if request.POST.get('contracts_from_selected'):
obj.contract_mod=Contract.objects.get(id=int(request.POST.get('contracts_from_selected')))
obj.save()
change_form
$(function () {
$("#id_person").change(function () {
var options = $("#id_contract_mod option").filter(function () {
return $(this).html().split(" ")[0] === $("#id_person option:selected").html();
}).clone();
$("#id_contracts_from_selected").empty();
$("#id_contracts_from_selected").append(options);
});
});