2012-07-16 48 views
0

我想在MultipleChoiceField中加载一个MultipletoField,并将其保存为具有多对多关系的初始数据字段。加载ManytoMany字段中的MultipleChoiceField值

我的班

class Course(models.Model): 
    name = models.CharField(max_length=30) 
    description = models.TextField(max_length=30) 
    owner = models.ForeignKey(User) 

class UserProfile(models.Model): 
    user = models.OneToOneField(User, unique=True) 
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='student') 
    courses_list = models.ManyToManyField(Course, blank=True) 

我的形式

class AddSubscibeForm(forms.ModelForm): 
    userprofile_set = forms.ModelMultipleChoiceField(initial = User.objects) 
    class Meta: 
     model = Course 

我的观点

def addstudents(request, Course_id): 
    editedcourse = Course.objects.get(id=Course_id) # (The ID is in URL) 
    form = AddSubscibeForm(instance=editedcourse) 
    return render(request, 'addstudents.html', locals()) 

其实,我有一个multiplecho icelist与用户,但我没有说在他们的“courses_list”字段过程的用户列表..

我可以通过访问用户的cours_list:

> editedcourse = Course.objects.get(id=Course_id) 
> subscribed = editedcourse.userprofile_set.all() 
> subscribed.user.username 

如果你有一个想法.. :)

回答

1

确认你在问什么。您希望能够看到带有课程的表格,并选择哪些用户在课程中拥有该课程?

您将无法正确使用模型中不存在的ModelForm中的字段。

你可以做的是改变模型,并有指向两个通道中的ManyToManyField,然后使用以下命令:

class AddSubscibeForm(forms.ModelForm): 
    class Meta: 
     model = Course 
     fields = ('userProfiles') 

这样的工作假设你有一个Courses叫ManyToManyField userProfiles

要让ManyToManyField以双向方式工作,请看this ticket

我没有试过这个,但我认为它应该工作。

class Test1(models.Model): 
    tests2 = models.ManyToManyField('Test2', blank=True) 

class Test2(models.Model): 
    tests1 = models.ManyToManyField(Test1, through=Test1.tests2.through, blank=True) 

或本:

class User(models.Model): 
    groups = models.ManyToManyField('Group', through='UserGroups') 

class Group(models.Model): 
    users = models.ManyToManyField('User', through='UserGroups') 

class UserGroups(models.Model): 
    user = models.ForeignKey(User) 
    group = models.ForeignKey(Group) 

    class Meta: 
     db_table = 'app_user_groups' 
     auto_created = User 

上述两者应该工作。在这两种情况下,你都不应该改变数据库中的任何东西。

+0

它运作良好,官方文件告诉我们不会这样做,但它是可以的。如果您有其他想法(与文档^^一致) https://docs.djangoproject.com/en/1.4/topics/db/examples/many_to_many/ – nlassaux 2012-07-16 21:57:19

相关问题