The admin panel is a user interface for managing the application, accessible through the browser. In the admin.py
file, we can add the model just created with the following command:
from models import Person admin.site.register(Person)
All the models can be accessed by a user interface at:
http://127.0.0.1:8000/admin/
At this link, the user name and password are required. We create that with the following command:
python manage.py createsuperuser
Then we type a username and password (in my case, andrea/a
).
Now, we can explore the panel that follows:
Clicking on Persons, we will see all Person
objects shown by name (because the__unicode__
function in the model refers to the name field):
The Django framework also provides a shell to explore the created models and test them. To start it, we type the following in the terminal:
python manage.py shell
Now we can import the Person
model and play with it:
In [1]: from addressesapp.models import Person In [2]: newcontact = Person() In [3]: newcontact.name = 'myfriend1' In [4]: newcontact.mail = '[email protected]' In [5]: newcontact.save() In [6]: Person.objects.all() Out[6]: [<Person: ss>, <Person: Andrea Isoni>, <Person: www 1>, <Person: addd-ww>, <Person: myfriend1>]
In these lines, we have created a new contact, myfriend1
, and verified it has been added to the list of Person
objects.
The Django framework also allows us to write custom commands through the manage.py
module. For example, we would like to export the entire list of contacts into a CSV file. To achieve that, we create a commands
folder inside a management
folder (with __init__.py
in each folder). The file implements the custom command to export the contacts list to CSV, extending the BaseCommand
class:
from addressesapp.models import Person from django.core.management.base import BaseCommand, CommandError from optparse import make_option import csv class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('--output', dest='output', type='string', action='store', help='output file'), ) def person_data(self, person): return [person.name,person.mail] def handle(self, *args, **options): outputfile = options['output'] contacts = Person.objects.all() header = ['Name','email'] f = open(outputfile,'wb') writer = csv.writer(f, quoting=csv.QUOTE_NONNUMERIC) writer.writerow(header) for person in contacts: writer.writerow(self.person_data(person))
The command must define a handler
function, which will perform the export operation. Type the following from the test_server
folder:
python manage.py contacts_tocsv –output='contacts_list.csv'
A RESTful API is an application programming interface that employs HTTP requests (such as GET and POST) to manage the data of an application. In this case, the API is used to obtain the address book through a curl
call. In order to do that, we have defined the rest_framework
app in the INSTALLED_APPS
section of settings.py
, and then the api.py
file implements the API:
from rest_framework import viewsets, generics, views from rest_framework.response import Response from rest_framework.permissions import AllowAny from rest_framework.pagination import PageNumberPagination from addressesapp.serializers import AddressesSerializer from addressesapp.models import Person class LargeResultsSetPagination(PageNumberPagination): page_size = 1000 page_size_query_param = 'page_size' max_page_size = 10000 class AddressesList(generics.ListAPIView): serializer_class = AddressesSerializer permission_classes = (AllowAny,) pagination_class = LargeResultsSetPagination def get_queryset(self): query = self.request.query_params.get if query('name'): return Person.objects.filter(name=query('name')) else: return Person.objects.all()
We have used the ListAPIView
class to return all Person
objects, or only the one that matches the name
value. Since the returned list may be too large, we need to override the PageNumberPagination
class to show more objects on the same page; the LargeResultsSetPagination
class allows a maximum of 10,000 objects per page. This API needs to transform the Person
objects to a JSON format object, which is performed by the AddressesSerializer serializer
implemented in serializers.py
:
from addressesapp.models import Person from rest_framework import serializers class AddressesSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Person fields = ('id', 'name', 'mail')
Now the address book can be retrieved using the curl
command:
curl -X GET http://localhost:8000/addresses-list/
Note the forward slash at the end of the URL. In the same way, we can Note the forward slash at the end of the URL. In the same way, we can specify a name value to get their email:
curl -X GET http://localhost:8000/addresses-st/?name=name_value
Note that we can always specify the page query parameter, in case the number of contacts is too large (or change the pagination size value). In the urls.py
file, we also defined the docs URL to be our Swagger RESTful API, which allows the user to explore and test the API using a browser:
This is a user-friendly way to verify that the API is working as expected and the data is shown in the correct format.
18.188.10.1