python - Django 1.7,模板不显示来自 views.py 的数据

标签 python django postgresql templates django-models

python 3.4.2 Django 1.7.1 Postgres 9.4

我正在尝试从 postgres 查询数据并将其发送到模板进行渲染。

我已经包含了模型、 View 、urls.py 和媒体页面

我认为问题出在 views.py 和我发送到模板的 contextDict var 中。

  1. 应该发生什么:
    1. 用户点击 index.html 并点击链接以查看有关媒体 Assets 的更多信息
    2. index.html 加载 views.py 的“媒体”函数
    3. 媒体函数捕获 slugify URL 并使用它来查询数据库
    4. views.py 中的“媒体”函数将数据加载到变量中
    5. “媒体”函数将请求、模板 url 和变量传递给模板
    6. 模板处理变量并将页面发送给用户客户端
  2. 发生了什么
    1. 用户点击 index.html 并点击链接以查看有关媒体 Assets 的更多信息
    2. index.html 加载 views.py mdia 函数
    3. 用户看到呈现的页面,其中包含文本“指定的项目 {{projectSlugTitle}} 不存在”

我认为问题是什么 第 3-6 步搞砸了,我认为问题要么出在我对数据库的查询上,要么出在我如何将数据传递到模板上

型号:

from django.db import models
from django.utils import timezone
from django.template.defaultfilters import slugify

#table for media files: audio, video, design
class Media(models.Model):
    #choicesConstants
    #type
    MEDIATYPE_FILM = 'MEDIATYPE_FILM'
    MEDIATYPE_AUDIO = 'MEDIATYPE_AUDIO'
    MEDIATYPE_DESIGN = 'MEDIATYPE_DESIGN'

    #category
    MEDIACATEGORY_MAJOR = 'MEDIACATEGORY_MAJOR'
    MEDIACATEGORY_INDIE = 'MEDIACATEGORY_INDIE'

    #genre
    MEDIAGENRE_RAP = 'MEDIAGENRE_RAP'
    MEDIAGENRE_ROCK = 'MEDIAGENRE_ROCK'
    MEDIAGENRE_TECHNO = 'MEDIAGENRE_TECHNO'

    #choicesList
    choicesType = (
        (MEDIATYPE_FILM,'Video'),
        (MEDIATYPE_AUDIO,'Audio'),
        (MEDIATYPE_DESIGN,'Design'),
    )

    choicesCategory = (
        (MEDIACATEGORY_INDIE,'Indie'),
        (MEDIACATEGORY_MAJOR,'Major'),
    )

    choicesGenre = (
        (MEDIAGENRE_RAP,'Rap'),
        (MEDIAGENRE_ROCK,'Rock'),
        (MEDIAGENRE_TECHNO,'Techno')
    )

    #boolean
    mediaPublished = models.BooleanField(default=True)

    #char fields
    title = models.CharField(max_length=256,blank=True)
    type = models.CharField(max_length=256,choices=choicesType, default=MEDIATYPE_FILM)
    category = models.CharField(max_length=256,choices=choicesCategory,default=MEDIACATEGORY_MAJOR)
    genre = models.CharField(max_length=256,choices=choicesGenre,default=MEDIAGENRE_TECHNO)

    #integer fields
    views = models.IntegerField(default=0)
    upVotes = models.IntegerField(default=0)
    downVotes = models.IntegerField(default=0)

    #date fields
    dateAdded = models.DateTimeField(default=timezone.now)
    datePublished = models.DateTimeField(blank=True,null=True)
    dateDePublished = models.DateTimeField(blank=True,null=True)

    #urlfields
    intUrl = models.URLField(blank=True)
    extUrl = models.URLField(blank=True)

    #email fields
    mediaEmail = models.EmailField(max_length=254,blank=True)

    #decimalFields
    mediaB2bPrice = models.DecimalField(max_digits=20,decimal_places=2,default=0)
    mediaB2cPrice = models.DecimalField(max_digits=20,decimal_places=2,default=0)

    #slugFields
    slug1 = models.SlugField()

    #functionUtility
    def __str__(self):
        return self.title

    #functionMath
    def totalVotes(self):
        return int(self.upVotes)+int(self.downVotes)

    def percentUpVotes(self):
        return int(self.upVotes)/int(self.totalVotes)

    def percentDownVotes(self):
        return int(self.downVotes) / int(self.totalVotes)

    def save(self, *args,**kwargs):
        self.slug1 = slugify(self.title)
        super(Media, self).save(*args, **kwargs)

    #metaData
    class Meta:
        ordering = ['dateAdded','title']
        get_latest_by = 'dateAdded'
        verbose_name = 'Media'
        verbose_name_plural = 'Media'

#tablef for projects, contain multiple media files
class Project(models.Model):
    #manyToMany relationships
    media = models.ManyToManyField(Media,null=True,blank=True)

    #boolean
    projectPublished = models.BooleanField(default=True)

    #charFields
    title = models.CharField(blank=True,max_length=256)

    #textFields
    projectDescription = models.TextField(blank=True)

    #email fields
    projectEmail = models.EmailField(max_length=254,blank=True)

    #dateFields
    dateCreated = models.DateTimeField(default=timezone.now)
    datePublished = models.DateTimeField(blank=True,null=True)

    #decimalFields
    projectB2bPrice = models.DecimalField(max_digits=20,decimal_places=2,default=0)
    projectB2cPrice = models.DecimalField(max_digits=20,decimal_places=2,default=0)

    #slugFields
    slug1 = models.SlugField()

    #functionsUtility
    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        self.slug1 = slugify(self.title)
        super(Project, self).save(*args, **kwargs)

    #metaData
    class Meta:
        ordering = ['dateCreated','title']
        get_latest_by = 'dateAdded'
        verbose_name = 'Project'
        verbose_name_plural = 'Projects'

查看:

def project(request,theProjectSlug):
    contextDict = {}
    try:
        #retrieve the project with the matching slug name
        project = Project.objects.get(slug1=theProjectSlug)
        contextDict['projectName'] = project.title

        #retrieve all of the associated media files of the project above
        mediaFiles = Media.objects.all().filter(project=project)

        #add mediaFiles to contextDict,add the project to the contextDict
        contextDict['mediaFilesOfProject'] = mediaFiles
        contextDict['project'] = project

    except Project.DoesNotExist:
        pass

    return render(request, 'famecity/media.html', contextDict)

urls.py:

urlpatterns = patterns('',
                       url(r'^$',views.index,name='index'),
                       url(r'^about/',views.about,name='about'),
                       url(r'^media/(?P<theProjectSlug>[\w\-]+)/$',views.project,name='project')

              )

呈现的页面:

<!DOCTYPE html>
<html>
<head>
    <title>Fame.city Projects
    </title>
</head>

<body>
    <h1>
        projectName: {{ projectName }}<br/>
        mediaFilesOfProject: {{mediaFilesOfProject}}<br/>
        project: {{project}}<br/>
    </h1>
    {% if project %}
        {% if media %}
            <ul>
                {% for mFile in media %}
                    <li>
                        <a href="{{mFile.url}}">{{mFile.title}}</a>
                    </li>
                {% endfor %}
            </ul>
        {% else %}
            <strong>No media files exist</strong>
        {% endif %}
    {% else %}
        The specified project {{projectSlugTitle}} does not exist
    {% endif %}
</body>
</html>

最佳答案

发现问题

我查询的是 Project 表而不是 Media 表

当用户点击 index.html 并点击媒体链接时,我上面的代码将创建一个 SQL 发送到 Project 表,错误从那里开始级联,因为后续行基于第一个变量的初始值。

关于python - Django 1.7,模板不显示来自 views.py 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27752321/

相关文章:

python - 在 Python 中使用加密负载的 Chrome Web 推送通知

sql - Postgresql 在 json 数组中的数组中搜索

mysql - 进行数据同步时检查已删除项目的最佳方法?

python:过滤几乎相同文本的算法

python - 为什么我收到此错误 : "Invalid rectstyle argument"

javascript - 使用 jQuery 在表单提交上将隐藏输入值设置为 dataURL

python - Django 组/聚合

database - 为什么刷新物化 View 会同时阻止插入/更新?

python - Django 中 QuerySet 中特定列的平均重复项

python - 如何在Python中将postgres表列指定为变量?