Showing posts with label Django. Show all posts
Explain what is Django?

Django is a web framework in python to develop a web application in python.

Mention what are the features available in Django?

Features available in Django are
  • Admin Interface (CRUD)
  • Templating
  • Form handling
  • Internationalization
  • Session, user management, role-based permissions
  • Object-relational mapping (ORM)
  • Testing Framework
  • Fantastic Documentation
 Mention the architecture of Django architecture?

Django architecture consists of
  • Models: It describes your database schema and your data structure
  • Views: It controls what a user sees, the view retrieves data from appropriate models and execute any calculation made to the data and pass it to the template
  • Templates: It determines how the user sees it. It describes how the data received from the views should be changed or formatted for display on the page
  • Controller: The Django framework and URL parsing

Why Django should be used for web-development?
  • It allows you to divide code modules into logical groups to make it flexible to change
  • To ease the website administration, it provides auto-generated web admin
  • It provides pre-packaged API for common user tasks
  • It gives you template system to define HTML template for your web page to avoid code duplication
  • It enables you to define what URL be for a given function
  • It enables you to separate business logic from the HTML
  • Everything is in python
Explain how you can create a project in Django?

To start a project in Django, you use command
$ django-admin startproject project_name

project_root
  manage.py
   project
      _init_.py
       settings.py
        urls.py
        wsgi.py




Explain how you can set up the Database in Django?

You can  edit mysite/setting.py 

Django uses SQLite by default; it is easy for Django users as such it won’t require any other type of installation. In the case your database choice is different that you have to the following keys in the DATABASE ‘default’ item to match your database connection settings
  • Engines: you can change database by using ‘django.db.backends.sqlite3’ , ‘django.db.backeneds.mysql’, ‘django.db.backends.postgresql_psycopg2’, ‘django.db.backends.oracle’ and so on
  • Name: The name of your database. In the case if you are using SQLite as your database, in that case database will be a file on your computer, Name should be a full absolute path, including file name of that file.
If you are not choosing SQLite as your database then setting like Password, Host, User, etc. must be added.


ive an example how you can write a VIEW in Django?

Views are Django functions that take a request and return a response .
Views are basically the python function which are responsible for doing the business logic over the data .


Once you have determined the VIEW, you can write  url  line in urls.py

Explain how you can setup static files in Django?

There are three main things required to set up static files in Django
  • Set STATIC_ROOT in settings.py
  • run manage.py collectsatic
  • set up a Static Files entry on the PythonAnywhere web tab

 Mention what does the Django templates consists of?

The template is a simple text file.  It can create any text-based format like XML, CSV, HTML, etc.  A template contains variables that get replaced with values when the template is evaluated and tags (% tag %) that controls the logic of the template.

Explain the use of session framework in Django?

In Django, the session framework enables you to store and retrieve arbitrary data on a per-site-visitor basis.  It stores data on the server side and abstracts the receiving and sending of cookies.  Session can be implemented through a piece of middleware


Explain how you can use file based sessions?

To use file based session you have to set the SESSION_ENGINE settings to “django.contrib.sessions.backends.file”


Explain the migration in Django and how you can do in SQL?

Migration in Django is to make changes to your models like deleting a model, adding a field, etc. into your database schema.  There are several commands you use to interact with migrations.
  • Migrate
  • Makemigrations
  • Sqlmigrate
To do the migration in SQL, you have to print the SQL statement for resetting sequences for a given app name.

django-admin sqlsequencreset

Use this command to generate SQL that will fix cases where a sequence is out sync with its automatically incremented field data.

Mention what command line can be used to load data into Django?

To load data into Django you have to use the command line 

Django-admin loaddata

The command line will searches the data and loads the contents of the named fixtures into the database.

Explain what does django-admin.py makemessages command is used for?

This command line executes over the entire source tree of the current directory and abstracts all the strings marked for translation.  It makes a message file in the locale directory.

  List out the inheritance styles in Django?
In Django, there is three possible inheritance styles
  • Abstract base classes: This style is used when you only wants parent’s class to hold information that you don’t want to type out for each child model
  • Multi-table Inheritance: This style is used If you are sub-classing an existing model and need each model to have its own database table
  • Proxy models: You can use this model, If you only want to modify the Python level behavior of the model, without changing the model’s fields
Mention what does the Django field class types?

Field class types determines
  • The database column type
  • The default HTML widget to avail while rendering a form field
  • The minimal validation requirements used in Django admin and in automatically generated forms
First we’ll need to create a user who can login to the admin site. Run the following command:

$ python manage.py createsuperuser 

 

Enter your desired username and press enter.

Username: admin
 
You will then be prompted for your desired email address:

Email address: admin@example.com
 
The final step is to enter your password. You will be asked to enter your password twice, the second time as a confirmation of the first.

Password: **********
Password (again): *********
Superuser created successfully.

Start the development server

The Django admin site is activated by default. Let’s start the development server and explore it.

If the server is not running start it like so:

$ python manage.py runserver
 
Now, open a Web browser and go to “/admin/” on your local domain – e.g.,

http://127.0.0.1:8000/admin/.

 You should see the admin’s login screen:

Make the poll app modifiable in the admin

But where’s our poll app? It’s not displayed on the admin index page.
Just one thing to do: we need to tell the admin that Question objects have an admin interface. To do this, open the polls/admin.py file, and edit it to look like this:
polls/admin.py
from django.contrib import admin

from .models import Question

admin.site.register(Question)

 

Now, let’s hop into the interactive Python shell and play around with the free API Django gives you. To invoke the Python shell, use this command:

$ python manage.py shell

We’re using this instead of simply typing “python”, because manage.py sets the DJANGO_SETTINGS_MODULE environment variable, which gives Django the Python import path to your mysite/settings.py file.

Once you’re in the shell, explore the database API:



>>> from polls.models import Question, Choice   # Import the model classes we just wrote.

# 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>]> 
 
 
>>> from polls.models import Question, Choice

# Make sure our __str__() addition worked.
>>> Question.objects.all()
<QuerySet [<Question: What's up?>]>

# Django provides a rich database lookup API that's entirely driven by
# keyword arguments.
>>> Question.objects.filter(id=1)
<QuerySet [<Question: What's up?>]>
>>> Question.objects.filter(question_text__startswith='What')
<QuerySet [<Question: What's up?>]>

# Get the question that was published this year.
>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Question.objects.get(pub_date__year=current_year)
<Question: What's up?>

# Request an ID that doesn't exist, this will raise an exception.
>>> Question.objects.get(id=2)
Traceback (most recent call last):
    ...
DoesNotExist: Question matching query does not exist.

# Lookup by a primary key is the most common case, so Django provides a
# shortcut for primary-key exact lookups.
# The following is identical to Question.objects.get(id=1).
>>> Question.objects.get(pk=1)
<Question: What's up?>

# Make sure our custom method worked.
>>> q = Question.objects.get(pk=1)
>>> q.was_published_recently()
True

# Give the Question a couple of Choices. The create call constructs a new
# Choice object, does the INSERT statement, adds the choice to the set
# of available choices and returns the new Choice object. Django creates
# a set to hold the "other side" of a ForeignKey relation
# (e.g. a question's choice) which can be accessed via the API.
>>> q = Question.objects.get(pk=1)

# Display any choices from the related object set -- none so far.
>>> q.choice_set.all()
<QuerySet []>

# Create three choices.
>>> q.choice_set.create(choice_text='Not much', votes=0)
<Choice: Not much>
>>> q.choice_set.create(choice_text='The sky', votes=0)
<Choice: The sky>
>>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)

# Choice objects have API access to their related Question objects.
>>> c.question
<Question: What's up?>

# And vice versa: Question objects get access to Choice objects.
>>> q.choice_set.all()
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
>>> q.choice_set.count()
3

# The API automatically follows relationships as far as you need.
# Use double underscores to separate relationships.
# This works as many levels deep as you want; there's no limit.
# Find all Choices for any question whose pub_date is in this year
# (reusing the 'current_year' variable we created above).
>>> Choice.objects.filter(question__pub_date__year=current_year)
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>

# Let's delete one of the choices. Use delete() for that.
>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
>>> c.delete() 
 
    def __str__(self):
        return self.choice_text         

difference between filter and get django ?

  • if you know it's one object that matches your query, use get. It will fail if it's more than one.
  • otherwise use filter, which gives you a list of objects

Database setup

Now, open up mysite/settings.py.

By default, the configuration uses SQLite. SQLite is included in Python, so you won’t need to install anything else to support your database while starting your first real project .

If you wish to use another database, install the appropriate database and change the following keys in the DATABASES 'default' item to match your database connection settings:
  • ENGINE – Either 'django.db.backends.sqlite3', 'django.db.backends.postgresql', 'django.db.backends.mysql', or 'django.db.backends.oracle'. Other backends are also available.
  • NAME – The name of your database. If you’re 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.
If you are not using SQLite as your database, additional settings such as USER, PASSWORD, and HOST must be added.


This example is for PostgreSQL:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydatabase',
        'USER': 'mydatabaseuser',
        'PASSWORD': 'mypassword',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}


ENGINE


The database backend to use. The built-in database backends are:
  • 'django.db.backends.postgresql'
  • 'django.db.backends.mysql'
  • 'django.db.backends.sqlite3'
  • 'django.db.backends.oracle'


While you’re editing mysite/settings.py, set TIME_ZONE to your time zone.

Also, 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 .

ute them for use by others in their projects.
By default, INSTALLED_APPS contains the following apps, all of which come with Django:
These applications are included by default as a convenience for the common case.

Some of these applications make 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 migrate

 
The migrate command looks at the INSTALLED_APPS setting and creates any necessary database tables according to the database settings in your mysite/settings.py file .


Note :The migrate command will only run migrations for apps in INSTALLED_APPS.

Creating models :

Now we’ll define your models – essentially, your database layout, with additional metadata.

A model contains the essential fields and behaviors of the data you’re storing .

In our simple poll app, we’ll create two models: Question and Choice. A Question has a question and a publication date. A Choice has two fields: the text of the choice and a vote tally. Each Choice is associated with a Question.

These concepts are represented by simple Python classes. Edit the polls/models.py file so it looks like this:

polls/models.py
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):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)


Activating models

 First we need to tell our project that the polls app is installed.

To include the app in our project, we need to add a reference to its configuration class in the INSTALLED_APPS setting. 

The PollsConfig class is in the polls/apps.py file, so its dotted path is 'polls.apps.PollsConfig'. 

Edit the mysite/settings.py file and add that dotted path to the INSTALLED_APPS setting.

INSTALLED_APPS = [
    'polls.apps.PollsConfig',
] 



Now Django knows to include the polls app. Let’s run another command:

$ python manage.py makemigrations polls

You should see something similar to the following:

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

By running makemigrations, you’re telling Django that you’ve made some changes to your models (in this case, you’ve made new ones) and that you’d like the changes to be stored as a migration.

Migrations are how Django stores changes to your models (and thus your database schema) - they’re just files on disk .


Note the following:

Table names are automatically generated by combining the name of the app (polls) and the lowercase name of the model – question and choice. (You can override this behavior.)

Primary keys (IDs) are added automatically. (You can override this, too.)

By convention, Django appends "_id" to the foreign key field name. (Yes, you can override this, as well.)

The foreign key relationship is made explicit by a FOREIGN KEY constraint

The sqlmigrate command doesn’t actually run the migration on your database - it just prints it to the screen so that you can see what SQL Django thinks is required. It’s useful for checking what Django is going to do or if you have database administrators who require SQL scripts for changes.

$ python manage.py sqlmigrate polls 0001

If you’re interested, you can also run 

python manage.py check; 

this checks for any problems in your project without making migrations or touching the database.

Now, run migrate again to create those model tables in your database:

$ python manage.py migrate


The migrate command takes all the migrations that haven’t been applied (Django tracks which ones are applied using a special table in your database called django_migrations) and runs them against your database - essentially, synchronizing the changes you made to your models with the schema in the database.

remember the three-step guide to making model changes:

 

 
Throughout this tutorial, we’ll walk you through the creation of a basic poll application.
It’ll consist of two parts:
  • A public site that lets people view polls and vote in them.
  • An admin site that lets you add, change, and delete polls.

You can tell Django is installed and which version by running the following command:

$ python -m django --version

Creating a project

You’ll need to auto-generate some code that establishes a Django project – a collection of settings for an instance of Django, including database configuration, Django-specific options and application-specific settings.

From the command line, cd into a directory where you’d like to store your code, then run the following command:

$ django-admin startproject mysite 

 

This will create a mysite directory in your current directory.

Let’s look at what startproject created:

mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        wsgi.py


These files are:
  • 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/ directory 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 a Python package.
  • mysite/settings.py: Settings/configuration for this Django project. 
  • mysite/urls.py: The URL declarations for this Django project; a “table of contents” of your Django-powered site. URL dispatcher.
  • mysite/wsgi.py: An entry-point for WSGI-compatible web servers to serve your project. 

The development server

 Change into the outer mysite directory, if you haven’t already, and run the following commands:

$ python manage.py runserver 

    or 

$./manage.py runserver 

(Note : don't need to prefix python each time)

You’ve started the Django development server, a lightweight Web server written purely in Python.

Now that the server’s running, visit http://127.0.0.1:8000/ with your Web browser. 
 
You’ll see a “Welcome to Django” page, in pleasant, light-blue pastel. It worked!
 
 
Changing the port

By default, the runserver command starts the development server on the internal IP at port 8000.
 
localhost:8000

If you want to change the server’s port, pass it as a command-line argument. For instance, this command starts the server on port 8080:

$ python manage.py runserver 8080

 
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 on your network), use:

$ python manage.py runserver 0.0.0.0:8000 

 

Automatic reloading of Server

The development server automatically reloads Python code for each request as needed. You don’t need to restart the server for code changes to take effect. However, some actions like adding files don’t trigger a restart, so you’ll have to restart the server in these cases.

Creating the Polls app :

Django comes with a utility that automatically generates the basic directory structure of an app, so you can focus on writing code rather than creating directories.

To create your app, make sure you’re in the same directory as manage.py and type this command:

$ python manage.py startapp polls 

or 

$ django-admin startapp polls

Projects vs. apps :

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 website.

 A project can contain multiple apps. An app can be in multiple projects.


This directory structure will house the poll application.

polls/
    __init__.py
    admin.py
    apps.py
    migrations/
        __init__.py
    models.py
    tests.py
    views.py
 
 

Write your first view :


Let’s write the first view. Open the file polls/views.py and put the following Python code in it:

polls/views.py

from django.http import HttpResponse 

def index(request):   

    return HttpResponse("Hello, world. You're at the polls index.")

 

To call the view, we need to map it to a URL - and for this we need a URLconf.
To create a URLconf in the polls directory, create a file called urls.py under polls app .

In the polls/urls.py file include the following code:

polls/urls.py

from django.conf.urls import url  

from . import views 

 urlpatterns = [ 

     url(r'^$', views.index, name='index'), 

]

 

The next step is to point the root URLconf at the polls.urls module. In mysite/urls.py, add an import for django.conf.urls.include and insert an include() in the urlpatterns list, so you have:

mysite/urls.py

from django.conf.urls import include, url  

from django.contrib import admin 

urlpatterns = [ 

     url(r'^polls/', include('polls.urls')), 

    url(r'^admin/', admin.site.urls), 

]

 

The include() function allows referencing other URLconfs. Note that the regular expressions for the include() function doesn’t have a $ (end-of-string match character) but rather a trailing slash. Whenever Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.
 
The idea behind include() is to make it easy to plug-and-play URLs Since polls are in their own URLconf (polls/urls.py) .
 
When to use include() :

You should always use include() when you include other URL patterns. admin.site.urls is the only exception to this.


You have now wired an index view into the URLconf. Lets verify it’s working, run the following command:

$ python manage.py runserver

 
Go to http://localhost:8000/polls/ in your browser, and you should see the text “Hello, world. You’re at the polls index.”, which you defined in the index view.

 
The url() function is passed four arguments, two required: regex and view, and two optional: kwargs, and name.  


 

 





Any text surrounded by a pair of braces (e.g., {{ person_name }}) is a variable.


Any text that’s surrounded by curly braces and percent signs (e.g., {% if ordered_warranty %}) is a template tag tag just tells the template system to “do something.”

eg :
 a for tag {% for item in item_list %} and
 an if tag {% if ordered_warranty %}

 {% else %}
 {% endif %}



 a filter, which is the most convenient way to alter the formatting of a variable. In this example, {{ ship_date|date:"F j, Y" }}, we’re passing the ship_date variable to the date filter, giving the date filter the argument "F j, Y". The date filter formats dates in a given format, as specified by that argument. Filters are attached using a pipe character (|), as a reference to Unix pipes.



    Create a Template object by providing the raw template code as a string.
    Call the render() method of the Template object with a given set of variables (the context). This returns a fully rendered template as a string, with all of the variables and template tags evaluated according to the context.

The Context constructor takes a Python dictionary, which maps variable names to values.

Those are the fundamentals of using the Django template system: just write a template string, create a Template object, create a Context, and call the render() method.

it’s more efficient to create the Template object once, and then call render() on it multiple times:


A view is a place where we put the "logic" of our application. It will request information from the model you created before and pass it to a template. We'll create a template in the next chapter. Views are just Python functions
Let's open up the mysite/urls.py file in your code editor of choice and see what it looks like:

"""mysite URL Configuration

[...]
"""
from django.conf.urls import url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
]

The admin URL, which you visited in previous chapter is already here:

    url(r'^admin/', admin.site.urls),

It means that for every URL that starts with admin/ Django will find a corresponding view(admin panel default by django).

Regular Expresions:
^post/(\d+)/$

    ^post/ is telling Django to take anything that has post/ at the beginning of the url (right after ^)

    (\d+) means that there will be a number (one or more digits) and that we want the number captured and extracted

    / tells django that another / character should follow

    $ then indicates the end of the URL meaning that only strings ending with the / will match this pattern


^ for beginning of the text

$ for end of text

\d for a digit

+ to indicate that the previous item should be repeated at least once

() to capture part of the pattern



Symbol  Matches

. (dot)     Any single character

\d          Any single digit

[A-Z]       Any character between A and Z (uppercase)

[a-z]       Any character between a and z (lowercase)

[A-Za-z]    Any character between a and z (case-insensitive)

+           One or more of the previous expression (e.g., \d+ matches one or more digits)

[^/]+       One or more characters until (and not including) a forward slash

?           Zero or one of the previous expression (e.g., \d? matches zero or one digits)

*           Zero or more of the previous expression (e.g., \d* matches zero, one or more than one digit)

{1,3}       Between one and three (inclusive) of the previous expression (e.g., \d{1,3} matches one, two or three digits)



([0-9]{4} 4digits only


([0-9]{2}) two digits only

'^$/'  empty string

 url(r'^$',

This regular expression will match ^ (a beginning) followed by $ (an end) - so only an empty string will match


Django admin
 
To add, edit and delete posts we've just modeled, we will use Django admin.

Let's open the blog/admin.py file and replace its content with this:

from django.contrib import admin
from .models import Post

admin.site.register(Post)


To make our model visible on the admin page, we need to register the model with admin.site.register(Post).

Go to the browser and type the address http://127.0.0.1:8000/admin/

To log in, you need to create a superuser - a user which has control over everything on the site.

Go back to the command-line and type

 python manage.py createsuperuser


Django models

A model in Django is a special kind of object - it is saved in the database.You can think of a model in the database as a spreadsheet(table)  with columns (fields) and rows (data).


Creating an application

To keep everything tidy, we will create a separate application inside our project.

To create an application we need to run the following command in the console (from djangogirls directory where manage.py file is):

(myvenv) ~/djangogirls$ python manage.py statapp blog



That’ll create a directory blog, which is laid out like this:

blog/

    __init__.py

    admin.py

    apps.py

    migrations/

        __init__.py

    models.py

    tests.py

    views.py

After creating an application we also need to tell Django that it should use it. We do that in the file mysite/settings.py. We need to find INSTALLED_APPS and add a line containing 'blog', just above ). So the final product should look like this:



Creating a blog post model


In the blog/models.py file we define all objects called Models - this is a place in which we will define our blog post.

Let's open blog/models.py, remove everything from it and write code like this:

from django.db import models
from django.utils import timezone


class Post(models.Model):
    author = models.ForeignKey('auth.User')

    title = models.CharField(max_length=200)

    text = models.TextField()

    created_date = models.DateTimeField(
            default=timezone.now)

    published_date = models.DateTimeField(
            blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

class Post(models.Model): - this line defines our model (it is an object).

class is a special keyword that indicates that we are defining an object.

 Post is the name of our model. We can give it a different name (but we must avoid special characters and whitespaces). Always start a class name with an uppercase letter.

 models.Model means that the Post is a Django Model, so Django knows that it should be saved in the database.

Now we define the properties we were talking about: title, text, created_date, published_date and author.

 models.CharField - this is how you define text with a limited number of characters.

  models.TextField - this is for long text without a limit. Sounds ideal for blog post content, right?

  models.DateTimeField - this is a date and time.

  models.ForeignKey - this is a link to another model.



def publish(self):? It is exactly the publish method we were talking about before. def means that this is a function/method and publish is the name of the method



Methods often return something. There is an example of that in the __str__ method. In this scenario, when we call __str__() we will get a text (string) with a Post title.


Create tables for models in your database


The last step here is to add our new model to our database. First we have to make Django know that we have some changes in our model (we have just created it!). Go to your console window and type

python manage.py makemigrations blog


Django prepared for us a migration file that we have to apply now to our database. Type

python manage.py migrate blog


Hurray! Our Post model is now in our database! It would be nice to see it, right?


Django command-line utility to create the database tables automatically:
    python manage.py migrate

The migrate command looks at all your available models and creates tables in your database for whichever tables don’t already exist .

The migrate command looks at the INSTALLED_APPS setting and creates any necessary database tables according to the database settings in your mysite/settings.py file The migrate command will only run migrations for apps in INSTALLED_APPS.


By running makemigrations, you’re telling Django that you’ve made some changes to your models (in this case, you’ve made new ones) and that you’d like the changes to be stored as a migration.

here’s a command that will run the migrations for you and manage your database schema automatically - that’s called migrate


    Change your models (in models.py).
    Run python manage.py makemigrations to create migrations for those changes
    Run python manage.py migrate to apply those changes to the database.
 
The first step is to start a new Django project. Basically, this means that we'll run some scripts provided by Django that will create the skeleton of a Django project for us.

This is just a bunch of directories and files that we will use later.In your MacOS or Linux console you should run the following command; don't forget to add the period (or dot) . at the end:(The period . is crucial because it tells the script to install Django in your current directory (for which the period . is a short-hand reference))


(myvenv) ~/djangoproject$ django-admin startproject mysite .


Note:Remember to run everything in the virtualenv. If you don't see a prefix (myvenv) in your console you need to activate your virtualenv.


Creating a project


django-admin startproject mysite

django-admin.py is a script that will create the directories and files for you. You should now have a directory structure which looks like this:
Let’s look at what startproject created:

mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        wsgi.py


These files are:

    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.  a script that helps with management of the site. With it we will be able to start a web server on our computer without installing anything else,

    The inner mysite/ directory 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 a Python package. (Read more about packages in the official Python docs if you’re a Python beginner.)
   
    mysite/settings.py: Settings/configuration for this Django project.
  
    mysite/urls.py: contains a list of patterns used by urlresolver.
The URL declarations for this Django project; a “table of contents” of your Django-powered site. You can read more about URLs in URL dispatcher.

   
    mysite/wsgi.py: An entry-point for WSGI-compatible web servers to serve your project



Running the Server

Let’s verify your Django project works. Change into the outer mysite directory, if you haven’t already, and run the following commands:

$ python manage.py runserver
or
./manage.py runserver
(Default port 8000)

$ python manage.py runserver 8080
./manage.py runserver  (don\'t need to prefix python  )

$ python manage.py runserver 0.0.0.0:8000  (Toi make it public)



Changing settings
 
Let's make some changes in mysite/settings.py

It would be nice to have the correct time on our website. Go to the wikipedia timezones list and copy your relevant time zone (TZ). (eg. Europe/Berlin )

In settings.py, find the line that contains TIME_ZONE and modify it to choose your own timezone:

TIME_ZONE = 'Europe/Berlin'

We'll also need to add a path for static files
Go down to the end of the file, and just underneath the STATIC_URL entry, add a new one called STATIC_ROOT:

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')



Setup a database

We'll use the default one, sqlite3.

This is already set up in this part of your mysite/settings.py file:

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

To create a database for our blog, let's run the following in the console:
 python manage.py migrate 

(we need to be in the djangoprojects directory that contains the manage.py file

Starting the Server


And we're done! Time to start the web server and see if our website is working!

You need to be in the directory that contains the manage.py file (the djangoprojects directory). In the console, we can start the web server by running python manage.py runserver:

(myvenv) ~/djangoprojects$ python manage.py runserver

http://127.0.0.1:8000/




Congratulations! You've just created your first website and run it using a web server!
What is Django?

Django  is a free and open source web application framework, written in Python.

A web framework is a set of components that helps you to develop websites faster and easier.

Django  give you ready-made components you can use.

Frameworks exist to save you from having to reinvent the wheel and help alleviate some of the overhead when you’re building a new site.

What happens when someone requests a website from your server?

When a request comes to a web server it's passed to Django which tries to figure out what actually is requested. It takes a webpage address first and tries to figure out what to do. This part is done by Django's urlresolver (note that a website address is called a URL - Uniform Resource Locator - so the name urlresolver makes sense). It is not very smart - it takes a list of patterns and tries to match the URL. Django checks patterns from top to the bottom and if something is matched then Django passes the request to the associated function (which is called view).



In the view function all the interesting things are done: we can look at a database to look for some information. The view can check if you are allowed to do that, Then the view generates a response and Django can send it to the user's web browser.

Virtual environment
 
Virtualenv will isolate your Python/Django setup on a per-project basis. This means that any changes you make to one website won't affect any others you're also developing. Neat, right?



All you need to do is find a directory in which you want to create the virtualenv; your home directory

we will be using a new directory djangoproject from your home directory:

mkdir djangoproject
cd djangoproject


We will make a virtualenv called myvenv. The general command will be in the format:

python3 -m venv myvenv

myvenv is the name of your virtualenv. You can use any other name, but stick to lowercase and use no spaces. It is also good idea to keep the name short as you'll be referencing it a lot!

Start your virtual environment by running:


$ source myvenv/bin/activate


NOTE: sometimes source might not be available. In those cases try doing this instead:

$ . myvenv/bin/activate

You will know that you have virtualenv started when you see that the prompt in your console is prefixed with (myvenv).

When working within a virtual environment, python will automatically refer to the correct version so you can use python instead of python3.

OK, we have all important dependencies in place. We can finally install Django!


Installing Django

Now that you have your virtualenv started, you can install Django using pip. In the console, run

pip install django~=1.9.0

or
easy_install django==1.9

That's it! You're now (finally) ready to create a Django application!



 You can tell Django is installed and which version by running the following command:

$ python -c "import django; print(django.get_version())"

or

django-admin --version
python --version
 Creating App :

django-admin startapp appname

  or

./manage.py startapp appname
Find out the version of Python:

python --version


Find out the version of  easy_install / pip:

easy_install --version

 Installing Django :

sudo easy_install django==1.9 or simply django (latest version)

Checkout the Version of Django Installed :

django-admin --version

 or
python -c 'import django; print(django.get_version())'
 
Creating a project
  
django-admin startproject project_name
Running the Project :
  
cd project_name
python manage.py runserver
  or
./manage.py runserver
 
Running the server publicly or changing port :
 
./manage.py runserver 0.0.0.0:8000
 
port no : 127.0.0.1:8000  (By default )
 
 

Copyright © 2013 SoftKul