Django Book 2.0 遇到的问题

把学习Django遇到的问题记录一下,不是很全了。而且还没看完。

学习网页         http://djangobook.py3k.cn/2.0/   

带附录的网页  http://www.djangobook.com/en/2.0/index.html

查看文档         https://docs.djangoproject.com/en/1.7/

问题1.  安装问题

问题2. urls.py 元组问题

问题3. 设置DJANGO_SETTINGS_MODULE参数

问题4. 文件第一行添加编码注释    #-*- coding: utf-8 -*-

问题5. 数据库的连接

问题6. 数据库的卸载安装

问题7. 数据库模型的有效性

问题8. Book类添加Author内容

暂时先弄这些,以后再添加。

1、 Django安装

django下载后,解压到python一样的安装路径。如果是cPython27,那么就把django解压形成CDjango-1.7.1,然后,cmdcd C:Django-1.7.1, python setup.py install这样django就安装上了。再打开pythonIDE import django成功。设置系统路径。计算机右键,属性,高级设置,环境变量,系统变量。path里面添加C:Python27scripts;C:Python27Libsite-packagesDjango-1.7.1-py2.7.eggdjango;

2.  urls.py 元组问题

mysite下有urls.py文件,修改里面的连接,形成自己需要的网址。应用正则。注意逗号不能少。(为什么逗号不能少?)Python 要求单元素元组中必须使用逗号,以此消除与圆括号表达式之间的歧义。 这是新手常犯的错误。以后要处处注意元组。

3. 设置DJANGO_SETTINGS_MODULE参数

运行Start->Run->cmd->cd C:Python25Libsite-packagesdjangoinmysite->输入set DJANGO_SETTINGS_MODULE=mysite.settings

如果放在Python IDLE里面使用,是需要这样设置的。

from django.conf import settings

settings.configure() #默认使用全局setting。也就是放在manage.py里面的setting

 

4.  第一行添加编码注释    #-*- coding: utf-8 -*-

必须要添加一行声明文件编码的注释,否则python2会默认使用ASCII编码(http://blog.csdn.net/arbel/article/details/7957782)。如果不添加,同时程序不能运行,就会跳出来一行 https://www.python.org/dev/peps/pep-0263/让你查看编码使用规则。  

5. 数据库的连接

setting.py里面的设置

DATABASES = {

    'default': {

        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.

        'NAME': 'books',                      # Or path to database file if using sqlite3.

        'USER': 'root',                      # Not used with sqlite3.

         'PASSWORD': '123456',                  # Not used with sqlite3.

         'HOST': 'localhost',                      # Set to empty string for localhost. Not used with sqlite3.#这里写127.0.0.1也可以

         'PORT': '3306',                      # Set to empty string for default. Not used with sqlite3.

    }

 }

把数据库卸载了,再安装,觉得安装好了,但是还是用不了,最后老是连接不上,问题出在哪里?发现少了逗号呀。这里的DATABASES也是一个元组,需要每个后面加一个逗号,特别是最后一个逗号。是逗号,不是分好,不是空着什么也不写。

6. 这里问题都是查看其它大量网页(http://jingyan.baidu.com/article/f96699bbaa8fc1894f3c1b5a.html)

要卸载程序,还有注册表cmd->register,删除HKEY_LOCAL_MACHINESYSTEMControlSet001ServicesEventlogApplicationMySQL文件夹,删除HKEY_LOCAL_MACHINESYSTEMControlSet002ServicesEventlogApplication MySQL文件夹,删除HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesEventlog ApplicationMySQL的文件夹,还有C:ProgramData里面的mysql文件夹,还有C:Program Files里面的文件夹。重启就成功了。

数据库的安装

http://jingyan.baidu.com/article/3052f5a1dad91197f21f8610.html

http://dev.mysql.com/downloads/windows/installer/

python mysql 数据库配置

http://jingyan.baidu.com/article/0eb457e5026ed903f1a9052a.html

数据库的卸载

http://blog.sina.com.cn/s/blog_6fc5bfa90100qmr9.html

7. 数据库模型有有效性验证

C:Python27Libsite-packagesDjango-1.7.1-py2.7.eggdjangoinmysite>python manage.py sqlall books

CommandError: App 'books' has migrations. Only the sqlmigrate and sqlflush commands can be used when an app has migrations.

此时需要输入如下部分即可

C:Python27Libsite-packagesDjango-1.7.1-py2.7.eggdjangoinmysite>python manage.py makemigrations

C:Python27Libsite-packagesDjango-1.7.1-py2.7.eggdjangoinmysite>python manage.py migrate

8. Book类添加author内容

在Book类中,如果想加author,加不到,最终我在数据库里面添加了。

在模型加入数据库的时候,添加了几个表格

mysql> show tables;

+--------------------+

| Tables_in_books    |

+--------------------+

| books_author       |

| books_book         |

| books_book_authors |

| books_publisher    |

| django_migrations  |

+--------------------+

添加Book类实例数据

import datetime

b1=Book(title="Ni Hao",publisher_id=1,publication_date=datetime.date(2015,01,01))

b2=Book(title="Hello World",publisher_id=2,publication_date=datetime.date(2015,01,02))

b3=Book(title="How are you",publisher_id=3,publication`_date=datetime.date(2015,01,03))

b1.save()

b2.save()

写入Author类实例

a1=Author(first_name="Wendy",last_name="Xu",email="wendy.xu@sina.com")

a2=Author(first_name="Beryl",last_name="Li",email="beryl.li@sina.com")

a3=Author(first_name="Billly",last_name="Xu",email="billy.xu@sina.com")

 在数据库中编辑books_book_authors表,建立Book表和Author表的关联。

insert into books_book_authors values(1,1,1),(2,2,2),(3,1,3);

insert into books_book_authors values(4,3,1),(5,2,1),(6,3,2);

结果就可以使用book和author的关联了。

>>>b1=Book.objects.get(id=1)

 >>>b1.__doc__
 >>>u'Book(id, title, publisher_id, publication_date, num_pages)'

Book,Publisher, Author  模型如下:

class Publisher(models.Model):

name = models.CharField(max_length=30)

address = models.CharField(max_length=50)

city = models.CharField(max_length=60)

state_province = models.CharField(max_length=30)

country = models.CharField(max_length=50)

website = models.URLField()

def __unicode__(self):

return self.name

class Meta:

ordering=['name']

 

class Author(models.Model):

first_name = models.CharField(max_length=30)

last_name = models.CharField(max_length=40)

email = models.EmailField()

def __unicode__(self):

return u'%s %s' % (self.first_name, self.last_name)

 

class Book(models.Model):

title = models.CharField(max_length=100)

authors = models.ManyToManyField(Author)  #注意这里的多对多设置,最后数据库里面形成了一个新表,books_book_authors

publisher = models.ForeignKey(Publisher)   #注意这里外键设置,最后在数据库的books_book表里面变成了publisher_id

publication_date = models.DateField()

num_pages=models.IntegerField(blank=True, null=True)

objects=BookManager()

wendy_objects=WendyBookManager()

 

def __unicode__(self):

return self.title

查看b1的作者  b1.authors.all()        b1.authors.all().count()

查看b1的出版社  b1.publisher         b1.publisher.website

同样的,a1=Author.objects.get(id=1)

查看a1的书   a1.book_set.all()
 [<Book: Ni Hao>, <Book: Hello World>, <Book: How are you>]

可以通过dir() 查看属性  比如, dir(a1), dir(a1.book_set)

 p1=Publisher.objects.get(id=1)

 p1.book_set.all()
 [<Book: Ni Hao>]

原文地址:https://www.cnblogs.com/gjwork/p/4255169.html