我几乎使用下面的代码(我稍微划了一下),我使用自动完成灯加载用户,用户可以插入不同的人名(用户)用逗号分隔。问题是当我尝试保存时出现以下错误
ValueError at /write/
"<Article: test1>" needs to have a value for field "article" before this many-to-many relationship can be used.
models.py
class Article(models.Model):
author = models.ForeignKey(User,)
people = models.ManyToManyField(User, related_name="with", null=True,)
content = models.TextField()
forms.py
class ArticleForm(forms.ModelForm):
people = forms.CharField(widget=autocomplete_light.TextWidget('UserAutocomplete'))
class Meta:
model = Article
views.py
def write(request):
if request.POST:
form = ArticleForm(request.POST)
if form.is_valid():
content = form.cleaned_data['content']
user = User.objects.get(username=request.user.username)
people_str = form.cleaned_data['accompanied']
people = [x.strip() for x in accompanied_str.split(',')]
article = Article(
content = content,
author = user,
)
for username in accompanied:
user = User.objects.get(username=username)
article.people.add(user)
article.save()
return HttpResponseRedirect('/success/')
答案 0 :(得分:2)
为了创建关系,您需要双方的ID。新创建的文章还没有id。如果您首先保存文章然后添加人员,它应该可以正常工作。
article = Article(
content = content,
author = user,
)
article.save()
article.add(*User.objects.filter(username__in=accompanied))
添加人员的过程可以通过让所有拥有用户名的用户在一次提取中附带来更便宜。