In the last article I have completely explained the steps required to do set up of Django on windows. Click here if you haven't done it so far.
This whole exercise is the crux of the post available in django docs. My approach just augments the theme provided on that link.
We are going to create a polling website in step by step fashion.
1. Create project >> django-admin.py startproject pollsite
2. Start server at port 8080 >> python manage.py runserver 8080
3. (Not required) I have changed the default database name of SQLite, to polling_db
In this file, all the tables required by different applications (INSTALLED_APPS in settings.py) will be created.
4. Each of the INSTALLED_APPS in settings.py has some database
table associated. To create that in your project, >> python manage.py syncdb
For auth application, it will ask for username, email and
password; provide that.
If you browse polling_db.sqlite3, you will find the following tables and indexes created.
You will find auth_user table with entry for the user created.
5. Create application polls at same level as manage.py by executing following command.
>> python manage.py startapp polls
This will create the basic directory structure.
6. For informing the project that polls app should be
installed, in settings.py, make entry 'polls' in INSTALLED_APPS
7. Now we need to create models for depicting following relationship.
For this write the following code in models.py
class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=200) votes = models.IntegerField()
To verify that the models created are not having any errors,
>> python manage.py validate
8. The tables for these models need be created in SQLite database. For this,
>> python manage.py makemigrations
>> python manage.py syncdb
You can see the table created, with application name
prefixed to the model name.
9. Now to test the code we have done so far, start python
shell but via manage.py which will set the required sys.path variables.
>> python manage.py shell
In the application poll, there is a module model which contains Poll class. Therefore,
>>> from polls.models import Poll
Import datetime module and then create the first poll question as follows.
>>> p = Poll(question="Who is the PM of India?", pub_date=datetime.datetime.now())
Now save the object,
>>> p.save()
And check in the database table, you will find record
inserted.
We will continue discussion to next post where we will talk about setting up administration site.
No comments:
Post a Comment
Your comments are very much valuable for us. Thanks for giving your precious time.