You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Django创建用户专属页面?新手技术求助

解决Django用户专属页面获取个人信息的问题

Hey there! Let's get your user-specific page working properly. You're really close—here's how to fix the missing piece in your views.py:

第一步:获取当前登录用户的关联信息

Since you're using the @login_required decorator, Django gives you access to the currently logged-in user via request.user. Your UserInfo model is linked to the built-in User model with a ForeignKey, and you set related_name='userinfo'—this lets you directly fetch the associated UserInfo instance for the logged-in user.

Update your views.py like this:

@login_required(login_url="/register")
def main(response):
    # 用get_or_create避免用户未提交信息时抛出异常
    thisUser, created = UserInfo.objects.get_or_create(authuser=response.user)
    return render(response, 'main.html', {'thisUser': thisUser})

为什么用get_or_create?

If a user hasn't filled out their profile yet, get_or_create will create an empty UserInfo instance linked to their account (instead of crashing your page). You can adjust this based on your workflow—if you want to force users to fill out the profile first, you could redirect them to the form page if created is True.

第二步:优化模板(可选但推荐)

To handle cases where the user hasn't added their info yet, update your main.html to show a friendly prompt:

{% extends 'base.html' %}
{% block content %}
    <h2>你的专属页面</h2>
    {% if thisUser.name and thisUser.introduction %}
        <p><strong>姓名:</strong>{{ thisUser.name }}</p>
        <p><strong>简介:</strong>{{ thisUser.introduction }}</p>
    {% else %}
        <p>你还未完善个人信息,请先<a href="{% url '你的信息表单URL' %}">填写个人资料</a></p>
    {% endif %}
{% endblock %}

额外建议:改用OneToOneField(更贴合业务逻辑)

Since each user should only have one set of personal info, using a OneToOneField instead of ForeignKey makes more sense—it enforces a strict 1:1 relationship between User and UserInfo. Update your models.py:

class UserInfo(models.Model):
    authuser = models.OneToOneField(User, on_delete=models.CASCADE, related_name='userinfo', null=True)
    name = models.CharField(max_length=50)
    introduction = models.CharField(max_length=100)

This won't break your existing code—you can still access request.user.userinfo the same way, but it prevents multiple UserInfo entries from being linked to a single user.

That's it! Now when users log in, their personal info will show up dynamically on the main page.

内容的提问来源于stack exchange,提问作者Ryan Oh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 23:52:45