Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

  1. Open up settings.py on your project, and you can see the default database settings like below

    Code Block
    titlesettings.py
    # Database
    # https://docs.djangoproject.com/en/2.1/ref/settings/#databases
    
    
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }

    If you want to use mysql instead of sqlite3, you can use it by replacing as "django.db.backends.mysql". For oracle, it will be "django.db.backends.oracle". 
    If you are not using SQLite as your database, additional settings such as USER, PASSWORD, and HOST must be added. For more details, see the reference documentation for DATABASES.
    Example)

    Code Block
    languagepy
    titlesettings.py
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql',
            'USER': 'mydatabaseuser',
            'NAME': 'mydatabase',
            'TEST': {
                'NAME': 'mytestdatabase',
            },
        },
    }


    Once you set all your requirements, you should run following command.

    Code Block
    python manage.py migrate


  2. Creating models for online poll.

    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:

    Code Block
    titlepolls/models.py
    from django.db import models
    
    # Create your models here.
    class Question(models.Model):
        question_text = models.CharField(max_length=200)
        pub_date = models.DateTimeField('date published')
        def __str__(self):
            return self.question_text
    
    class Choice(models.Model):
        question = models.ForeignKey(Question, on_delete=models.CASCADE)
        choice_text = models.CharField(max_length=200)
        votes = models.IntegerField(default=0)
        def __str__(self):
            return self.choice_text

    If you see above, it looks like a table schema when we create a table in database. I won't elaborate the detail about above for this time.

  3. Activating models
    Even though we have created an app at the moment, but actually we can't say "polls" are correctly integrated with the project. In django, we should make some additional action to make it happen.
    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,

    Code Block
    languagepy
    titlepolls/apps.py
    from django.apps import AppConfig
    
    class PollsConfig(AppConfig):
        name = 'polls'


    so its dotted path is 'polls.apps.PollsConfig'. Edit the <your project folder>/settings.py file and add that dotted path to the INSTALLED_APPS setting. It’ll look like this:

    Code Block
    title<your project folder>/settings.py
    INSTALLED_APPS = [
        'polls.apps.PollsConfig',
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
    ]

    Note that 'polls.apps.PollsConfig' is added on top of 'django.contrib.admin'.

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

    Code Block
    python manage.py makemigrations polls

    As a result, you should see similar to the following

    Code Block
    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. You can read the migration for your new model if you like; it’s the file polls/migrations/0001_initial.py. Don’t worry, you’re not expected to read them every time Django makes one, but they’re designed to be human-editable in case you want to manually tweak how Django changes things.

    There’s a command that will run the migrations for you and manage your database schema automatically - that’s called migrate, and we’ll come to it in a moment - but first, let’s see what SQL that migration would run. The sqlmigrate command takes migration names and returns their SQL:

    Code Block
    python manage.py sqlmigrate polls 0001

    As a result, you should see similar to the following

    Code Block
    languagesql
    BEGIN;
    --
    -- Create model Choice
    --
    CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL);
    --
    -- Create model Question
    --
    CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);
    --
    -- Add field question to choice
    --
    ALTER TABLE "polls_choice" RENAME TO "polls_choice__old";
    CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" integer NOT NULL REFERENCES "polls_question" ("id") DEFERRABLE INITIALLY DEFERRED);
    INSERT INTO "polls_choice" ("id", "choice_text", "votes", "question_id") SELECT "id", "choice_text", "votes", NULL FROM "polls_choice__old";
    DROP TABLE "polls_choice__old";
    CREATE INDEX "polls_choice_question_id_c5b4b260" ON "polls_choice" ("question_id");
    COMMIT;

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

    Code Block
    python manage.py migrate

    You will see following similar results if everything goes fine.

    Code Block
    Operations to perform:
      Apply all migrations: admin, auth, contenttypes, polls, sessions
    Running migrations:
      Applying polls.0001_initial... OK


    Info

    But for now, remember the three-step guide to making model changes:

    1. Change your models (in models.py).

    2. Run python manage.py makemigrations to create migrations for those changes

    3. Run python manage.py migrate to apply those changes to the database.


  4. Playing with the API
    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:

    Code Block
    python manage.py shell

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

    Code Block
    >>> from polls.models import Choice, Question
    >>> Question.objects.all()
    <QuerySet []>
    >>> from django.utils import timezone
    >>> q = Question(question_text="What's new?", pub_date=timezone.now())
    >>> q.save()
    >>> q.id
    1
    >>> q.question_text
    "What's new?"
    >>> q.pub_date
    datetime.datetime(2018, 11, 10, 5, 29, 23, 419109, tzinfo=<UTC>)
    >>> q.question_text = "What's up?"
    >>> q.save()
    >>> Question.objects.all()
    <QuerySet [<Question: Question object (1)>]>

    If everything is okay, you will see the same result except q.pub_date, because that will be based on your current timezone.
    In addition, let us add more features in polls/models.py like below

    Code Block
    titlepolls/modes.py
    import datetime
    from django.db import models
    from django.utils import timezone
    
    # Create your models here.
    
    class Question(models.Model):
        question_text = models.CharField(max_length=200)
        pub_date = models.DateTimeField('date published')
        def __str__(self):
            return self.question_text
        def was_published_recently(self):
            return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
    
    
    class Choice(models.Model):
        question = models.ForeignKey(Question, on_delete=models.CASCADE)
        choice_text = models.CharField(max_length=200)
        votes = models.IntegerField(default=0)
        def __str__(self):
            return self.choice_text

    Note that we imported datetime and timezone from django.utils to implement three additional functions on Question and Choice.
    Save these changes and start a new Python interactive shell by running python manage.py shell again:

    Code Block
    >>> from polls.models import Choice, Question
    >>> Question.objects.all()
    <QuerySet [<Question: What's up?>]>
    >>> Question.objects.filter(id=1)
    <QuerySet [<Question: What's up?>]>
    >>> Question.objects.filter(question_text__startswith='What')
    <QuerySet [<Question: What's up?>]>
    >>> from django.utils import timezone
    >>> current_year = timezone.now().year
    >>> Question.objects.get(pub_date__year=current_year)
    <Question: What's up?>
    >>> Question.objects.get(id=2)
    Traceback (most recent call last):
      File "<console>", line 1, in <module>
      File "/Users/..../env/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
        return getattr(self.get_queryset(), name)(*args, **kwargs)
      File "/Users/..../env/lib/python3.7/site-packages/django/db/models/query.py", line 399, in get
        self.model._meta.object_name
    polls.models.Question.DoesNotExist: Question matching query does not exist.
    >>> Question.objects.get(pk=1)
    <Question: What's up?>
    >>> q = Question.objects.get(pk=1)
    >>> q.was_published_recently()
    True
    >>> q = Question.objects.get(pk=1)
    >>> q.choice_set.all()
    <QuerySet []>
    >>> 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)
    >>> c.question
    <Question: What's up?>
    >>> q.choice_set.all()
    <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
    >>> q.choice_set.count()
    3
    >>> Choice.objects.filter(question__pub_date__year=current_year)
    <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
    >>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
    >>> c.delete()
    (1, {'polls.Choice': 1})


  5. Creating an admin user

    First we’ll need to create a user who can login to the admin site. Run the following command:

    Code Block
    python manage.py createsuperuser

    Enter your desired username and press enter.

    Code Block
    Username: admin

    You will then be prompted for your desired email address:

    Code Block
    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.

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


  6. 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:

    Code Block
    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:

    Image Added

  7. Enter the admin site
    If everything is okay, you will see following screen

    Image Added

  8. Make the poll app modifiable in the admin
    Even though we created an app, that is not appeared 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:

    Code Block
    from django.contrib import admin
    
    
    # Register your models here.
    from .models import Question
    
    admin.site.register(Question)


  9. Explore the free admin functionality 

    Now that we’ve registered Question, Django knows that it should be displayed on the admin index page:

    Image Added

    Click “Questions”. Now you’re at the “change list” page for questions. This page displays all the questions in the database and lets you choose one to change it. There’s the “What’s up?” question we created earlier:
    Image Added
    Click the “What’s up?” question to edit it:
    Image Added
    Note that the form is automatically generated from the Question model. I haven't seen such a kind software model in another software languages.