Django 01 to create a project (windows)

Copyright: arbitrary, seeding https://blog.csdn.net/qq_32662595/article/details/85251608!
  1. Create a virtual environment
    installation virtualenv: pip install virtualenv
    problems may arise:
	 ImportError: cannot import name 'main'
	 python提示AttributeError: 
	 'NoneType' object has no attribute 'append'
	 
	 解决方法: pip install https://github.com/pyinstaller/pyinstaller/tarball/develop
  1. Create a project directory under the virtual environment
    virtualenv image
  1. Activation
    into the into the scripts folder new-env directory, windows under dir can see what files, runactivate
activate
  1. Create a project

     django-admin startproject dj01
    

If a problem occurs -> here

结构如下-》

dj01/  --项目根目录是一个容器
    manage.py      一个命令行实用程序,可以让你与这个Django项目以不同的方式进行交互
    dj01/              实际Python包为您的项目
        __init__.py   一个空文件,告诉Python这个目录应该考虑一个Python包
        settings.py   Django projec配置
        urls.py       Django projec URL声明
        wsgi.py       WSGI-compatible web服务器的一个入口点为您的项目

Run the following command (default port 8000):

python manage.py runserver 

或  python manage.py runserver 8080

result:
Here Insert Picture Description

  1. Create a name is not the app Polls

     python manage.py startapp polls
    

    Project is structured as follows:
    can be independently as separate items poll

  2. Configuration database
    dj01 / settings.py replaced by the following fields of information:

    Data Field
    defaultProject to match your database connection settings
    ENGINEcan be [ 'django.db.backends.sqlite3', 'django.db.backends.postgresql' , 'django.db.backends.mysql', or 'django.db.backends.oracle '] one. or other (this is similar to the data driver java)
    NAMEdatabase name (using the sqlite3 os.path.join (bASE_DIR,' db.sqlite3 ') ,)
    USERdatabase username
    PASSWORDdatabase password
    HOSTdatabase host address

  3. INSTALLED_APPS

    INSTALLED_APPS set at the bottom of the file. It saves all the current Django Django application instance is activated. Each application can be used by multiple projects, and you can package and distribute it to other people to use in their projects.

    django.contrib.auth - authentication system.
    django.contrib.contenttypes - the content type framework.
    django.contrib.sessions - session framework.
    django.contrib.sites - Site management framework.
    django.contrib.messages - message frame.
    django.contrib.staticfiles - static file management framework.

	python manage.py migrate
		该命令参照settings.py 文件 `INSTALLED_APPS` 所配置的数据库中创建必要的数据库表。每创建一个数据库表你都会看到一条消息,接着你会看到一个提示询问你是否想要在身份验证系统内创建个超级用户。
  1. Creating models
 	from django.db import models  
    	class Question(models.Model):
        	question_text = models.CharField(max_length=200)
        	pub_date = models.DateTimeField('date published')
    
    
    	class Choice(models.Model):
    		# ForeignKey
        	question = models.ForeignKey(Question, on_delete=models.CASCADE)
        	choice_text = models.CharField(max_length=200)
        	votes = models.IntegerField(default=0)
  1. The polls added dj01 / settings.py / INSTALLED_APPS in
    Here Insert Picture Description

Execute the following command: change of models already told django, let Django know you want to update an existing view.

python manage.py makemigrations polls

Results of the-

Migrations for 'polls':
  polls/migrations/0001_initial.py:
    - Create model Choice
    - Create model Question
    - Add field question to choice

Then execute the following command, we will see the generated database tables, and detailed sql statement.

python manage.py sqlmigrate polls 0001
BEGIN;
--
-- Create model Choice
--
CREATE TABLE "polls_choice" (
    "id" serial NOT NULL PRIMARY KEY,
    "choice_text" varchar(200) NOT NULL,
    "votes" integer NOT NULL
);
--
-- Create model Question
--
CREATE TABLE "polls_question" (
    "id" serial NOT NULL PRIMARY KEY,
    "question_text" varchar(200) NOT NULL,
    "pub_date" timestamp with time zone NOT NULL
);
--
-- Add field question to choice
--
ALTER TABLE "polls_choice" ADD COLUMN "question_id" integer NOT NULL;
ALTER TABLE "polls_choice" ALTER COLUMN "question_id" DROP DEFAULT;
CREATE INDEX "polls_choice_7aa0f6ee" ON "polls_choice" ("question_id");
ALTER TABLE "polls_choice"
  ADD CONSTRAINT "polls_choice_question_id_246c99a640fbbd72_fk_polls_question_id"
    FOREIGN KEY ("question_id")
    REFERENCES "polls_question" ("id")
    DEFERRABLE INITIALLY DEFERRED;

COMMIT;

Run the following command to create a data model for the table

python manage.py migrate
  1. Shell API
    executed in the same directory manage.py, python manage.py shellinto a shell command interface,
    may be model operation.

    # Import the model classes we just wrote.
    >>> from polls.models import Question, Choice   
    # No questions are in the system yet.
    >>> Question.objects.all()
    	<QuerySet []>
    # Create a new Question.
    # Support for time zones is enabled in the default settings file, so
    # Django expects a datetime with tzinfo for pub_date. Use 				 		timezone.now()
    # instead of datetime.datetime.now() and it will do the right thing.
    >>> from django.utils import timezone
    >>> q = Question(question_text="What's new?", 				
    >>>pub_date=timezone.now())
    
    # Save the object into the database. You have to call save() explicitly.
    >>> q.save()
    
    # Now it has an ID. Note that this might say "1L" instead of "1", depending
    # on which database you're using. That's no biggie; it just means your
    # database backend prefers to return integers as Python long integer
    # objects.
    >>> q.id
    	1
    
    # Access model field values via Python attributes.
    >>> q.question_text
    "What's new?"
    >>> q.pub_date
    datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)
    
    # Change values by changing the attributes, then calling save().
    >>> q.question_text = "What's up?"
    >>> q.save()
    
    # objects.all() displays all the questions in the database.
    >>> Question.objects.all()
    <QuerySet [<Question: Question object>]>
    
    1. Django Admin

      Create a super administrator

			执行第一个命令,根据提示完成超级管理员的创建
			 python manage.py createsuperuser
			
			执行以下命令,启动项目
		 	python manage.py runserver
	
			然后在在浏览器访问127.0.0.1:8000(根据自己设置的ip和端口访问),将出现以下页面

Here Insert Picture Description
Enter the steps to create a user name and password to access the following pages.
the admin page

For the first time to enter the page does not exist POLLs labels, admin.py add the following code to refresh the page to see POLLS tab bar.

admin.site.register(Poll)

GIT source address: https://gitee.com/UniQue006/django_mysite.git

Guess you like

Origin blog.csdn.net/qq_32662595/article/details/85251608