简体   繁体   中英

Django ModelForm exclude required many to many field

I have these models

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 

The User shall be able to create a new Team. I want the user who created the team to be an admin of the team automatically. He can later add other users as admins. So I did this in my form and view.

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}) 

I get this error "<Team: X>" needs to have a value for field "team" before this many-to-many relationship can be used.

How do I fix this? Is there a better way for automatically adding the user who created the team to the admins? and also do I need a Through parameter for the many to many fields?

Try in this way:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM