无法将关键字’tag’解析为字段。

huangapple go评论104阅读模式
英文:

Cannot resolve keyword 'tag' into field

问题

我正在按照《Django 2示例》这本书的示例进行操作,当涉及到为博客文章实现标签系统时,我遇到了这个错误:

无法将关键字’tag’解析为字段。

此错误是在我点击这里显示的第一篇文章标签时引发的:

无法将关键字’tag’解析为字段。

以下是models.py的代码:

  1. from django.contrib.auth.models import User
  2. from django.db import models
  3. from django.utils import timezone
  4. from django.urls import reverse
  5. from taggit.managers import TaggableManager
  6. class PublishManager(models.Manager):
  7. def get_queryset(self):
  8. return super(PublishManager, self).get_queryset().filter(status='published')
  9. class Post(models.Model):
  10. STATUS_CHOICES = (
  11. ('draft', 'Draft'),
  12. ('published', 'Published'),
  13. )
  14. title = models.CharField(max_length=250)
  15. slug = models.SlugField(max_length=250, unique_for_date='publish')
  16. author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_post')
  17. body = models.TextField()
  18. publish = models.DateTimeField(default=timezone.now)
  19. created = models.DateTimeField(auto_now_add=True)
  20. updated = models.DateTimeField(auto_now=True)
  21. status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
  22. object = models.Manager() # 默认管理器
  23. published = PublishManager() # 我的自定义管理器
  24. tags = TaggableManager() # 从库'taggit'导入的标签管理器
  25. class Meta:
  26. ordering = ('-publish',)
  27. def __str__(self):
  28. return self.title
  29. def get_absolute_url(self):
  30. return reverse(
  31. 'blog:post_detail',
  32. args=[
  33. self.publish.year,
  34. self.publish.month,
  35. self.publish.day,
  36. self.slug,
  37. ]
  38. )
  39. class Comment(models.Model):
  40. post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
  41. name = models.CharField(max_length=80)
  42. email = models.EmailField()
  43. body = models.TextField()
  44. created = models.DateTimeField(auto_now_add=True)
  45. updated = models.DateTimeField(auto_now=True)
  46. active = models.BooleanField(default=True)
  47. class Meta:
  48. ordering = ('created',)
  49. def __str__(self):
  50. return 'Comment by {} on {}'.format(self.name, self.post)

如果需要其他上传的代码,请告诉我。
希望这是一个容易修复的错误。

谢谢您的任何帮助。

英文:

I am following the book 'Django 2 by example', and when it comes to implementing the tagging system for blog posts I encounter this error:

无法将关键字’tag’解析为字段。

the error is caused when I click on the first-post tag shown here

无法将关键字’tag’解析为字段。

here is models.py

  1. from django.contrib.auth.models import User
  2. from django.db import models
  3. from django.utils import timezone
  4. from django.urls import reverse
  5. from taggit.managers import TaggableManager
  6. class PublishManager(models.Manager):
  7. def get_queryset(self):
  8. return super(PublishManager, self).get_queryset().filter(status='published')
  9. class Post(models.Model):
  10. STATUS_CHOICES = (
  11. ('draft', 'Draft'),
  12. ('published', 'Published'),
  13. )
  14. title = models.CharField(max_length=250)
  15. slug = models.SlugField(max_length=250, unique_for_date='publish')
  16. author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_post')
  17. body = models.TextField()
  18. publish = models.DateTimeField(default=timezone.now)
  19. created = models.DateTimeField(auto_now_add=True)
  20. updated = models.DateTimeField(auto_now=True)
  21. status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
  22. object = models.Manager() # The default manager.
  23. published = PublishManager() # My custom manager
  24. tags = TaggableManager() # Imported from the library 'taggit'
  25. class Meta:
  26. ordering = ('-publish',)
  27. def __str__(self):
  28. return self.title
  29. def get_absolute_url(self):
  30. return reverse(
  31. 'blog:post_detail',
  32. args=[
  33. self.publish.year,
  34. self.publish.month,
  35. self.publish.day,
  36. self.slug,
  37. ]
  38. )
  39. class Comment(models.Model):
  40. post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
  41. name = models.CharField(max_length=80)
  42. email = models.EmailField()
  43. body = models.TextField()
  44. created = models.DateTimeField(auto_now_add=True)
  45. updated = models.DateTimeField(auto_now=True)
  46. active = models.BooleanField(default=True)
  47. class Meta:
  48. ordering = ('created',)
  49. def __str__(self):
  50. return 'Comment by {} on {}'.format(self.name, self.post)

list.html

  1. {% extends 'base.html' %}
  2. {% block content %}
  3. <h1>My Blog</h1>
  4. {% if tag %}
  5. <h2>Posts tagged with "{{ tag.name }}"</h2>
  6. {% endif %}
  7. {% for post in posts %}
  8. <h2>
  9. <a href="{{ post.get_absolute_url }}">
  10. {{ post.title }}
  11. </a>
  12. </h2>
  13. <p class="tags">
  14. Tags:
  15. {% for tag in post.tags.all %}
  16. <a href="{% url 'blog:post_list_by_tag' tag.slug %}">
  17. {{ tag.name }}
  18. </a>
  19. {% if not forloop.last %}, {% endif %}
  20. {% endfor %}
  21. </p>
  22. <p class="date">
  23. Published {{ post.publish }} by {{ post.author }}
  24. </p>
  25. {{ post.body|truncatewords:30|linebreaks }}
  26. {% endfor %}
  27. <!--{% include "pagination.html" with page=page_obj %}-->
  28. <!-- ^^^^^^^^^^^^ if using class-based view page=page_obj ^^^^^^^^^^ -->
  29. {% include "pagination.html" with page=posts %}
  30. <!-- ^^^^^^^^^^^^ if using function-based view page=posts ^^^^^^^^^^ -->
  31. {% endblock %}

and urls.py

  1. from django.urls import path
  2. from . import views
  3. app_name = 'blog'
  4. urlpatterns = [
  5. path('', views.post_list, name='post_list'),
  6. # path('', views.PostListView.as_view(), name='post_list'),
  7. path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name='post_detail'),
  8. path('<int:post_id>/share/', views.post_share, name='post_share'),
  9. path('tag/?<slug:tag_slug>/', views.post_list, name='post_list_by_tag'),
  10. ]

views.py

  1. from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
  2. from django.shortcuts import render, get_object_or_404
  3. from .models import Post
  4. from django.views.generic import ListView
  5. from .forms import EmailPostForm, CommentForm
  6. from django.core.mail import send_mail
  7. from taggit.models import Tag
  8. def post_list(request, tag_slug=None):
  9. object_list = Post.published.all()
  10. tag = None
  11. if tag_slug:
  12. tag = get_object_or_404(Tag, slug=tag_slug)
  13. object_list = object_list.filter(tag__in=[tag])
  14. paginator = Paginator(object_list, 3)
  15. page = request.GET.get('page')
  16. try:
  17. posts = paginator.page(page)
  18. except PageNotAnInteger:
  19. # if page is not an integer deliver the first page
  20. posts = paginator.page(1)
  21. except EmptyPage:
  22. # if page is out of range deliver last page of results
  23. posts = paginator.page(paginator.num_pages)
  24. return render(request, 'blog/post/list.html', {
  25. 'posts': posts,
  26. 'page': page,
  27. 'tag': tag,
  28. })
  29. # ^^^^^^^^^^^^^^^^^^ SAME AS ^^^^^^^^^^^^^^^^^^^^^^^^ #
  30. # class PostListView(ListView):
  31. # queryset = Post.published.all()
  32. # context_object_name = 'posts'
  33. # paginate_by = 3
  34. # template_name = 'blog/post/list.html'
  35. def post_detail(request, year, month, day, post):
  36. post = get_object_or_404(Post,
  37. slug=post,
  38. status='published',
  39. publish__year=year,
  40. publish__month=month,
  41. publish__day=day)
  42. # List of active comments for this post
  43. comments = post.comments.filter(active=True)
  44. new_comment = None
  45. if request.method == 'POST':
  46. # A comment was posted
  47. comment_form = CommentForm(data=request.POST)
  48. if comment_form.is_valid():
  49. # Create Comment objects but don't save to database yet
  50. new_comment = comment_form.save(commit=False)
  51. # Assign the current post to the comment
  52. new_comment.post = post
  53. # Save
  54. new_comment.save()
  55. else:
  56. comment_form = CommentForm()
  57. return render(request, 'blog/post/detail.html', {'post': post,
  58. 'comments': comments,
  59. 'new_comment': new_comment,
  60. 'comment_form': comment_form})
  61. def post_share(request, post_id):
  62. # Retrieve post by id
  63. post = get_object_or_404(Post,
  64. id=post_id,
  65. status='published')
  66. sent = False
  67. if request.method == 'POST':
  68. # Form was submitted
  69. form = EmailPostForm(request.POST)
  70. if form.is_valid():
  71. # Form fields passed validation
  72. cd = form.cleaned_data
  73. post_url = request.build_absolute_uri(post.get_absolute_url())
  74. subject = '{} ({}) recommends you reading "{}"'.format(cd['name'], cd['email'], post.title)
  75. message = 'Read "{}" at {}\n\n{}\'s comments: {}'.format(post.title, post_url, cd['name'], cd['comments'])
  76. send_mail(subject, message, 'admin@mayblog.com', [cd['to']])
  77. sent = True
  78. else:
  79. form = EmailPostForm()
  80. return render(request, 'blog/post/share.html', {'post': post, 'form': form, 'sent': sent})

If you need any other code uploaded let me know about it.
Hopefully, it's some easy-to-fix error.

Thanks for any help.

答案1

得分: 1

post_list视图中,您需要将object_list = object_list.filter(tag__in=[tag])更改为

object_list = object_list.filter(tags__in=[tag])

英文:

At post_list view, you need to change object_list = object_list.filter(tag__in=[tag]) to

  1. object_list = object_list.filter(tags__in=[tag])

huangapple
  • 本文由 发表于 2020年1月4日 01:30:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/59582843.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定