【问题标题】:How can I link the author of a post two his profile page with django?如何将帖子的作者与 django 链接到他的个人资料页面?
【发布时间】:2016-06-21 05:17:25
【问题描述】:

我正在尝试将帖子的作者链接到他的个人资料页面,但是当我单击链接时,会被引用两个 /profiles/ 而不是作者的 ID。

我的 views.py 看起来像这样:

def userpage(request, id):
    profil = get_object_or_404(UserProfile, pk=id)
    context = {'profil': profil}
    return render(request, 'gaestebuch/userpage.html', context)

我的 urls.py 看起来像这样:

url(r'^profiles/(?P<id>[0-9]+)/$', views.userpage, name='userpage')

我想要链接的 html 部分如下所示:

{% for e in latest_eintrage_list %}
        <li>
           <div id="comment_main">
--->           <a href="{% url 'gaestebuch:userpage' profil.id %}">{{ e.author }}</a>
           <br>
        </div>
        <a href="{% url 'gaestebuch:result' e.id %}">{{ e.title }}</a>
        <br>
        <div id="comment_main">
           Comments: {{ e.comments.count }} | {{ e.created_date }} | {{ e.get_typ_display }}
        </div>
        {% if not forloop.last %}
           <hr>
        {% endif %}
        </li>
{% endfor %}

标有箭头的部分是我想要链接到作者的部分。

models.py:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    info = models.CharField(max_length=200, blank = False, default=('keine Angabe'))


class Eintrag(models.Model):
    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    text = models.TextField()
    NEED = 'ND'
    GIVE = 'GV'
    TYP_CHOICES = (
        (NEED, 'Need'),
        (GIVE, 'Give'),
)

typ = models.CharField(max_length=2, choices= TYP_CHOICES, default=NEED)
created_date = models.DateTimeField(default=timezone.now)

我收到以下错误消息:

Reverse for 'userpage' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'gaestebuch/profiles/(?P<id>[0-9]+)/$']      

我很高兴得到任何帮助:)

【问题讨论】:

  • 您收到什么错误信息?
  • 你上次的 sn-p 中的profil 是什么?..
  • 这是错误消息:未找到带有参数 '('',)' 和关键字参数 '{}' 的 'userpage' 的反向。尝试了 1 种模式:[u'gaestebuch/profiles/(?P[0-9]+)/$']
  • 我认为我必须使用在我的视图中定义的配置文件,因为我对帖子的链接做了同样的事情。我是新的两个 django,所以我猜到了。
  • 再次检查 profil.id 是否实际上是通过在模板中呈现 {{ profil.id }} 来定义的。我怀疑它不会出现

标签: python django django-templates django-views django-urls


【解决方案1】:

{% for e in latest_eintrage_list %} 循环内,您确实有一个变量profil。因此profil.id被视为空字符串,url标签失败。

您可以从Eintrag.author 外键跟随外键到User 模型,然后按照一对一字段向后到UserProfile 模型:

<a href="{% url 'gaestebuch:userpage' e.author.userprofile.id %}">{{ e.author }}</a>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-10
    • 2020-08-09
    • 1970-01-01
    • 2022-10-17
    • 1970-01-01
    • 2020-09-17
    • 2020-08-22
    • 1970-01-01
    相关资源
    最近更新 更多