0

請您一直試圖在表格中顯示錶格,但我一直無法做到。 請克隆和創建數據庫並在github上運行項目。 代碼太多,無法粘貼到此處。如何將模型加載到multipleChoiceField

github上:https://github.com/mattisbmx/django-multipleChoiceField

型號:

from django.db import models 
from multiselect.fields import ManyToManyField 

class Choice(models.Model): 
    choice = models.CharField(max_length=15) 

    def __unicode__(self): 
     return self.choice 

class SampleModel(models.Model): 
    name = models.CharField(max_length=15) 
    funciones = ManyToManyField(Choice) 
    passwd = models.TextField() 
    def __unicode__(self): 
     return unicode(self.pk) 

查看:

def index(request): 
    data = {'form': forms.SelectForm()} 

    return render_to_response("multiselect/index.html", data, 
          context_instance=RequestContext(request 

形式:

class SelectForm(forms.Form): 
    data = (('1', 'One'), ('2', 'Two'), ('3', 'Three'), ('4', 'Four')) #<--I think here I load the data model 
    choices = MultipleChoiceField(choices=data) 

感謝

+0

['ModelMultipleChoiceField'](https://docs.djangoproject.com/en/1.5/ref/forms/fields/#modelmultiplechoicefield)有幫助嗎? – okm

回答

2

您可以使用ModelMultipleChoiceField

class SelectForm(forms.Form): 
    choices = forms.ModelMultipleChoiceField(queryset=Choice.objects.all()) #Replace the queryset with the queryset of your choice. 

如果要更改默認的小部件

您可以使用widget=CheckboxSelectMultiple()或任何你想。

+0

非常感謝karthikr! 來自智利 –