gpt4 book ai didi

Python/Django TangoWithDjango 模型和数据库

转载 作者:行者123 更新时间:2023-11-28 21:57:33 25 4
gpt4 key购买 nike

我目前正在关注 http://www.tangowithdjango.com我正在尝试使用 populate_rango.py 填充现有数据库。当我创建新类别时,我试图让 View 和喜欢填充以下内容:

Python: 128, 64
Django: 64, 32
Other Frameworks: 32, 16

在我的管理面板中,所有三个类别的浏览量和点赞数一直显示为 0。

有人可以用下面的代码告诉我我做错了什么吗?

模型.py

from django.db import models

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

def __unicode__(self):
return self.name

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

def __unicode__(self):
return self.title

populate_rango.py

import os
import sys

def populate():
python_cat = add_cat('Python', 128, 64)

add_page(cat=python_cat,
title="Official Python Tutorial",
url="http://docs.python.org/2/tutorial/")

add_page(cat=python_cat,
title="How to Think like a Computer Scientist",
url="http://www.greenteapress.com/thinkpython/")

add_page(cat=python_cat,
title="Learn Python in 10 Minutes",
url="http://www.korokithakis.net/tutorials/python/")

django_cat = add_cat("Django", 64, 32)

add_page(cat=django_cat,
title="Official Django Tutorial",
url="https://docs.djangoproject.com/en/1.5/intro/tutorial01/")

add_page(cat=django_cat,
title="Django Rocks",
url="http://www.djangorocks.com/")

add_page(cat=django_cat,
title="How to Tango with Django",
url="http://www.tangowithdjango.com/")

frame_cat = add_cat("Other Frameworks", 32, 16)

add_page(cat=frame_cat,
title="Bottle",
url="http://bottlepy.org/docs/dev/")

add_page(cat=frame_cat,
title="Flask",
url="http://flask.pocoo.org")

# Print out what we have added to the user.
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, url=url, views=views)[0]
return p

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

# Start execution here!
if __name__ == '__main__':
print "Starting Rango population script..."
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django_project.settings')
from rango.models import Category, Page
populate()

设置.py

"""
Django settings for tango_with_django_project project.

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

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

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



# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '@&v@6mq6b-4(97c8s^4g((t-&%k&@hi08u$x0w+(mnhre08m!='

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

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rango',
)

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

ROOT_URLCONF = 'tango_with_django_project.urls'

WSGI_APPLICATION = 'tango_with_django_project.wsgi.application'


# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases

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

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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_PATH = os.path.join(PROJECT_PATH,'static')

STATIC_URL = '/static/' # You may find this is already defined as such.

STATICFILES_DIRS = (
STATIC_PATH,
)


TEMPLATE_PATH = os.path.join(PROJECT_PATH, 'templates')

TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
TEMPLATE_PATH,
)

MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media')

最佳答案

我不知道我们在做 CH6 时需要完成 CH5 的练习,幸运的是我遇到了你的问题,这帮助我从 index.html 中获得了我想要的输出。

虽然我还没有在管理方面做任何工作,但看起来你的错误在这里:

populate_rango.py

    frame_cat = add_cat("Other Frameworks", 32, 16)

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

您需要在这一行中设置 views=0 & likes=0:def add_cat(name, views, likes):

然后你需要改变这个:

frame_cat = add_cat("Other Frameworks", 32, 16) 对此:

frame_cat = add_cat("其他框架", views=32, likes=16)

此外,您将拥有一个名为 DATABASE_PATH 的数据库(或者至少我的是这样叫的)。您需要删除并运行:

python manage.py 同步数据库

& 然后为了确保它有效,我运行了:

python populate_rango.py

当您在管理部分遇到错误时,您是否首先检查了/rango 页面以查看您是否获得了正确的输出?很有可能,您也遇到了像我这样的错误,或者您的类别没有显示(尽管在您的输出中我可能是错的)。

我想我的解决方案现在会显示浏览量和点赞数。试试看,然后告诉我。

关于Python/Django TangoWithDjango 模型和数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19699136/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com