Python / Django TangoWithDjango模型和数据库 [英] Python/Django TangoWithDjango Models and Databases

查看:140
本文介绍了Python / Django TangoWithDjango模型和数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注 http://www.tangowithdjango.com ,我正在尝试填写现有DB与 populate_rango.py 。当我创建新的类别时,我想通过以下方式获取观看次数和喜好:

  Python: 128,64 
Django:64,32
其他框架:32,16

在我的管理面板中,它会显示所有三个类别的视图和喜欢的0。



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



models.py < h3>

 从django.db导入模型

类别(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。标题



populate_rango.py



 import os 
import sys

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

add_page(cat = python_cat,
title =Official Pytho n教程,
url =http://docs.python.org/2/tutorial/)

add_page(cat = python_cat,
title =如何想像电脑科学家,
url =http://www.greenteapress.com/thinkpython/)

add_page(cat = python_cat,
title =学习Python in 10 minutes,
url =http://www.korokithakis.net/tutorials/python/)

django_cat = add_cat(Django,64,32)

add_page(cat = django_cat,
title =官方Django教程,
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 =如何用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)

#打印出我们添加到用户的内容。
在Category.objects.all()中的c:
在Page.objects.filter(category = c)中:
打印 - {0} - {1}格式(str(c),str(p))

def add_page(cat,title,url,views = 0):
p = Page.objects.get_or_create(category = cat,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

#开始执行这里!
如果__name__ =='__main__':
打印启动Rango人口脚本...
os.environ.setdefault('DJANGO_SETTINGS_MODULE','tango_with_django_project.settings')
来自rango.models import Category,Page
populate()



settings.py


 
tango_with_django_project项目的Django设置

有关此文件的更多信息,请参阅
https://docs.djangoproject.com/en/dev/topics/settings/

有关设置及其值的完整列表,请参阅
https:// docs .djangoproject.com / en / dev / ref / settings /


#在项目中构建路径,如下所示:os.path.join(BASE_DIR,...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__ file__))
PROJECT_PATH = os.getcwd()



#快速启动开发设置 - 不适合生产
#请参阅https://docs.djangoproject.com/en/dev/howto/deployment/checklist/

#安全警告:保留生产秘密密钥!
SECRET_KEY ='@& v @ 6mq6b-4(97c8s ^ 4g((t-&%k& @ hi08u $ x0w +(mnhre08m!='

#安全警告:在生产中打开调试程序运行!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []


#应用程序定义

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.XFrameOpt离子中间件',

$ b ROOT_URLCONF ='tango_with_django_project.urls'

WSGI_APPLICATION ='tango_with_django_project.wsgi.application'


#数据库
#https://docs.djangoproject.com/en/dev/ref/settings/#databases

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

#国际化
#https://docs.djangoproject.com/en/dev/topics/i18n/

LANGUAGE_CODE ='en-us'

TIME_ZONE ='UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


#静态文件(CSS,JavaScript,图像)
#https://docs.djangoproject.com/en/dev/howto/static-files/

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

STATIC_URL ='/ static /'#你可能会发现这已经是这样定义的。

STATICFILES_DIRS =(
STATIC_PATH,



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

TEMPLATE_DIRS =(
#将字符串放在这里,如/ home / html / django_templates或C:/ www / django / templates
#始终使用正斜杠
#不要忘记使用绝对路径而不是相对路径
TEMPLATE_PATH,


MEDIA_URL ='/ media /'

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


解决方案

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



我没有做任何工作的管理方面的事情,但它看起来像你的错误在这里:



populate_rango.py

  frame_cat = add_cat(O其他框架,32,16)



pre> 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) / code>到:



frame_cat = add_cat(Other Frameworks,views = 32,likes = 16)



此外,您将有一个名为DATABASE_PATH的数据库(或至少这是我的调用)。您需要删除,然后运行:



python manage.py syncdb p>

&那么只是为了确保它有效,我跑了:



python populate_rango.py



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



我认为我的解决方案将显示视图并喜欢现在。尝试一下,让我知道。


I'm currently following http://www.tangowithdjango.com and I'm trying to populate an existing DB with populate_rango.py. When I create the new categories, I'm trying to get the views and likes to be populated with the following:

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

In my admin panel, it keeps showing 0's for both views and likes for all three categories.

Can someone show me what I'm doing incorrectly with the code below?

models.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()

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

解决方案

I didn't know we needed to complete the exercises of CH5 when doing CH6, luckily I came across your question and this helped me get the desired output I wanted from the index.html.

I haven't done any work with the admin side of things though, but it looks like your error is here:

populate_rango.py

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

and

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

You need to make the views=0 & likes=0 in this line: def add_cat(name, views, likes):

Then you need to change this:

frame_cat = add_cat("Other Frameworks", 32, 16) to this:

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

Also, you will have a database called DATABASE_PATH (or at least that is what mine is called). You need to delete this and run:

python manage.py syncdb

& then just to make sure it worked, I ran:

python populate_rango.py

When you got the error in the admin section, did you first check the /rango page to see if you were getting the correct output? Chances are, you were also either getting an error like me or your categories weren't displaying (I could be wrong though on your output).

I think my solution will display the views and likes now. Try it and let me know.

这篇关于Python / Django TangoWithDjango模型和数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆