Django url中的对象ID

时间:2017-03-06 15:03:10

标签: python django url django-urls

我有一个类似下面的Post模型:

class Post(models.Model):
user = models.ForeignKey(User)
posted = models.DateTimeField(auto_now_add=True)
content = models.CharField(max_length=150)
picturefile = models.ImageField(upload_to="post_content", blank=True)

我希望能够将每个帖子的ID放在网址中,以便我可以单独访问每个帖子。我之前使用用户的ID来查看用户的个人资料页面。

    url(r'^profile/(?P<username>\w+)/$', Dashviews.public_profile_view, name='public_profile_view'),

但是我如何制作相同类型的网址,而是使用帖子的ID?

3 个答案:

答案 0 :(得分:3)

简单地

url('^post/(?P<post_id>\d+)/$',Dashviews.public_post_view, name='public_post_view'),
views.py中的

def public_post_view(request, post_id):
    # do some stuff
模板中的

{% url 'public_post_view' post.id %}

答案 1 :(得分:0)

    url(r'^profile/(?P<pk>\d+)/$', Dashviews.public_profile_view, name='public_profile_view'),

答案 2 :(得分:0)

更好的方法是在模型中添加get_absolute_url:

首先,定义模型的视图:

def public_post_view(request, post_id):
    # print(post_id) or whatever you want

然后创建地图以映射该视图:

urls.py

url('^post/(?P<post_id>\d+)/$', Dashviews.public_post_view, name='public_post_view'),

然后,使Post模型中的每个对象都能够创建自己的URL。

models.py

from django.core.urlresolvers import reverse_lazy

class Post(models.Model):
    user = models.ForeignKey(User)
    posted = models.DateTimeField(auto_now_add=True)
    content = models.CharField(max_length=150)
    picturefile = models.ImageField(upload_to="post_content", blank=True)

    def get_absolute_url(self):
        return reverse_lazy('public_post_view', kwargs={'post_id': self.id})

现在您可以使用

<a href="{{ post.get_absolute_url }}">Go to the post</a>

在您的模板中。因此,只要您显示{{ post.content }}之类的内容或类似内容,您也可以使用get_absolute_url方法获取其网址。