Monday, April 27, 2020

Django pollapp-3 (creating model)

Now we’ll setup the database, create our first model, and get a quick introduction to Django’s automatically-generated admin site.

If you open up pollsite/settings.py you’ll notice that by default, the configuration uses SQLite. SQLite is included in Python, so you won’t need to install anything else to support your database. When starting your first real project, however, you may want to use a more scalable database like PostgreSQL, to avoid database-switching headaches down the road.

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. Apps can be used in multiple projects, and you can package and distribute them for use by others in their projects.

By default, INSTALLED_APPS contains the following apps, all of which come with Django:

django.contrib.admin – The admin site. You’ll use it shortly.
django.contrib.auth – An authentication system.
django.contrib.contenttypes – A framework for content types.
django.contrib.sessions – A session framework.
django.contrib.messages – A messaging framework.
django.contrib.staticfiles – A framework for managing static files.
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

(pollapp_env) C:\Application_django>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying sessions.0001_initial... OK

(pollapp_env) C:\Application_django>

The migrate command looks at the INSTALLED_APPS setting and creates any necessary database tables according to the database settings in your pollsite/settings.py file and the database migrations shipped with the app. You’ll see a message for each migration it applies.

It’s time now to create models. In our 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. Edit the polls/models.py file and add the following code to it:

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)


Each model is represented by a class that subclasses 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 (e.g. question_text or pub_date) is the field’s name, in machine-friendly format. You’ll use this value in your Python code, and your database will use it as the column name.

You can use an optional first positional argument to a Field to designate a human-readable name. That’s used in a couple of introspective parts of Django, and it doubles as documentation. If this field isn’t provided, Django will use the machine-readable name. In this example, we’ve only defined a human-readable name for Question.pub_date. For all other fields in this model, the field’s machine-readable name will suffice as its human-readable name.

Some Field classes have required arguments. CharField, for example, requires that you give it a max_length. That’s used not only in the database schema, but in validation, as we’ll soon see.

A Field can also have various optional arguments; in this case, we’ve set the default value of votes to 0.

Finally, note a relationship is defined, using ForeignKey. That tells Django each Choice is related to a single Question. Django supports all the common database relationships: many-to-one, many-to-many, and one-to-one.

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 pollsite/settings.py file and add that dotted path to the INSTALLED_APPS setting. It’ll look like this:

INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

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:

(pollapp_env) C:\Application_django>python manage.py makemigrations polls
Migrations for 'polls':
  polls\migrations\0001_initial.py
    - Create model Question
- Create model 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 files on disk. You can read the migration for your new model if you like; it’s the file polls/migrations/0001_initial.py.

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

(pollapp_env) C:\Application_django>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
  Applying polls.0001_initial... OK

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.

Migrations are very powerful and let you change your models over time, as you develop your project, without the need to delete your database or tables and make new ones - it specializes in upgrading your database live, without losing data.

Django Admin

Django entirely automates creation of admin interfaces for models. First, we’ll need to create a user who can login to the admin site. Run the following command:

python manage.py createsuperuser

(pollapp_env) C:\Application_django>python manage.py createsuperuser
Username (leave blank to use 'vswam'): admin
Email address: admin@swami.com
Password:
Password (again):
Superuser created successfully.

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:

Django admin login screen
Now log in with the superuser account that was created:

Django admin index page

Now 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:

from django.contrib import admin
from .models import Question

# Register your models here.

admin.site.register(Question)


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

Django admin index page, now with polls displayed

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.

I’ve created Which is better framework for wed development as an example question.
There is a typo in Which is better framework for wed development, it should be web and not wed. This can be done by editing the question.

Create some questions on your own and see if are able to.

Share:

Sunday, April 26, 2020

Django pollapp - 2( creating the poll app)


Creating the Polls app

In the previous post we created our environment for our pollsite “project”. Now it’s time to start doing the real work.

Each application you write in Django consists of a Python package that follows a certain convention. 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.

We’ll create our poll app in the same directory as our manage.py file so that it can be imported as its own top-level module, rather than a submodule of pollsite.

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

Microsoft Windows [Version 10.0.18362.778]
(c) 2019 Microsoft Corporation. All rights reserved.

C:\Users\vswam>cd C:\Application_django

C:\Application_django>pollapp_env\Scripts\activate

(pollapp_env) C:\Application_django>python manage.py startapp polls

(pollapp_env) C:\Application_django>

Now notice the directory structure created:

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



Now we will create our first view. Open the file polls/views.py and put the following code in it:

from django.http import HttpResponse

# Create your views here.
def index(request):
            return HttpResponse("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. Your app directory should now look like:

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

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

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

Next, we need to point the root URLconf at the polls.urls module. In pollsite/urls.py, add an import for django.urls.include and insert an include() in the urlpatterns list, so you have:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
path('polls/', include('polls.urls')),
]


The include() function allows referencing other URLconfs. 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.

We have now wired an index view into the URLconf. Verify it’s working by going to http://localhost:8000/polls/ (make sure the Django server is up and running).

You should see the following message in your browser- “You're at the polls index.”

The path() function is passed four arguments, two required: route and view, and two optional: kwargs, and name. route is a string that contains a URL pattern. When processing a request, Django starts at the first pattern in urlpatterns and makes its way down the list, comparing the requested URL against each pattern until it finds one that matches.

For example, in a request to http://localhost:8000/polls/  the URLconf will look for polls/.

When Django finds a matching pattern, it calls the specified view function with an HttpRequest object as the first argument and any “captured” values from the route as keyword arguments.

Using path() argument: kwargs , arbitrary keyword arguments can be passed in a dictionary to the target view.

Using path() argument: name, naming your URL lets you refer to it unambiguously from elsewhere in Django, especially from within templates. This powerful feature allows you to make global changes to the URL patterns of your project while only touching a single file.
Share: