1
我正在嘗試創建一個動態字段,因爲我需要在服務模型中爲每個組添加個人消息。Django表單上的動態自動創建字段問題
所以,我必須在我的服務表單上動態創建一些字段。
這是我ServiceForm:
class ServicesForm(forms.ModelForm):
role = forms.ModelChoiceField(queryset=Group.objects.all(), required=False)
def __init__(self, *args, **kwargs):
super(ServicesForm, self).__init__(*args, **kwargs)
try:
for elem in Group.objects.all():
i = elem.pk
service = kwargs['instance']
group = elem
if RoleMessage.objects.filter(service=service, role=group).count() > 0:
default = RoleMessage.objects.get(service=service, role=group).message
else:
default = ""
self.fields[elem.name+'_message'] = forms.CharField(widget=forms.Textarea(attrs={'class': str(i)+'_message'}), initial=default, required=False)
except:
pass
class Meta:
model = Services
fields="__all__"
這是我ServiceAdmin:
class ServicesAdmin(admin.ModelAdmin):
form = ServicesForm
list_display = (
'serviceName',
)
def get_fieldsets(self, request, obj=None):
fieldsets = super(ServicesAdmin, self).get_fieldsets(request, obj)
if obj != None:
limit = len(fieldsets[0][1]['fields']) - 1
index = 0
for elem in Group.objects.all():
i = elem.pk
fieldsets[0][1]['fields'].insert(limit+index, elem.name+'_message')
index += 1
return ((None, {'fields': fieldsets[0][1]['fields'],}),)
這是當我嘗試打開或創建一個服務,我有錯誤:
Unknown field(s) (ServicesManager_message, Administradores_message) specified for Services. Check fields/fieldsets/exclude attributes of class ServicesAdmin.
我model.py是:
class Services(models.Model):
serviceName = models.CharField(
blank=False,
max_length=50
)
class Meta:
db_table = "service"
class RoleMessage(models.Model):
service = models.ForeignKey(Services, blank=False)
role = models.ForeignKey(Group, blank=False)
message = models.CharField(max_length=256, blank=False, default="")