无法在Django区块内容Django 1.7

时间:2018-09-30 14:12:05

标签: python django

我正在尝试在Django模板中呈现一些内容。但是由于某种原因,block标签内部没有呈现任何内容。我正在使用Django 1.7和Python 2.7。

我还注意到我的产品的get_absolute_url无法正常工作。

这是我到目前为止尝试过的:

# -*- coding: utf-8 -*-

from __future__ import unicode_literals

from django.db import models


# Create your models here.

class Category(models.Model):
    name = models.CharField(max_length=50)
    slug = models.SlugField(max_length=50, unique=True,
                            help_text='Unique value for product page URL, created from name.')
    description = models.TextField()
    is_active = models.BooleanField(default=True)
    meta_keywords = models.CharField("Meta Keywords", max_length=255,
                                     help_text='Comma-delimited set of SEO keywords for meta tag')
    meta_description = models.CharField("Meta Description", max_length=255,
                                        help_text='Content for description meta tag')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)


class Meta:
    ordering = ['-created_at']
    verbose_name_plural = 'Categories'

    def __unicode__(self):
        return self.name

    @models.permalink
    def get_absolute_url(self):
        return 'catalog_category', (), {'category_slug': self.slug}


class Product(models.Model):


    name = models.CharField(max_length=255, unique=True)
    slug = models.SlugField(max_length=255, unique=True,help_text = 'Unique value for product page URL, created from name.')
    brand = models.CharField(max_length=50)
    sku = models.CharField(max_length=50)
    price = models.DecimalField(max_digits=9, decimal_places=2)
    old_price = models.DecimalField(max_digits=9, decimal_places=2,blank = True, default = 0.00)
    image = models.CharField(max_length=50)
    is_active = models.BooleanField(default=True)
    is_bestseller = models.BooleanField(default=False)
    is_featured = models.BooleanField(default=False)
    quantity = models.IntegerField()
    description = models.TextField()
    meta_keywords = models.CharField(max_length=255,help_text = 'Comma-delimited set of SEO keywords for meta tag')
    meta_description = models.CharField(max_length=255,help_text = 'Content for description meta tag')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    categories = models.ManyToManyField(Category)


class Meta:
    ordering = ['-created_at']

    def __unicode__(self):
        return self.name

    @models.permalink
    def get_absolute_url(self):
        return 'catalog_product', (), {'product_slug': self.slug}

    def sale_price(self):
        if self.old_price > self.price:
            return self.price
        else:
            return None

views.py

 def show_product(request, product_slug, template_name="catalog/product.html"):

        print('Product info')
        print('productslug',product_slug)
        p = get_object_or_404(Product, slug=product_slug)
        print('p',p.sku)
        categories = p.categories.filter(is_active=True)

        print('categories',len(categories))
        page_title = p.name
        meta_keywords = p.meta_keywords
        meta_description = p.meta_description
        return render_to_response(template_name, locals(), context_instance=RequestContext(request))


category_list.html
<h3>Categories</h3>
{% for c in active_categories %}
<a href="{{ c.get_absolute_url }}">{{ c.name }}</a><br />
{% endfor %}
catalog.html

    {% include "tags/category_list.html" %}
    {% include "tags/base.html" %}

product.html

    {% extends "tags/catalog.html" %}
    {% block content %}
        <div class="product_image">
            <h1>{{ p.name }}</h1>

        </div>

    {% endblock %}

settings.py

    """

    Django settings for lstm project.

    Generated by 'django-admin startproject' using Django 1.11.10.

    For more information on this file, see
    https://docs.djangoproject.com/en/1.11/topics/settings/

    For the full list of settings and their values, see
    https://docs.djangoproject.com/en/1.11/ref/settings/
    """

    import os

    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))








    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True

    ALLOWED_HOSTS = ['*']


    # Application definition

    TIME_ZONE = 'Africa/Kenya'
    USE_TZ = True



    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'catalog',
        'utils',

    ]


    CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
            'LOCATION': '127.0.0.1:11211',
        }
    }



    MIDDLEWARE_CLASSES = [
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]



    from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS


    TEMPLATE_CONTEXT_PROCESSORS +=  ('utils.context_processors.ecomstore',)


    SITE_NAME = 'MV'
    META_KEYWORDS = ''
    META_DESCRIPTION = ''

    ROOT_URLCONF = 'lstm.urls'

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]

    WSGI_APPLICATION = 'lstm.wsgi.application'


    # Database


    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }


    # Password validation
    # https://docs.djangoproject.com/en/1.7/ref/settings/#auth-password-validators

    AUTH_PASSWORD_VALIDATORS = [
        {
            'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
        },
    ]

    #MEDIA_URL = '/static/'
    #MEDIA_ROOT = os.path.join(BASE_DIR, "media")

    # Internationalization
    # https://docs.djangoproject.com/en/1.7/topics/i18n/

    LANGUAGE_CODE = 'en-us'

    TIME_ZONE = 'UTC'

    USE_I18N = True

    USE_L10N = True

    USE_TZ = True

    import dj_database_url
    prod_db  =  dj_database_url.config(conn_max_age=500)
    DATABASES['default'].update(prod_db)


    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/1.11/howto/static-files/

    STATIC_URL = '/static/'

    STATICFILES_DIRS = (
        os.path.join(BASE_DIR, 'static'),
    )

    #STATIC_ROOT = os.path.join(BASE_DIR, 'static')


    STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'


    PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
    STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')



utils/context_processors.py

    from catalog.models import Category
    from lstm import settings

    def ecomstore(request):
        return {
            'active_categories': Category.objects.filter(is_active=True),
            'site_name': settings.SITE_NAME,
            'meta_keywords': settings.META_KEYWORDS,
            'meta_description': settings.META_DESCRIPTION,
            'request': request
        }

1 个答案:

答案 0 :(得分:0)

根据每个问题,您的catalog.html如下:

{% include "tags/category_list.html" %}
{% include "tags/base.html" %}

因此,您在此处{% block content %}定义为要被覆盖的占位符(如果您从另一个模板扩展 您只能覆盖现有的{% block .. %})。

也许该块是在tags/base.html(或tags_category_list.html)中定义的,但是您需要从该模板扩展

简而言之,您只能覆盖直接或间接 的块(如果您继承自从另一个模板继承的模板),则不能引入新的块,因为这样“主模板”可以不知道放在哪里。