Django:禁止直接分配给相关集的反面。使用username.set()代替

时间:2018-12-16 15:01:06

标签: python django django-models

在Django中迁移数据库时遇到一些麻烦

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "E:\Env\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "E:\Env\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "E:\Env\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv
    self.execute(*args, **cmd_options)
  File "E:\Env\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 350, in execute
    self.check()
  File "E:\Env\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 379, in check
    include_deployment_checks=include_deployment_checks,
  File "E:\Env\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 366, in _run_checks
    return checks.run_checks(**kwargs)
  File "E:\Env\Python\Python37-32\lib\site-packages\django\core\checks\registry.py", line 71, in run_checks
    new_errors = check(app_configs=app_configs)
  File "E:\Env\Python\Python37-32\lib\site-packages\django\contrib\auth\checks.py", line 74, in check_user_model
    if isinstance(cls().is_anonymous, MethodType):
  File "E:\Env\Python\Python37-32\lib\site-packages\django\db\models\base.py", line 470, in __init__
    _setattr(self, field.attname, val)
  File "E:\Env\Python\Python37-32\lib\site-packages\django\db\models\fields\related_descriptors.py", line 537, in __set__
    % self._get_set_deprecation_msg_params(),
TypeError: Direct assignment to the reverse side of a related set is prohibited. Use username.set() instead.

这是我的模型。py:

class PostComments(models.Model):
    post = models.ForeignKey(InfoPost, on_delete=models.CASCADE, related_name='comments')
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="username")
    text = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    #approved_comment = models.BooleanField(default=False)
    reply_to = models.ForeignKey("self", null=True, blank=True, on_delete=models.CASCADE, related_name='replies')

    #def __str__(self): return 'Comment by {} on {}'.format(self.name, self.post)

我正在尝试为我的网站中的帖子创建评论系统,但是发生了一些错误。我不知道我的模型有什么问题,但是如果我尝试在没有新的PostComments模型的情况下进行迁移,那么它的迁移就可以了。

UPD。这是我的代码,我正在使用我的PostComments模型

forms.py
    class CommentsForm(forms.ModelForm):
        post = forms.CharField(required=False)
        author = forms.CharField(required=False)

        class Meta:
            model = PostComments
            fields = '__all__'

views.py

def post(request, slug):
    post = get_object_or_404(InfoPost, slug=slug)
    comment_list = CommentsForm._meta.model.objects.all()

    if request.user.is_authenticated:
        user = User.objects.get(username=request.user.username)

        if request.method == 'POST':
            comment = CommentsForm(request.POST)
            print(comment.is_valid())
            if comment.is_valid():
                com = comment.save(commit=False)
                com.author = request.user
                com.post = post
                com.save()
                return redirect('post', slug=slug)
        else:
            comment_form = CommentsForm()
        return render_to_response('MainPage/Post.html',
                                  {'post': post, "user": user, 'img_w': image_w, 'img_h': image_h,
                                   'comments_list': comment_list, 'comment_form': comment_form})

    return render_to_response('MainPage/Post.html', {'post': post, 'img_w': image_w, 'img_h': image_h, 'comments_list': comment_list})

我当时在想,它是在尝试获取所有注释对象以在视图中显示它们时开始的,但是我真的不知道

2 个答案:

答案 0 :(得分:1)

您正在使用作者ForeignKey上的username来屏蔽User模型上的实际related_name字段。

应该是这样的:

author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="usernames")

' related_name = 用户名 '。

失败的原因是因为您这样做了:

user = User.objects.get(username=request.user.username)

您基本上是在访问与用户相关的注释集的反向关系,而不是实际的username字段(我认为是CharField)。

django documentation中有关related_name的更多信息。

答案 1 :(得分:0)

当模型具有外键时,我不明白您为什么将帖子和作者设置为CharFields。尤其是您要直接在模型中进行设置后。

您应该删除这些定义,然后从表单中完全排除这些字段:

class CommentsForm(forms.ModelForm):

    class Meta:
        model = PostComments
        exclude = ("post", "author")