2015-11-05 90 views
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="") 

回答

1

我已經解決了這個問題。有些東西在Django 1.8中改變,實現從1.5開始。

這裏我回答我的更改以解決問題。

在我ServiceAdmin也發生了變化:

fieldsets = (
    (None, { 
     'fields': (
      'serviceName', 
     ), 
    }), 
) 

def get_form(self, request, obj=None, **kwargs): 
    kwargs['fields'] = flatten_fieldsets(self.declared_fieldsets) 
    return super(ServicesAdmin, self).get_form(request, obj, **kwargs) 

def get_fieldsets(self, request, obj=None): 
    fieldsets = super(ServicesAdmin, self).get_fieldsets(request, obj) 
    newfieldsets = list(fieldsets) 
    fields = ['role'] 
    if obj != None: 
     for elem in Group.objects.all(): 
      fields.append(elem.name+'_message') 
     newfieldsets.append(['Custom Message', {'fields': fields}]) 
    return newfieldsets