Category Archives: Django

Django – making changes to a model

Unless you get your model/database structure spot on first time, you’ll want to change it. Here is how to keep the database in line with your Django models

  1. Make a change to your model. For instance, in the books app, to the Author class, add an extra field:
    email_address = models.EmailField()
  2. Create the migrations file: python manage.py makemigrations
  3. Run the migrations file: python manage.py migrate

That’s all. Have a look in the admin panel to see the new field

 

Django – starting with the admin panel

The admin panel lets you manage your models (i.e. the Django data in the database). It is not really meant for use in the production system, but it is very useful during development and for sysadmin

  1. Create a super user (so you can log in)
    1. (DjangoTest) python manage.py createsuperuser
    2. Enter username, email address and password
  2. In your browser, go to http://localhost:8000/admin
  3. Enter the log in details from step 1.
    1. You should now see groups and users. Models you’ve created yourself aren’t there yet
  4. In your books app folder (<dev root>Projects/HelloWorldDjango/books) edit admin.py, add the following:
    from books.models import Book, Author# Register your models here.
    admin.site.register(Author)
    admin.site.register(Book)
  5. Refresh the admin panel in your browser. You should now see all your models

 

Django – create your first model

In Django, a “model” is a Python class which turns database entities into objects. You create the class, and then use it to build the database tables and to add/edit/delete database entities. Here is a brief example

Models are part of “apps”, and apps are part of a project. For instance, a book store system may have an Inventory app, with books, shelves, etc, and a Finance app, with sales, purchases, etc

  1. Create a new app
    1. Start the virtual environment
    2. Switch to the project folder
    3. (DjangoTest) python manage.py startapp books
    4. If all is well, no message will be shown
  2. In your favourite editor, open <dev root>Projects/HelloWorldDjango/books/models.py
    1. Add the following at the end:

      class Author (models.Model):
      first_name = models.CharField(max_length = 30)
      last_name = models.CharField(max_length = 40)class Book(models.Model):
      title = models.CharField(max_length=100)
      authors = models.ManyToManyField(Author)

  3. Add this to the installed apps:
    1. In settings.py, at the end of the INSTALLED_APPS list, add “books, “
  4. Test this: python manage.py validate. You should see: no issues
  5. Set up the minimum required (INSTALLED_APPS) database: python manage.py migrate
  6. Create additional migrations for your new books app: python manage.py makemigrations book
  7. Apply these migrations to the database: python manage.py migrate

 

Django with MySQL

After PostgreSQL, MySQL is probably the most popular DBMS (database management system) used with Django. Here is how I set it up

  1. Install MySQL, etc
    1. Use the Software Manager to install mysql-server (write down the root password you entered here) and phpmyadmin
  2. In your browser, go to http://localhost/phpmyadmin. Enter “root” and the password you wrote down
    1. Note, on my LinuxMint 17 installation I got an error “The mcrypt extension is missing. Please check your PHP configuration”. I used the instructions at http://stackoverflow.com/questions/22721630/the-mcrypt-extension-is-missing-please-check-your-php-configuration to fix this. The commands I used were
      sudo apt-get install mcrypt php5-mcrypt
      php5enmod mcrypt
      sudo service apache2 restart
      The first line may not have been necessary. I made the beginner’s mistake of not using “sudo” at the start of the first line, so apache didn’t actually reboot, until I got this right
  3. Create a database and a user for Django (still in phpmyadmin in your browser)
    1. Second line from the top, click on “Databases”
      1. Create database, enter the name (e.g. “HelloWorldDjango”)
      2. For collation, https://docs.djangoproject.com/en/dev/ref/databases/  suggests using utf8_general_ci, but read the note about case sensitivity
      3. Click on Create
    2. Second line from the top, click on “Users”
      1. Click on “Add user”
      2. Enter the user name – e.g. “DjangoUser” – and write it down
      3. Set the host to “localhost”
      4. Enter a password, or click on the “Generate” button to get a random (and fairly secure) password  and write it down (or copy it into an editor  – you’ll need it soon)
      5. Leave the rest as it is, and click on “Go”
    3. Against your new user, click on the “Edit Privileges” link
      1. Scroll down to the “Database-specific privileges” block, next to “Add privileges on the following database:” click on the “Use text field:” dropdown, and select the new database name (e.g. “HelloWorldDjango”)
      2. At the top of the first box, next to “Database-specific privileges”, click on “Check All”
      3. Click on the “Go” button
    4. Now tell Django to use the database
      1. Open <dev root>Projects/HelloWorldDjango/HelloWorldDjango/settings.py
      2. Replace the 6 lines which start with “DATABASES = {” with:
        DATABASES = {
        ‘default’: {
        ‘ENGINE’: ‘django.db.backends.mysql’,
        ‘NAME’: ‘HelloWorldDjango’,
        ‘USER’: ‘DjangoUser’,
        ‘PASSWORD’: ‘(your password)’,
        ‘HOST’: ‘localhost’, # Or an IP Address that your DB is hosted on
        ‘PORT’: ‘3306’,
        }
        }
    5. Install python-mysql – so Python/Django can access the MySQL database
      1. sudo apt-get install libmysqlclient-dev
      2. sudo apt-get install python-dev
      3. Switch to the virtual env
        source <dev root>/envs/DjangoTest/bin/activate
      4. pip install MySQL-python
    6. And test that it is all working correctly
      1. Still in the virtual env (see previous step)
      2. cd <dev root>Projects/HelloWorldDjango
      3. python manage.py shell
      4. >>> from django.db import connection
      5. >>> cursor = connection.cursor()

Congratulations. You can now create some Django models to start using the database

 

Django – Hello World

Pre-requisites:

  1. easy_install, pip, virtualenv – getting ready for Django
  2. Installing Django

Hello World project in <dev root>/Projects/HelloWorldDjango

  1. Switch to <dev root>/Projects
  2. django-admin.py startproject HelloWordDjango (create the basic project files)
  3. cd HelloWorldDjango
  4. Check if it works so far: python manage.py runserver (start the test server)
  5. Ctrl-C to stop the test server
  6. Create the view: In <dev root>/Projects/HelloWorldDjango/HelloWorldDjango, create a file called “views.py” with the following content:
    from django.http import HttpResponse

    def hello(request):
    return HttpResponse(“Hello world”)

  7. Set the URL:
    1. In <dev root>/Projects/HelloWorldDjango/HelloWorldDjango/urls.py, add the following to the import line:
      from HelloWorldDjango.views import hello
    2. In the same file, add the following to the urlpatters list:
      (‘^hello$’, hello),
  8. Start the test server: in <dev root>/Projects/HelloWorldDjango, python manage.py runserver
  9. In your browser go to http://localhost:8000/hello. This should show you “Hello world”

Installing Django

I like running Django within a virtual environment (for installation instructions see easy_install, pip, virtualenv – getting ready for Django)

I use the following folder structure:

<dev root>
— envs  (short for “environments”)
—– Project 1
—– Project 2
—– etc
— Projects (contains all projects, Django and others)
—– Project 1
—– Project 2
—– etc

Note: not all projects need a virtual environment

To start a new Django project (e.g. called “DjangoTest”):

  1. cd <dev root>
  2. cd envs
  3. virtualenv DjangoTest (create the virtual environment)
  4. source DjangoTest/bin/activate (start using the virtual environment)
  5. pip install Django

easy_install, pip, virtualenv – getting ready for Django

I like running Django within a virtual environment. It gives each project its own set of programmes, libraries, etc. Updating a library for one project then doesn’t affect (and possibly break) all the other projects

For a simple introduction to virtualenv, etc, see http://www.dabapps.com/blog/introduction-to-pip-and-virtualenv-python/

  1. Install easy_install: sudo apt-get install python-setuptools
  2. Install pip: sudo easy_install pip
  3. Install virtualenv: sudo pip install virtualenv