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

如何从Product页面生成访问作者Public Profile页面的URL

解决方案

1. 修正Profile模型的关联关系与Slug生成逻辑

Profile与User应为一对一关联(一个用户对应唯一的个人资料),将ForeignKey改为OneToOneField,同时明确用用户名生成slug避免歧义:

class Profile(models.Model):
    # 改为OneToOneField,确保用户与资料一一对应
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    profile_photo = models.ImageField(upload_to='profile-image', default='static/dafault.jpg')
    twitter = models.URLField(blank=True, null=True, unique=True)
    website = models.URLField(blank=True, null=True, unique=True)
    linkedln = models.URLField(blank=True, null=True, unique=True)
    country = models.CharField(max_length=70, blank=True, null=True,)
    about = models.TextField(max_length=700, blank=True, null=True)
    slug = models.SlugField(max_length=100, unique=True)

    def save(self, *args, **kwargs):
        # 明确使用用户名生成slug,避免对象转换问题
        self.slug = slugify(self.user.username)
        super().save(*args, **kwargs)

    def __str__(self):
        return str(self.user.username)

2. 完善视图函数(获取对应Profile对象)

当前视图未根据slug加载用户资料,补充查询逻辑:

from django.shortcuts import get_object_or_404

def public_profile(request, slug):
    # 根据slug获取对应的Profile,不存在则返回404
    profile = get_object_or_404(Profile, slug=slug)
    return render(request, 'public_profile.html', {'profile': profile})

3. 修正URL配置(移除开头的斜杠)

Django URL路径不需要开头的斜杠,否则会导致匹配异常:

path('<slug:slug>/', views.public_profile, name='Public-Profile'),

4. 修正模板中的链接与用户名显示

循环中需引用当前Product的作者(product.user)而非全局user,同时传递Profile的slug参数给URL:

{% for product in products %}
<div class="col-md-3">
    <div class="card my-2 shadow-sm bg-body">
        <div class="card-head">
            <a href="{% url 'Public-Profile' slug=product.user.profile.slug %}">
                <span class="material-symbols-outlined">
                    account_circle
                </span>
                {{ product.user.username }}
            </a>
        </div>
    </div>
</div>
{% endfor %}

关键说明

  • 用OneToOneField确保用户与Profile的唯一关联,避免一个用户对应多个资料的异常情况。
  • 模板中必须使用product.user获取当前产品的作者,否则会错误显示当前登录用户的信息。
  • URL必须传递Profile的slug参数,因为视图是通过Profile的slug来定位用户资料的。

内容的提问来源于stack exchange,提问作者Adamu Abdulkarim Dee

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 18:47:36