得到“<Team:jaja>”的错误需要有一个字段“id”的值才能使用这种多对多关系

Posted

技术标签:

【中文标题】得到“<Team:jaja>”的错误需要有一个字段“id”的值才能使用这种多对多关系【英文标题】:Getting an error of "<Team: jaja>" needs to have a value for field "id" before this many-to-many relationship can be used 【发布时间】:2022-01-16 07:42:15 【问题描述】:

我正在尝试将团队添加到数据库中,但出现此错误。看了类似的问题,但没有一个能解决我的问题。 (我是 Django 新手)

我的代码如下:

forms.py

from django.forms import ModelForm
from .models import Team


class TeamForm(ModelForm):


    class Meta:
        model = Team
        fields = ['title', 'team_country', 'team_logo']

    def __init__(self, *args, **kwargs):
        super(TeamForm, self).__init__(*args, **kwargs)

        for name, field in self.fields.items():
            field.widget.attrs.update('class': 'input')

models.py

from django.db import models

# Create your models here.
from django.contrib.auth.models import User
from django_countries.fields import CountryField
from .validators import validate_file_size


class Team(models.Model):
    #
    # Status

    ACTIVE = 'active'
    DELETED = 'deleted'

    CHOICES_STATUS = (
        (ACTIVE, 'Active'),
        (DELETED, 'Deleted')
    )    

    #
    # Fields

    title = models.CharField(max_length=255)
    team_country = CountryField(blank=True, null=True)    
    team_logo = models.ImageField(
        null=True, blank=True, upload_to='logos/', default="logos/logo.png",
        validators=[validate_file_size])
    members = models.ManyToManyField(User, related_name='teams')
    created_by = models.ForeignKey(User, related_name='created_teams', on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    status = models.CharField(max_length=10, choices=CHOICES_STATUS, default=ACTIVE)

    class Meta:
        ordering = ['title']
    
    def __str__(self):
        return self.title

views.py

from django.shortcuts import render
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect, get_object_or_404


from .models import Team

@login_required
def add(request):
    profile = request.user.profile
    form = TeamForm()
    if request.method == 'POST':
        form = TeamForm(request.POST, request.FILES)

        if form.is_valid():
            team = form.save(commit=False)
            team.created_by = request.user
            team.members.add(request.user)
            team.save()

            
            profile.active_team_id = team.id
            profile.save()

            return redirect('account')

    context = 'form': form
    return render(request, 'team/add.html', context)

当我尝试不使用表单时,例如只有标题字段:

@login_required
def add(request):
    if request.method == 'POST':
        title = request.POST.get('title')

        if title:
            team = Team.objects.create(title=title, created_by=request.user)
            team.members.add(request.user)
            team.save()

            userprofile = request.user.profile
            userprofile.active_team_id = team.id
            userprofile.save()

            return redirect('account')
    
    return render(request, 'team/add.html')

添加成功。我在这里做错了什么?

【问题讨论】:

【参考方案1】:

您无法将成员添加到尚不存在的组中,因此您需要在创建组后添加用户,例如:

 if form.is_valid():
        team = form.save(commit=False)
        team.created_by = request.user
        team.members.add(request.user)
        team.save()

现在:

 if form.is_valid():
        team = form.save(commit=False)
        team.created_by = request.user
        team.save()
        team.members.add(request.user) # you can only add member after the group has been created

在第二个 sn-p 中相同:

team = Team.objects.create(title=title, created_by=request.user)
        team.save()
        team.members.add(request.user)

【讨论】:

这正是问题所在。谢谢!!但是第二个 sn-p 工作,即使它不是按那个顺序。为什么?

以上是关于得到“<Team:jaja>”的错误需要有一个字段“id”的值才能使用这种多对多关系的主要内容,如果未能解决你的问题,请参考以下文章

ValueError:所需数组的深度太小,

当这些变量被删除时,如何停止获取所需导出变量的 Apollo GraphQL 查询

使用 MPMoviePlayerViewController 的时髦错误

为何在JS里encodeURI("中文"),在controller里不需解码直接得到中文?

SubSelectionRequired 类型的验证错误:字段时间戳类型需要子选择

所需参数缺失错误(PUT 请求)