有点神奇:今天我被唤醒了,为我的笔记本电脑供电并开始为我的项目工作,但...... 当我按下按钮时,django回复给我404错误,并说“不匹配查询”。我有点难过,因为昨天所有工作都一如既往。
这是我的大观点:
def p(request, pk):
user = request.user
topic = get_object_or_404(Topic, pk=pk)
post = get_object_or_404(Post, pk=pk)
comment = Comments.objects.filter(pk=pk)
who_come = WhoComeOnEvent.objects.filter(which_event=topic.id)
if request.is_ajax() and request.POST.get('action') == 'joinEvent':
who_come_obj = WhoComeOnEvent.objects.create(
visiter=user,
which_event=post.topic
)
visitors_usernames = []
for w in who_come:
visitors_usernames.append(w.visiter.username)
return HttpResponse(json.dumps(visitors_usernames))
if request.method == 'POST':
form = CustomCommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.creator = user
comment = Comments.objects.create(
body=form.cleaned_data.get('body'),
creator=user,
post=post
)
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
else:
form = CustomCommentForm()
return render(request, 'post.html', {'post': post, 'topic': topic, 'comment': comment,
'form': form, 'who_come': who_come})
post = get_object_or_404(Post, pk=pk)
中的问题,此代码工作了一个月,但现在显示404错误。我不知道是什么原因。它为什么坏了?
我尝试将post = get_object_or_404(Post, pk=pk)
更改为Post.objects.filter(topic=topic.id)
,现在看起来很好,更改后我可以按下按钮并按网址前进。但是,如果我想发表评论,则会在Cannot assign "<QuerySet [<Post: sfdfhgf>]>": "Comments.post" must be a "Post" instance.
行上向我comment.post = post
返回错误。在这里,我陷入困境。
在数据库中都存在。
这是我的模特
class Topic(models.Model):
subject = models.CharField(max_length=255)
last_updated = models.DateTimeField(auto_now_add=True)
board = models.ForeignKey(Board, related_name='topics')
starter = models.ForeignKey(User, related_name='topics')
image = models.ImageField(upload_to='media', null=True)
def __str__(self):
return self.subject
class Post(models.Model):
message = models.TextField(max_length=4000)
topic = models.ForeignKey(Topic, related_name='posts')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(null=True)
created_by = models.ForeignKey(User, related_name='posts')
updated_by = models.ForeignKey(User, null=True, related_name='+')
def __str__(self):
return self.topic.subject
class Comments(models.Model):
creator = models.ForeignKey(User, related_name='comment')
body = models.TextField(max_length=4000)
post = models.ForeignKey(Post, related_name='comment')
created_at = models.DateTimeField(default=now)
def __str__(self):
return '%s comment on %s' % (self.body, self.post.topic.subject)
不知道为什么会破碎:(
看起来很奇怪,但解决方案是在数据库中。我删除了使用过的数据库,创建了新数据库,所有工作都必须如此。知道数据库出了什么问题吗?