Django ModelForm排除了需要多个到多个字段

时间:2014-12-28 07:47:18

标签: python django django-forms

我有这些模型

class Team(models.Model):

    title=models.CharField(max_length=50)
    picture=models.ImageField(upload_to='documents/%Y/%m/%d',null=True)
    admins = models.ManyToManyField(Profile, related_name="team_admins")
    members = models.ManyToManyField(Profile, related_name="team_members")
    gender=models.CharField(max_length=1, choices=GENDER_CHOICES,default='M')


    created_date = models.DateTimeField(auto_now_add=True)
    modified_date = models.DateTimeField(auto_now=True)

    def __str__(self):             
        return self.title  

class Profile(models.Model):

    user = models.OneToOneField(User, related_name="profile")
    birthdate = models.DateField(null=True, blank=True)
    phone=models.CharField(null=True,blank=True,max_length=15)
    created_date = models.DateTimeField(auto_now_add=True)
    modified_date = models.DateTimeField(auto_now=True)
    def __str__(self):              # __unicode__ on Python 2
        return self.user.username 

用户应能够创建一个新团队。我希望创建团队的用户自动成为团队的管理员。他以后可以将其他用户添加为管理员。所以我在表单和视图中做到了这一点。

class TeamForm(ModelForm):
    class Meta:
        model=Team
        exclude = ['created_date', 'modified_date', 'admins']

def CreateTeam(request):
    user=request.user
    prof=user.profile
    if request.method == 'POST':
        form=TeamForm(request.POST,request.FILES)
        if form.is_valid():
            t = form.save(commit=False)
            t.admins= prof
            # I also tried this
            # t.admins.add(prof)
            t.save()
            form.save_m2m()


    form=TeamForm()
    return render(request, 'create_team.html', {'form' : form}) 

我收到此错误"<Team: X>" needs to have a value for field "team" before this many-to-many relationship can be used.

我该如何解决这个问题?是否有更好的方法可以自动将创建团队的用户添加到管理员?我还需要一个针对多对多字段的Through参数吗?

1 个答案:

答案 0 :(得分:1)

尝试这种方式:

if form.is_valid():
    t = form.save()
    t.admins.add(prof)