Django:如何实现用户配置文件?

2024-04-19 00:25:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个Twitter克隆并尝试加载个人资料页面。我的逻辑是从简单开始,找到与某个作者匹配的所有tweet,并将这些tweet作为用户的个人资料加载到页面上。我真的不知道从哪里开始。你知道吗

你知道吗网址.py你知道吗

url(r'^users/(?P<username>\w+)/$', views.UserProfileView.as_view(), name='user-profile'),

你知道吗型号.py你知道吗

class Howl(models.Model):
    author = models.ForeignKey(User, null=True)
    content = models.CharField(max_length=150)

你知道吗视图.py你知道吗

class UserProfileView(DetailView):
    """
    A page that loads howls from a specific author based on input
    """
    model = get_user_model()
    context_object_name = 'user_object'
    template_name = 'howl/user-profile.html'

用户-配置文件.html你知道吗

{% block content %}
<h1>{{user_object.author}}</h1>
{% endblock %}

我现在得到一个错误,它说“Generic detail view UserProfileView必须用object pk或slug调用”localhost:8000/用户/你知道吗

我也试了试

Howl.objects.filter(author="admin")

但是我得到了

ValueError: invalid literal for int() with base 10: 'admin'

Tags: 用户namepyviewobjectmodels页面profile
1条回答
网友
1楼 · 发布于 2024-04-19 00:25:32

外键需要模型对象或对象的主键。你知道吗

传递用户名为“admin”的对象的id。使用

Howl.objects.filter(author=1) 

而不是

Howl.objects.filter(author="admin") 

或者你也可以用这个

user = User.objects.get(username = "admin")
Howl.objects.filter(author=user)

相关问题 更多 >