When I create new team and trying to associate it to my User's Profile, I get this error is showing. I wanted a team that lot of members and only one creator(or admin of the team) and that creator is also member of the group. How can I associate team with User's Profile?
Models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
steam_id = models.IntegerField(unique=True, null=True)
steam_name = models.CharField(max_length=255, null=True, unique=True)
profile_pic = models.ImageField(upload_to='profile_images', default='profile_images/default_user.png', blank=True)
rank = models.IntegerField(default=1)
matches = models.IntegerField(default=0)
kda = models.IntegerField(default=0)
team = models.ForeignKey(Team, related_name='players', on_delete=models.CASCADE, null=True)
class Team(models.Model):
creator = models.ForeignKey(User, related_name='teams', on_delete=models.CASCADE)
name = models.CharField(max_length=20, unique=True)
rank = models.IntegerField(default=0)
Views.py
class TeamsCreateView(generic.CreateView):
model = Team
form_class = TeamCreationForm
def form_valid(self, form):
form.instance.creator = self.request.user
self.request.user.profile.team = form.instance
print(form.instance)
print(self.request.user.profile.team)
self.request.user.profile.save()
return super().form_valid(form)
答案 0 :(得分:2)
you get this error because you need to save the Team instance first then save the Profile instance
After form.instance.creator = self.request.user
call form.instance.save()