2017-08-19 176 views
0

必須有更好的方法來編寫此代碼。基本上,我有我的數據庫中的電子郵件列表。我正在努力做出一個整潔的表格,這將有按年份和類型分開的電子郵件複選框。例如Django Multi複選框表單

一年級學生
複選框複選框

二年級的學生: .......

我的模型看起來像這樣

class Email(models.Model): 
    name = models.CharField(max_length = 254) 
    email = models.EmailField(unique = True) 
    year = models.IntegerField(default=0 
    course = models.IntegerField(default=0) 
    type = models.CharField(max_length = 100) 

也是目前唯一途徑我設法通過寫這樣的許多表格

class Emailform1(forms.Form): 
    my_models = forms.ModelMultipleChoiceField(
             widget=forms.CheckboxSelectMultiple, 
             queryset=None) 
    def __init__(self, *args, **kwargs): 
     super(Emailform1, self).__init__(*args, **kwargs) 
     self.fields['my_models'].queryset = Email.objects.filter(course = 1).filter(type="Type") 

但是,這會產生很大的麻煩與視圖和一噸的形式等工作..

回答

0

不要使用有多種形式 - 你可以使用一個帶有多個字段:

def get_courses_types(): 
    results = [] 
    courses = [1, 2, 3] 
    types = ['Type1', 'Type2', 'Type3'] 
    for course in courses: 
     for type in types: 
      results.append((course, type)) 
    return results 

class EmailForm(forms.Form): 
    def __init__(self, *args, **kwargs): 
     super(Emailform, self).__init__(*args, **kwargs) 
     for course, type in get_courses_types(): 
      field = 'field_{}_{}'.format(course, type) 
      self.fields[field] = forms.ModelMultipleChoiceField(
       widget=forms.CheckboxSelectMultiple, 
       queryset=Email.objects.filter(course=course).filter(type=type) 
      ) 

然後:

form = EmailForm(data=request.POST) 
if form.is_valid(): 
    for course, type in get_courses_types(): 
     value = form.cleaned_data['field_{}_{}'.format(course, type)] 
     # save value as you want