【发布时间】:2021-01-22 12:22:06
【问题描述】:
在 Models.py 中
class Post(models.Model):
user = models.CharField(max_length=100)
likes = models.IntegerField(default=0)
content = models.TextField()
date = models.DateTimeField(auto_now_add=True)
class Profile(models.Model):
following = models.ForeignKey('User',on_delete=models.CASCADE,related_name='following')
user = models.ForeignKey('User',on_delete=models.CASCADE,related_name='user')
def __str__(self):
return self.user
在views.py中
def viewProfile(request,username):
posts = Post.objects.filter(user=username).order_by('id').reverse()
profile = Profile.objects.filter(user=username)
no_of_followers = profile.following.count()
return render(request, "network/profile.html",{
"posts":posts,
"username":username,
"no_of_followers":no_of_followers
})
在 profile.html 中
{% extends "network/layout.html" %}
{% block body %}
<h2 style="margin-left: 20px;">Posts of {{username}}</h2>
<div class="col-sm-6">
<div class="card">
<div class="card-body">
<h5 class="card-title">Profile Details</h5>
<p class="card-text">Followers:{{no_of_followers}}</p>
<p class="card-text">Followings:0</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
</div>
{% for post in posts %}
<div class="card" style="width:70%;margin-left: 10%;margin-right: 20%;">
<div class="card-body">
<a href="{% url 'viewprofile' post.user %}"><h5 class="card-title">{{post.user}}</h5></a>
<div class="form-group">
<p>{{post.date}}<br>{{post.content}}</p>
</div>
<p>{{post.likes}}</p>
</div>
</div>
{% endfor %}
{% endblock %}
遇到字段“id”期望一个数字但得到“xyz”的错误。xyz 是用户名
如果我将 profile = Profile.objects.filter(user=username) 替换为 profile = Profile.objects.filter(user__user=username),则会收到错误 django.core.exceptions.FieldError: Related Field got invalid lookup: user
【问题讨论】:
标签: python html django django-models