探戈与Django第6章-URL不起作用

时间:2018-10-03 12:41:21

标签: python django

我一直在学习“与Django一起探戈”,无法亲自解决或通过在线解决此问题。有人知道如何解决吗?

当我单击链接时,应该打开相关页面,但没有任何链接通过,这使我认为view.py文件中甚至是url.py或model.py文件(索引。 html似乎正常工作。)

Views.py

# Create your views here.
from django.http import HttpResponse
from django.shortcuts import render
from Spaces.models import Category, Page

def index(request):
    # Query the databse for a list of ALL categories currently stored.
    # Order the categories by no likes in descending order .
    # Retrieve the top 5 only - or all if less than 5.
    # Place the list in context_dict dictionary
    # that will be passed to the template engine.
    category_list = Category.objects.order_by('-likes')[:5]

    context_dict = {'categories': category_list}

    # Render the response and send it back!

    return render(request, 'Spaces/index.html', context=context_dict)


def about(request):
    context_dict = {'boldmessage':"Crunchy, creamy, cookie, candy, cupcake!"}
    return render(request, 'Spaces/about.html', context=context_dict)

def show_category(request, category_name_slug):
    # Create a context dictionary which we can pass
    # to the template rendering engine.
    context_dict = {}
    try:
        # Can we find a category name slug with the given name?
        # If we can't, the .get() method raises a DoesNotExist exception.
        # So the .get() method returns one model instance or raises an exception.
        category = Category.objects.get(slug=category_name_slug)
        # Retrieve all of the associated pages.
        # Note that filter() will return a list of page objects or an empty list
        pages = Page.objects.filter(category=category)
        # Adds our results list to the template context under name pages.
        context_dict['pages'] = pages
        # We also add the category object from
        # the database to the context dictionary.
        # We'll use this in the template to verify that the category exists.
        context_dict['category'] = category
    except Category.DoesNotExist:
        # We get here if we didn't find the specified category.
        # Don't do anything -
        # the template will display the "no category" message for us.
        context_dict['category'] = None
        context_dict['pages'] = None
        # Go render the response and return it to the client.
        return render(request, 'Spaces/category.html', context_dict)

Urls.py

from django.conf.urls import url

from Spaces import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^about/$', views.about, name='about'),
    url(r'^category/(?P<category_name_slug>[\w\-]+)/$',
        views.show_category, name='show_category'),
]

models.py

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


class Category(models.Model):
    name = models.CharField(max_length=128, unique=True)
    views = models.IntegerField(default=0)
    likes = models.IntegerField(default=0)
    slug = models.SlugField(unique=True, blank=True, null=True)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Category, self).save(*args, **kwargs)

    class Meta:
        verbose_name_plural = 'categories'

    def __str__(self):
        return self.name


class Page(models.Model):
    category = models.ForeignKey(Category, on_delete=models.PROTECT)
    title = models.CharField(max_length=128)
    url = models.URLField()
    views = models.IntegerField(default=0)

    def __str__(self): # For Python 2, use __unicode__ too
        return self.title

index.html

<!DOCTYPE html>
{% load staticfiles %}
<html>
<head>
  <title>Spaces</title>
</head>
<body>
  <h1>Spaces says...</h1>
  <div>hey there partner!</div>

  <div>
    {% if categories %}
    <ul>
    {% for category in categories %}
      <li>
        <a href="{% url 'show_category' category_name_slug=category.slug %}">{{ category.name }}</a>
      </li>
    {% endfor %}
    </ul>
    {% else %}
    <strong>There are no categories present.</strong>
    {% endif %}
  </div>

  <div>
    <a href="/Spaces/about/">About Space</a><br />
    <img src="{% static 'images/Spaces.jpg' %}" alt="Picture of Rango" />
  </div>
</body>
</html>

populate_spaces.py(测试脚本)

import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
                        'Space.settings')
import django
django.setup()
from Spaces.models import Category, Page

def populate():
    #First, we will create lists of dictionaries containing the pages
    # we want to add into each category.
    # Then we will create a dictionary of dictionaries for our categories.
    # This might seem a little bit confusing, but it allows us to iterate
    # through each data structure, and add the data to our models.

    python_pages = [
    {"title": "Prahran",
    "url":"http://docs.python.org/2/tutorial/", "views":20},
    {"title": "South Yarra",
    "url":"http://docs.python.org/2/tutorial/", "views":25},
    {"title": "etcetera",
    "url":"http://docs.python.org/2/tutorial/", "views":35}
    ]

    django_pages = [
    {"title" :  "Official Django Tutorial",
    "url" :"https://docs.djangoproject.com/en/1.9/intro/tutorial01/", "views":36},
    {"title":"Django Rocks",
    "url":"http://www.djangorocks.com/", "views":23},
    {"title":"How to Tango with Django",
    "url":"http://www.tangowithdjango.com/", "views":45}
    ]

    other_pages = [
    {"title":"Bottle",
    "url":"http://bottlepy.org/docs/dev/", "views":3},
    {"title":"Flask",
    "url":"http://flask.pocoo.org",
    "views":34}]

    cats = {"Python": {"pages": python_pages, "views": 128, "likes":64},
            "Django": {"pages": django_pages, "views": 64, "likes":32},
            "Other Frameworks": {"pages": other_pages, "views": 32, "likes":16} }

    # If you want to add more categories or pages,
    # Add them to the dictionaries above.

    # The code below goes through the cats dictionary, then adds each category
    # and then adds all the associated pages for that category.





    for cat, cat_data in cats.items():
        c = add_cat(cat,cat_data)
        for p in cat_data["pages"]:
            add_page(c, p["title"], p["url"], p["views"])

    #Print out the categories we have added.
    for c in Category.objects.all():
        for p in Page.objects.filter(category=c):
            print("-{0})-{1}".format(str(c), str(p)))

def add_page(cat, title, url, views=0):
    p = Page.objects.get_or_create(category=cat, title=title)[0]
    p.url=url
    p.views=views
    p.save()
    return p

def add_cat(name, cat_data):
    c = Category.objects.get_or_create(name=name)[0]
    c.likes = cat_data["likes"]
    c.views = cat_data["views"]
    c.save()
    return c

    # Start execution here!
if __name__ == '__main__':
    print("Starting Spaces population script...")
    populate()

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。

基本上,我在view.py文件中缩进了一个返回函数!