简体   繁体   中英

Django 1.7, template not displaying data from views.py

python 3.4.2 django 1.7.1 postgres 9.4

I am attempting to query data from postgres and send it to the template for rendering.

I've included the models, views, urls.py, and the media page

I think the issue is in views.py, and the contextDict var I send to the template.

  1. What should be happening:
    1. user hits index.html and clicks a link to view more information about a media asset
    2. index.html loads the views.py 'media' function
    3. media function captures the slugify URL and uses it to query the DB
    4. the 'media' function in views.py loads the data into variables
    5. the 'media' function passes the request, template url, and variables to the template
    6. the template processes the variables and sends the page to the users client
  2. what is happening
    1. user hits index.html and clicks link to view more information about the media asset
    2. index.html loads the views.py mdia function
    3. the user sees a rendered page with text "The specified project {{projectSlugTitle}} does not exist"

what I think the problem is step 3-6 is f**** up, I think the problem lies either in my query to the DB, or how i'm passing the data to the template

model:

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'

view:

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')

              )

the rendered page:

<!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>

Found the issue

I was querying the Project table instead of the Media table

when the user hits index.html and clicks the media link, my code above sent create an SQL to the Project table, and the error cascades from there because of the subsequent lines are based on the initial value of the first variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM