【问题标题】:django 1.8 what does <a href="{% url "post_detail" pk=post.pk %}">{{ post.title }}</a> dodjango 1.8 <a href="{% url "post_detail" pk=post.pk %}">{{ post.title }}</a> 做了什么
【发布时间】:2015-12-03 16:40:31
【问题描述】:

我从djangogirls学习django

我无法理解以下代码块在扩展名为“博客”的应用程序时的作用。我用谷歌搜索但找不到相关的例子。 我有一个名为 post_list.html 的模板文件,它扩展了 base.html 并且看起来像

{% extends "blog/base.html" %}

{% block content %}
    {% for post in posts %}
        <div class="post">
            <div class="date">
                {{ post.published_date }}
            </div>
        <h1><a href="{% url "post_detail" pk=post.pk %}">{{ post.title }}</a></h1>   #confused part here ??

        <p>{{ post.text|linebreaks }}</p>
    </div>
    {% endfor %}
{% endblock content %}


i dont have post.pk in any model and dont know how it is assigned to "pk"   variable

<h1><a href="{% url "post_detail" pk=post.pk %}">{{ post.title }}</a> 

</h1> 

下面是app url和model的样子

#models.py
from django.db import models
from django.utils import timezone

class Post(models.Model):
    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)

def publish(self):
    self.published_date = timezone.now()
    self.save()

def __str__(self):
    return self.title



#views.py
from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from .models import Post
def post_list(request):
    posts =     Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'blog/post_list.html', {'posts': posts})    

def post_detail(request, pk):
    post = get_object_or_404(Post, pk=pk)
    return render(request, 'blog/post_detail.html', {'post': post})

#urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'),
]

谢谢

【问题讨论】:

    标签: django django-models django-templates


    【解决方案1】:

    默认情况下,所有 django 模型都有一个名为 id 的主键;即使您没有在models.py 中指定一个。

    .pk 是 django 分配的每个模型的 automatic generated property,它指的是主键。

    之所以使用.pk,是因为无论实际主键字段是什么,它都会返回主键值。因此,如果您决定创建一个模型,其中您拥有自己的主键(因此,django 不会为您创建主键).pk 仍然可以工作。

    【讨论】:

    • 感谢 Burhan Khalid,为我扫清了阴霾。 django 生成的主键是否永久存储到关联的模型对象中?
    • 是的;否则 ForeignKey 关系将不起作用。
    猜你喜欢
    • 2011-04-21
    • 1970-01-01
    • 2015-09-17
    • 1970-01-01
    • 1970-01-01
    • 2011-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多