Django learning notes, django learning notes

Source: Internet
Author: User
Tags install django mysql import pip install django

Django learning notes, django learning notes
1. Django Intor2. Django Install(1) PIP Installation

sudo apt-get isntall python-pipsudo pip install Django
(2) source code Installation
/usr/local/share/Django/Django-1.8.3.tar.gzDjango-1.8.3├── AUTHORS├── build├── dist├── django├── Django.egg-info├── docs├── extras├── INSTALL├── LICENSE├── MANIFEST.in├── PKG-INFO├── README.rst├── scripts├── setup.cfg├── setup.py└── tests
sudo python setup.py install 
3. Django Project(1) create a project
root@kallen:Django#django-admin startproject MyProjroot@kallen:Django# tree MyProj/MyProj/├── manage.py└── MyProj    ├── __init__.py    ├── settings.py    ├── urls.py    └── wsgi.py

_ Init _. py: The Django Project is a Python package, which is used to tell the Python folder as a package. In Python terminology, a package is a set of modules used to group similar files to prevent name conflicts.

Manage. py: This step is used to manage your project, you can think of it as the django-admin.py version of your project, in fact, manage. py and django-admin.py are sharing the same background code.

Settings. py: This is the main configuration file of the Django project. In this file, you can describe many options, including database settings, Web language, and the need to turn
Django function of on.

Urls. py: This is another configuration file. You can think of it as a match between URLS and the Python method used to process them;

Http://www.cnblogs.com/bluescorpio/archive/2009/11/28/1612805.html)

(2) create an application
root@kallen:Django#python manage.py startapp jobs└── MyProj    ├── jobs    │   ├── admin.py    │   ├── __init__.py    │   ├── migrations    │   │   └── __init__.py    │   ├── models.py    │   ├── tests.py    │   └── views.py    ├── manage.py    └── MyProj
(3) create an object class
from django.db import modelsclass Job(models.Model):    pub_date = models.DateField()    job_title = models.CharField(max_length=50)    job_description = models.TextField()    location = models.ForeignKey(Location)    def __str__(self):        return "%s (%s)" % (self.job_title, self.location)  
(4) view the database mode
root@kallen:/home/kallen/Python/Django/MyProj# python manage.py sql jobsBEGIN;CREATE TABLE `jobs_location` (    `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,    `city` varchar(50)NOT NULL,    `state` varchar(50),    `country` varchar(50)NOT NULL);CREATE TABLE `jobs_job` (    `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,    `pub_date` date NOT NULL,    `job_title` varchar(50)NOT NULL,    `job_description` longtext NOT NULL,    `location_id` integerNOT NULL);ALTER TABLE `jobs_job` ADD CONSTRAINT `location_id_refs_id_35f2feb6` FOREIGN KEY (`location_id`) REFERENCES `jobs_location` (`id`);COMMIT;

[Common Errors]

$ python manage.py sql jobsCommandError: App 'jobs' has migrations. Only the sqlmigrate and sqlflush commandscan be used when an app has migrations.

[Solution] Delete the migrations under jobs;

(5) Check the database mode
root@kallen:/home/kallen/Python/Django/MyProj#python manage.py validate/usr/local/lib/python2.7/dist-packages/Django-1.8.3-py2.7.egg/django/core/management/commands/validate.py:15: RemovedInDjango19Warning:"validate" has been deprecated in favor of"check".RemovedInDjango19Warning)System check identified no issues (0 silenced).root@kallen:/home/kallen/Python/Django/MyProj#python manage.py makemigrationsMigrations for 'jobs':0001_initial.py:- Create model Job- Create model Location- Add field location to jobroot@kallen:/home/kallen/Python/Django/MyProj#python manage.py migrateOperations to perform:  Synchronize unmigrated apps: staticfiles, messages  Apply all migrations: admin, contenttypes, jobs, auth, sessionsSynchronizing apps without migrations:  Creating tables...    Running deferred SQL...  Installing custom SQL...Running migrations:  Rendering model states... DONE  Applying jobs.0001_initial... OK
(6) start the test Server
root@kallen:/home/kallen/Python/Django/MyProj#python manage.py runserverPerforming system checks...System check identified no issues (0 silenced).You have unapplied migrations; your app may not work properly until they are applied.Run 'python manage.py migrate' to apply them.August 14,2015-05:55:23Django version 1.8.3, using settings 'MyProj.settings'Starting development server at http://127.0.0.1:8000/Quit the server with CONTROL-C.
(7) Background Management
root@kallen:/home/kallen/Python/Django/MyProj#python manage.py syncdb
(8) register the Model
from django.contrib issmport admin# Register your models here.# Register my models of job for mapping # utility class Location & Job.# Kallen Ding, Agu 17 2015from .models import Location, Job admin.site.register(Location)admin.site.register(Job) 
4. Django FAQ(1) MySQL import Error
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module

[Solution] install the mysql-python module.

Installation steps:

sudo apt-get install python-setuptoolssudo apt-get install libmysqld-devsudo apt-get install libmysqlclient-dev sudo apt-get install python-devsudo easy_install mysql-python

Test: In the python interactive window, try import MySQLdb. If no error is reported, the installation is successful.

(2) An error occurred while importing the model object.
>>> from jobs.models import Jobdjango.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

[Solution]

>>>from django.conf import settings  >>> settings.configure()
(3) CSRF Verification Failed
Forbidden (403)CSRF verification failed. Request aborted.HelpReason given for failure:    CSRF token missing or incorrect.In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:Your browser is accepting cookies.The view function passes a request to the template's render method.In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.You're seeing the help section of this page because you have DEBUG =Truein your Django settings file. Change that to False, and only the initial error message will be displayed.You can customize this page using the CSRF_FAILURE_VIEW setting.

[Solution]

First: add{% csrf_token %}That's all;

Method 2: add the configuration in MIDDLEWARE_CLASSES in Settings:

'django.middleware.csrf.CsrfViewMiddleware','django.middleware.csrf.CsrfResponseMiddleware',

Method 2 is not feasible:

ImportError: Module "django.middleware.csrf" does not define a "CsrfResponseMiddleware" attribute/class

In the test environment, you only need to comment the two lines;

[Reference]

Http://queengina.com/2014/10/15/Django%E7%B3%BB%E5%88%97%EF%BC%88%E4%BA%8C%EF%BC%89/

Http://stackoverflow.com/questions/6315960/djangos-querydict-bizarre-behavior-bunches-post-dictionary-into-a-single-key

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger | Copyright©2011-2015, Kallen Ding, All Rights Reserved.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.