When we define models for an app, Django makes it easy for us to work with our models through the admin site. A site’s administrators use the admin site, not a site’s general users. Now we’ll set up the admin site and use it to add some questions through the Question model.
Creating a superuser
Django allows you to create a user who has all privileges available on the site, called a superuser. A privilege controls the actions a user can take. The most restrictive privilege settings allow a user to only read public information on the site. Registered users typically have the privilege of reading their own private data and some selected information available only to members. To effectively administer a web application, the site owner usually needs access to all information stored on the site. To create a superuser in Django, enter the following command and respond to the prompts:
(pollsite_env) C:\Projects\PollSite>python manage.py createsuperuser
Username (leave blank to use 'python'): pollsite_admin
Email address:
Password:
Password (again):
This password is too short. It must contain at least 8 characters.
This password is too common.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.
(pollsite_env) C:\Projects\PollSite>
When you issue the command createsuperuser, Django prompts you to enter a username for the superuser. Here we’re using pollsite_admin, but you can enter any username you want. You can enter an email address if you want or just leave this field blank. You’ll need to enter your password twice. I have used a simple password hence I choose to Bypass password validation.
Registering a Model with the Admin Site
Django includes some models in the admin site automatically, such as User and Group, but the models we create need to be registered manually. From C:\Projects\PollSite\polls directory open admin.py file to register the Question Model:
from django.contrib import admin
from .models import Question
# Register your models here.
admin.site.register(Question)
This code imports the model we want to register Question Model and then uses admin.site.register() to tell Django to manage our model through the admin site.
Go to http://localhost:8000/admin/, enter the username and password for the superuser we just created, and you should see a screen like the one shown below:
In case the model doesn't show then restart the server running in the other terminal by executing python manage.py runserver command.
We can add questions by clicking the Add button button at this stage the complete functionality of the project has not been implemented. So instead of adding questions we'll move on to create our next model, Choice which will give us options to select an answer for the Question asked in Poll. The code for the Choice model is shown below:
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
Add this code to the models.py file. The Choice model has two fields: the text of the choice and a vote tally. Each Choice is associated with a Question and this 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.
As we’ve added a new model, we need to migrate the database again. Run the command python manage.py makemigrations polls, and then run the command python manage.py migrate. Migrate the database and check the output:
(pollsite_env) C:\Projects\PollSite>python manage.py makemigrations polls
Migrations for 'polls':
polls\migrations\0002_choice.py
- Create model Choice
(pollsite_env) C:\Projects\PollSite>python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
Applying polls.0002_choice... OK
(pollsite_env) C:\Projects\PollSite>
A new migration called 0002_choice.py is generated, which tells Django how to modify the database to store information related to the model Choice. When we issue the migrate command, we see that Django applied this migration, and everything was okay. As we did before for the Question model, we'll register the Choice model with the admin.py. Modify the admin.py file as shown below:
from django.contrib import admin
from .models import Question,Choice
# Register your models here.
admin.site.register(Question)
admin.site.register(Choice)
Go back to http://localhost/admin/, and you should see Choices listed under Questions. It’s important to add __str__() methods to your models, not only for your own convenience when dealing with the interactive prompt, but also because objects’ representations are used throughout Django’s automatically-generated admin.
Note these are normal Python methods. Let’s add a custom method to the Question model as shown below:
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):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
We'll use this function later as of now this was just to demonstrate how to create custom method in our models. We also have to import the respective modules like the datetime and from django.utils import timezone, to reference Python’s standard datetime module and Django’s time-zone-related utilities in django.utils.timezone, respectively.
Creating a superuser
Django allows you to create a user who has all privileges available on the site, called a superuser. A privilege controls the actions a user can take. The most restrictive privilege settings allow a user to only read public information on the site. Registered users typically have the privilege of reading their own private data and some selected information available only to members. To effectively administer a web application, the site owner usually needs access to all information stored on the site. To create a superuser in Django, enter the following command and respond to the prompts:
(pollsite_env) C:\Projects\PollSite>python manage.py createsuperuser
Username (leave blank to use 'python'): pollsite_admin
Email address:
Password:
Password (again):
This password is too short. It must contain at least 8 characters.
This password is too common.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.
(pollsite_env) C:\Projects\PollSite>
When you issue the command createsuperuser, Django prompts you to enter a username for the superuser. Here we’re using pollsite_admin, but you can enter any username you want. You can enter an email address if you want or just leave this field blank. You’ll need to enter your password twice. I have used a simple password hence I choose to Bypass password validation.
Registering a Model with the Admin Site
Django includes some models in the admin site automatically, such as User and Group, but the models we create need to be registered manually. From C:\Projects\PollSite\polls directory open admin.py file to register the Question Model:
from django.contrib import admin
from .models import Question
# Register your models here.
admin.site.register(Question)
This code imports the model we want to register Question Model and then uses admin.site.register() to tell Django to manage our model through the admin site.
Go to http://localhost:8000/admin/, enter the username and password for the superuser we just created, and you should see a screen like the one shown below:
In case the model doesn't show then restart the server running in the other terminal by executing python manage.py runserver command.
We can add questions by clicking the Add button button at this stage the complete functionality of the project has not been implemented. So instead of adding questions we'll move on to create our next model, Choice which will give us options to select an answer for the Question asked in Poll. The code for the Choice model is shown below:
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
Add this code to the models.py file. The Choice model has two fields: the text of the choice and a vote tally. Each Choice is associated with a Question and this 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.
As we’ve added a new model, we need to migrate the database again. Run the command python manage.py makemigrations polls, and then run the command python manage.py migrate. Migrate the database and check the output:
(pollsite_env) C:\Projects\PollSite>python manage.py makemigrations polls
Migrations for 'polls':
polls\migrations\0002_choice.py
- Create model Choice
(pollsite_env) C:\Projects\PollSite>python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
Applying polls.0002_choice... OK
(pollsite_env) C:\Projects\PollSite>
A new migration called 0002_choice.py is generated, which tells Django how to modify the database to store information related to the model Choice. When we issue the migrate command, we see that Django applied this migration, and everything was okay. As we did before for the Question model, we'll register the Choice model with the admin.py. Modify the admin.py file as shown below:
from django.contrib import admin
from .models import Question,Choice
# Register your models here.
admin.site.register(Question)
admin.site.register(Choice)
Go back to http://localhost/admin/, and you should see Choices listed under Questions. It’s important to add __str__() methods to your models, not only for your own convenience when dealing with the interactive prompt, but also because objects’ representations are used throughout Django’s automatically-generated admin.
Note these are normal Python methods. Let’s add a custom method to the Question model as shown below:
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):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
We'll use this function later as of now this was just to demonstrate how to create custom method in our models. We also have to import the respective modules like the datetime and from django.utils import timezone, to reference Python’s standard datetime module and Django’s time-zone-related utilities in django.utils.timezone, respectively.
0 comments:
Post a Comment