Django:如何做到使我可以对任何博客帖子(而不只是1个博客帖子)提交兴趣?目前,现在,当我向博客文章提交兴趣后,就无法再对任何其他博客文章提交兴趣。我将收到此消息,内容为“您已经对此文章提出了自己的兴趣”。即使我没有。
从我的模型的性质来看。我是否可以过滤兴趣模型中的“用户”字段,以便只检查该特定博客文章中的特定用户是否已经提交了兴趣?
因为我现在知道,他们正在基于所有博客文章对其进行过滤,只要我已经提交了1,它肯定存在。如果有帮助的话,也请告诉我您是否需要我的forms.py,urls.py。
views.py
def submit_interest_view(request, slug):
form = SubmitInterestForm()
user = request.user
blog_post = get_object_or_404(BlogPost, slug=slug)
num_blogpost = BlogPost.objects.filter(author=user).count()
if blog_post.author.email == user.email:
return HttpResponse('You cannot submit interest to your own post.')
if Interest.objects.filter(user=request.user).exists() and request.method=="POST":
return HttpResponse('You have already submitted your interest to this post.')
if request.method == 'POST':
form = SubmitInterestForm(request.POST, request.FILES)
if form.is_valid():
obj = form.save(commit=False)
obj.user = user
obj.blog_post = blog_post
obj.save()
InterestInvite.objects.create(interest=obj)
messages.success(request, 'Your interests have been submitted', extra_tags='submittedinterest')
return redirect(reverse('HomeFeed:main'))
else:
messages.warning(request, 'Something went wrong. Please try again..', extra_tags='wronginterest')
return render(request, "HomeFeed/submitinterest.html", {'form': form,'user': user, 'num_blogpost': num_blogpost, 'blog_post': blog_post})
else:
form = SubmitInterestForm()
return render(request, "HomeFeed/submitinterest.html", {'form': form,'user': user, 'num_blogpost': num_blogpost, 'blog_post': blog_post})
models.py
class Interest(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(blank=False, null=False, default=True)
my_thoughts = models.TextField(max_length=5000, null=False, blank=False)
blog_post = models.ForeignKey(BlogPost, on_delete=models.CASCADE)
class BlogPost(models.Model):
chief_title = models.CharField(max_length=50, null=False, blank=False, unique=True)
body = models.TextField(max_length=5000, null=False, blank=False)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
slug = models.SlugField(blank=True, unique=True)