- Quick install guide
1.1 Install Python, it works with Python2.6, 2.7, 3.2, 3.3. All these version of Python include a lightweight database SQLite, so you don't need to setup a database
1.2 Remove any old versions of Django: if you are upgrading your installation of Django from a previous version, you will need to uninstall the old version before installing the new version
1.3 If you previously installed Django using python setup.py install, uninstalling is as simple as deleting the Django directory from your Python site-packages.
1.4 To find the directory you need to remove, you can run the following at your shell prompt(not the interactive Python prompt): python -c "import sys; sys.path = sys.path[1:]; import django; print(django.__path__)"
1.5 Install the Django code: install pip, and use “sudo pip install Django”(on Linux or Mac OS) or “pip install Django”(on Windows), or specific the version: “pip install Django==1.6.3”
1.6 Installing an official release manually: download the latest version, and use “python setup.py install”
1.7 Verifying: import Django, print Django.get_version()
- Creating a project: from the command line, cd into a directory where you want to store your code, then run the following command: django-admin.py startproject mysite this will create a mysite directory in your current directory
- Note: you’ll need to avoid naming projects after built-in Python or Django components. In particular, this means you should avoid using names like Django or test
- The outer mysite/ root directory is just a container for your project. Its name doesn’t matter to Django. You can rename it to anything you like.
- Manage.py: A command-line utility that lets you interact with this Django project in various ways.
- The inner mysite/ ditrectory is the actual Python package for your project. Its name is the Python package name you’ll need to use to import anything inside it(e.g. mysite.urls)
- Mysite/__init__.py: an empty file that tells Python that this directory should be considered as Python package.
- Mysite/settings.py: Setting/configuration for this Django project.
- Mysite/urls.py: The URL declarations for this Django project; a “table of contents” of your Django-powered site.
- Mysite/wsgi.py: an entry-point for WSGI-compatible web servers to serve your project.
- Change into the outer mysite directory, run the command python manage.py runserver, now that the server is running, visit http://localhost:8000 with your web browser. You’ll see “Welcome to Django” page.
- By default, the runserver command starts the development server on the internal IP at port 8080
- If you want to change the server’s port, pass it as a command-line argument. For instance, this commands starts the server on port 8000: pythin manage.py runserver 8000
- If you want to change the server’s IP, pass it along with the port, so to listen on all public IPs(useful if you want to show off your work on other computers), use: python manage.py runserver 0.0.0.0: 8000
- By default, the configuration(mysite/settings.py) uses SQLite.
- If you wish to use another database, change the following keys in the DATABASE’default’ item to match your database connection settings:
16.1 ENGINE – either ‘django.db.backends.sqlite3’, ‘django.db.backends.postgresql_psycopq2’, ‘django.db.backends.mysql’, or ‘django.db.backends.oracle’
16.2 NAME – the name of your database. If you are using SQLite, the database will be a file on your computer; in that case, NAME should be the full absolute path, including filename, of that file. The default value, ‘os.path.join(BASE_DIR, ‘db.sqlite3’)’, will store the file in your project directory
- Note the INSTALLED_APPS setting at the top of the file. That holds the names of all Django applications that are activated in this Django instance.
- By default, INSTALLED_APPS contains the following apps, all of which come with Django:
18.1 django.contrib.admin – the admin site
18.2 django.contrib.auth – An authentication system
18.3 django.contrib.contenttype – a framework for content types
18.4 django.contrib.sessions – a session framework
18.5 django.contrib.messages – a messaging framework
18.6 django.contrib.staticfiles – a framework for managing static files
- some of these applications makes use of at least one database table, though. So we need to create the tables in the database before we can use them. To do that, run the following command: python manage.py syncdb
- the syncdb command looks at the INSTALLED_APPS setting and creates any necessary database tables according to the database settings in your mysite/settings.py file. You’ll see a message for each database table it creates
- the default applications are included for the common case, but not everybody needs them. If you don’t need any or all of them. Feel free to comment-out or delete the appropriate line(s) from INSTALLED_APPS before running syncdb. The syncdb command will only create tables for apps in INSTALLED_APP
- what’s the difference between a project and an app? An App is a web application that does something – e.g. a weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular Web site. A project can contain multiple apps. An app can be in multiple projects.
- Your apps can live anywhere on your Python path.
- To create your app, make sure you are in the same directory as manage.py and type this command: python manage.py startapp polls
- The first step in writing a database web application in Django is to define your models – essentially, your database layout, with additional metadata
- A model is the single, definitive source of data about your data. It contains the essential fields and behaviors of the data you’re storing. Django follows the DRY principle. The goal is to define your data model in one place and automatically derive things from it.
- Each model is represented by a class that subclass Django.db.models.Model. each model has a number of class variables, each of which represents a database field in the model.
- Each field is represented by an instance of a Field class – e.g., CharField for character fields and DateTimeField for datetimes. This tells Django what type of data each field holds.
- The name of each Field instance is the field’s name, in machine-friendly format. You’ll use this value in your Pytohn code, and your database will use it as the column name.
- Django supports all the common database relationships: many-to-ones, many-to-manys and one-to-ones.
- Django apps are “plugable”: you can use an app in multiple projects, and you can distribute apps, because they don’t have to be tied to a given Django installation
- And your app to INSTALLED_APPS and run “python mange.py sql your_app”
- Python manage.py validate – Checks for any errors in the construction of your models
- Python manage.py sqlcustom polls – Outputs any custom SQL statement (such as table modifications or constraints) that are defined for the application.
- Python mange.py sqlclear polls – Outputs the necessary DROP TABLE statements for this app, according to which tables already exist in your database (if any)
- Python manage.py sqlindexes polls – Output the CREATE INDEX statements for this app.
- Python manage.py sqlall polls – a combination of all the SQL from the sql, sqlcustom and sqlindexes commands
- Run syncdb again to create those model tables in your database: python manage.py syncdb
- Syncdb can be called as often as you can, and it will only ever create the tables that don't exist.
- To invoke the Python shell, use this command: python manage.py shell
- We are using this instead of simply typing “python”, because manage.py sets the DJANGO_SETTING_MODULE environment variable, which gives Django the Python import path to your mysite/settings.py file
- It’s important to add __unicode__ methods (or __str__() on Python 3) to your modules, not only for your own sanity when dealing with the interactive prompt, but also because object’s representations are used to throughout Django’s automatically generated admin.
- We use __unicode__ because Django models deal with Unicode by default. All data stored in your database is converted to Unicode when it’s returned.
- Django models have a default __str__() method that calls __unicode__() and converts the result to a UTF-8 bytestring. This means that Unicode(p) will return a Unicode string, and str(p) will return a normal string, with character encoded as UTF-8.
- Creating superusers: python manage.py createsuperuser –username=joe –[email protected]
- Visit admin site: http://localhost:8000/admin
- Make the poll app modifiable in the admin: we need to tell the admin that Poll objects have an admin interface. (edit polls/admin.py)
- The different model field types(DateTimeField, CharField) correspond to the appropriate HTML input widget. Each type of field knows how to display itself in the Django admin.
- Create a model admin object, then pass ot as the second argument to admin.site.register() – any time you need to change the admin options for an object.
- You can assign arbitrary HTML classes to each fieldset. Django provides a “collapse” class that displays a particular fieldset initially collapsed.
- Django knows that a ForeignKey should be represented in the admin as a <select> box.
- By default, Django displays the str() of each object.
- Use the list_display admin option, which is a tuple of field names to display, as columns, on the change list page for the object.
- You can click on the column headers to sort by those values – except in the case of the was_published_recently header, because sorting by the output of an arbitrary methods is not supported.
- Create a templates directory in your project directory. Template can live anywhere on your filesystem that Django can access.
- Open you settings file (mysite/settings.py), and add a TEMPLATE_DIRS setting:
TEMPLATE_DIR = [os.path.join(BASE_DIR, 'templates')]
TEMPLATE_DIR is an iterable of filesystem directories to check when loading Django templates; it’s a search path.
- But if TEMPLATE_DIRS was empty by default, how was Django finding the default admin templates? The answer is that, by default, Django automatically looks for a templates/subdirectory within each application package, for use as a fallback.
- By default, it displays all the apps in INSTALLED_APPS that have been registered with the admin application, in alphabetical order.
- Edit admin/index.html, app_list, the variable contains every installed Django app.
- A view is a “type” of Web page in your Django application that generally serves a specific function and has a specific template.
- In Django, web pages and other content are delivered by views. Each view is represented by a simple Python function (or method, in the case of class-based views). Django will choose a view by examining the URL that’s requested (to be precise, the part of the URL after the domain name).
- A URL pattern is simply the general form of a URL.
- To get from a URL to a view, Django uses what we are known as “URLconfs”. A URLconf maps URL patterns (described as regular expressions) to views.
- To call the view, we need to map it to a URL – and for this, we need a URLconf.
- The url() function is passed 4 arguments, two required: regex and view, and two optional: kwargs, and name.
- url() argument: regex: Django starts at the first regular expression and makes its way down the list, comparing the requested URL against each regular expression until it finds one that matches.
- url() argument: view: when Django finds a regular expression match, Django calls the specified view function, with an HttpRequest object as the first argument and any “captured” values from the regular expression as other arguments. If the regex uses simple captures, values are passed as positional arguments; if it uses named captures, values are passed as keyword arguments.
- url() argument: name: Naming your URL lets you refer to it unambiguously from elsewhere in Django especially templates.
- When somebody requests a page from your web site, Django will load the mysite.urls Python module because it’s pointed to by the ROOT_URLCONF setting. It finds the variable named urlpatterns and traverses the regular expressions in order. The include() functions we are using simply reference other URLconfs.
- Each view is responsible for doing one of two things: returning an HtppResponse object containing the content for the requested page, or raising an exception such as Http404
- All Django wants is that HttpResponse. Or an exception.
- Django’s TEMPLATE_LOADERS setting contains a list of callables that know how to import templates from various sources. One of the defaults is Django.template.loaders.app_directories.Loader which looks for a “template” subdirectory in each of the INSTALLED_APPS
- The render() function takes the request object as its first argument, a template name as its second argument and a directory as its optional argument. It returns an HttpResponse object of the given template rendered with the given context.
- The get_object_or_404 function takes a Django model as its first argument and an arbitrary number of keyword arguments, which it passes to the get() function of the models’s manager. It raises Http404 if the object doesn't exist.
- There is also a get_list_or_404() function, which works just as get_object_or_404() – except using filter() instead of get(). It raises Http404 if the list is empty.
- The template system uses dot-lookup syntax to access variable attributes.
- Namespacing URL names: the answer is to add namespaces to your root URLconf. In the mysite/urls.py (the project’s urls.py, not the application’s)
- Request.POST is a dictionary-like object that lets you access submitted data by key name. a string request.POST values are always string. Note that Django also provides request.GE for accessing GET data in the same way
- Reverse() function in the HttpResponseRedirect helps avoid having to hardcode a URL in the view function. It is given name of the view that we want to pass control to and the variable portion of the URL pattern that points to that view.
- ListView and DetaiView. Respectively, those two views abstract the concepts of “display a list of objects” and “display a detail page for a particular type of object”
- Each generic view needs to know what model it will be acting upon. This is provided using the model attribute.
- The DetailView generic view expects the primary key value captured from the URL to be called “pk”, so we’ve changed poll_id to pk for the generic views.
- By default, the DetailView generic view uses a template called <app name>/<model name>_detail.html
- A conventional place for an application’s tests in the application’s tests.py file; the testing system will automatically find tests in any file whose name begins with test.
- Running tests: python manage.py test polls
- Django provides a test Client to simulate a user interacting with the code at the view level. We can use it in tests.py or even in the shell.
- Django will look for static files in static folder
- Django’s STATICFILES_FIN?DERS setting contains a list of finders that know how to discover static files from various source. One of the defaults is AppDirectoriesFinder which looks for a “static” subdirectory in each of the INSTALLED_APPS.