字段 'id' 需要一个数字但得到了 'natsu' django

Field 'id' expected a number but got 'natsu' django

我想创建一个 user_posts 视图,其中包含与特定用户相关的所有帖子 让我们假设 is/are 用户撰写的博客帖子 'Natsu' 然后登录假设用户 'Testuser' 将能够看到该用户的所有帖子,即用户 'Natsu'.

的所有帖子

blog models.py

class Post(models.Model):
  title = models.CharField(max_length=250)
  slug = models.SlugField(max_length=250, unique_for_date='publish')
  author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
  body = models.TextField()

user models.py

class Profile(models.Model):
  user = models.OneToOneField(User, on_delete=models.CASCADE)
  image = models.ImageField(upload_to='profile_pic', default='default.jpg')

  def __str__(self):
    return f'{ self.user.username } Profile'

views.py

def user_posts(request, username):
  posts = Post.objects.filter(author=username)
  return render(request, 'blog/user_posts.html', {'posts':posts})

user_posts.html

{% for post in posts %}
      <a href="{% url 'user-posts' post.author.username %}" class="mr-2">{{ post.author }}</a>
      <h2><a href="{% url 'post-detail' post.pk %}">{{ post.title }}</a></h2>
      {{ post.body|truncatewords:30 }} 
{% endfor %}

urls.py

  path('user/<str:username>/', views.user_posts, name='user-posts'),

但是当我转到 url 时它显示错误 Field 'id' expected a number but got 'admin'.

完整的追溯在这里:

Internal Server Error: /user/natsu/
Traceback (most recent call last):
  File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 1772, in get_prep_value
    return int(value)
ValueError: invalid literal for int() with base 10: 'natsu'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner     
    response = get_response(request)
  File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response 
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response 
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Sheraram Prajapat\OneDrive\Desktop\Virtual Environment\mysite\blog\views.py", line 78, in user_posts
    posts = Post.published.filter(author=username)
  File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 82, in manager_method  
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 904, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 923, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\query.py", line 1350, in add_q       
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\query.py", line 1377, in _add_q      
    child_clause, needed_inner = self.build_filter(
  File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\query.py", line 1311, in build_filter
    condition = self.build_lookup(lookups, col, value)
  File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\query.py", line 1165, in build_lookup
    lookup = lookup_class(lhs, rhs)
  File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\lookups.py", line 22, in __init__        
    self.rhs = self.get_prep_lookup()
  File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\related_lookups.py", line 115, in 
get_prep_lookup
    self.rhs = target_field.get_prep_value(self.rhs)
  File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 1774, in get_prep_value
    raise e.__class__(
ValueError: Field 'id' expected a number but got 'natsu'.
[29/Jun/2020 17:47:37] "GET /user/natsu/ HTTP/1.1" 500 127097

我哪里做错了?还有其他选择吗?

author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')

由于您对作者字段使用了外键,我认为您无法通过 posts = Post.objects.filter(author=username) 对其进行过滤。你能试试filter(author=user.id)吗?

Post 上的

author 将是 User table 的主键,它是一个整数(除非从默认值修改)而不是 username.你要么需要首先查找 usernameUser,要么使用其他 Django 'magic'。也许尝试其中之一(我认为他们都在后端做同样的事情):

posts = Post.objects.filter(author=User.object.filter(username=username)[:1])

posts = Post.objects.filter(author__username=username)

(我也没有测试...所以请随意编辑此答案或评论,如果两者都不起作用)

  posts = Post.objects.filter(author=User.object.get(username=username))

  posts = Post.objects.filter(author__username=username)