如何将他的个人资料页面的作者与django链接?

时间:2016-03-07 15:21:48

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

我正在尝试将帖子的作者链接到他的个人资料页面,但是当我点击链接时,请将两个/个人资料/不提及作者的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]+)/$']      

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

1 个答案:

答案 0 :(得分:2)

{% 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>
相关问题