- Notifications
You must be signed in to change notification settings - Fork5
Django Rest Framework 3.9.1 Quickstart Tutorial
macagua/example.django.rest_framework.tutorial
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
My practices about the following tutorials:
- Django 1.9 Project tutorial.
- Django Rest Framework 3.9.1 tutorial Quickstart.
- Desarrollo de un API REST con Django REST framework, tutorial 1: Serialización.
This Django Web app need a lot of Python extras packages, please execute the following command:
$ pip install -r requirements.txt --timeout 120
$ python manage.py makemigrations$ python manage.py migrate
This Django Web app need a to create a Django Admin User, for access and manager the Admin interface, please execute the following command:
Tip: for this local installation use the user asadmin and password aspassword123.
$ python manage.py createsuperuser --email admin@mail.com --username adminPassword: Password (again): Superuser created successfully.
You need to run the Django server, please execute the following command:
$ python manage.py runserver
Open your web browser with the following URL:http://0.0.0.0:8000/ and see the Django Web app.
Open your web browser with the following URL:http://0.0.0.0:8000/admin/ and see the Django Admin Interface, use the useradmin and passwordpassword123.
Tip: PLEASE add twogroups, twousers and later add a user into a group.
For add data forQuickstart App, please access to the following URL:http://localhost:8000/admin/quickstart/
For add data forSnippets App, please access to the following URL:http://localhost:8000/admin/snippets/
You have many APIs Rest for testing, now access to the APIs, both from the command-line, using tools likecurl, please execute the following command:
For testing theusers API Rest, please execute the following command:
$ curl -H'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/users/[ {"url":"http://127.0.0.1:8000/users/4/","username":"rocio","email":"rociogonzalez@mail.com","groups": ["http://127.0.0.1:8000/groups/3/" ] }, {"url":"http://127.0.0.1:8000/users/3/","username":"leonardo","email":"leonardo@mail.com","groups": ["http://127.0.0.1:8000/groups/2/" ] }, {"url":"http://127.0.0.1:8000/users/1/","username":"admin","email":"admin@mail.com","groups": [] }]
For testing thegroups API Rest, please execute the following command:
$ curl -H'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/groups/[ {"url":"http://127.0.0.1:8000/groups/1/","name":"Administrators" }, {"url":"http://127.0.0.1:8000/groups/2/","name":"Plone" }, {"url":"http://127.0.0.1:8000/groups/3/","name":"Botana" }]
For testing theevents API Rest, please execute the following command:
$ curl -H'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/events/[ {"name":"New Plone release for 2018","description":"Plone will be release a new version at PloneConf 2018","room_number": 201,"start_date":"2018-02-13T19:42:31Z","finish_date":"2018-02-14T19:42:37Z" }, {"name":"New Django release","description":"Django will be release a new version at DjangoConf 2018","room_number": 101,"start_date":"2018-02-12T19:40:59Z","finish_date":"2018-02-12T20:41:04Z" }]
For testing theblog post API Rest, please execute the following command:
$ curl -H'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/blog-post/[ {"title":"Django project will be release a new version soon","content":"Django will be release a new version at DjangoConf 2018" }, {"title":"Plone is Cool","content":"Plone is still in fashion with the latest Web technologies" }]
For testing thecomments API Rest, please execute the following command:
$ curl -H'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/comments/[ {"email":"leonardo@mail.com","content":"I want to dowload and test it","created":"2018-02-03T19:46:43Z" }, {"email":"leonardoc@plone.org","content":"#FuckYou Djanguero","created":"2018-02-03T19:22:02Z" }, {"email":"djangueroguy@djangoproject.com","content":"You are very pathetic you are still using Plone","created":"2018-02-03T19:21:33Z" }]
For testing thesnippets list API Rest, please execute the following command:
$ curl -H'Accept: application/json; indent=4' -u admin:password123 http://localhost:8000/snippets/list/[{"id":1,"title":"","code":"foo =\"bar\"\n","linenos":false,"language":"python","style":"friendly"},{"id":2,"title":"","code":"print\"hello, world\"\n","linenos":false,"language":"python","style":"friendly"},{"id":3,"title":"","code":"print\"hello, world\"","linenos":false,"language":"python","style":"friendly"}]
For testing thesnippets detail API Rest, please execute the following command:
$ curl -H'Accept: application/json; indent=4' -u admin:password123 http://localhost:8000/snippets/detail/1/{"id":1,"title":"","code":"foo =\"bar\"\n","linenos":false,"language":"python","style":"friendly"}
For make some practices the Django ORM, please execute the following command:
$ python manage.py shellPython 2.7.13 (default, Nov 24 2017, 17:33:09) [GCC 6.3.0 20170516] on linux2Type"help","copyright","credits" or"license"for more information.(InteractiveConsole)>>>
At Python Interactive Console, please execute the following command:
>>>>>># Serializers tutorial section>>>>>># Declaring Serializers section>>>>>>fromdatetimeimportdatetime>>>>>>classComment(object):...def__init__(self,email,content,created=None):...self.email=email...self.content=content...self.created=createdordatetime.now()...>>>comment=Comment(email='leonardo@mail.com',content='THIS IS A TESTING COMMENT')>>>comment<Commentobjectat0x7f110aa91510>>>>fromrest_frameworkimportserializers>>>classCommentSerializer(serializers.Serializer):...email=serializers.EmailField()...content=serializers.CharField(max_length=200)...created=serializers.DateTimeField()...>>>>>># Serializing objects section>>>>>>serializer=CommentSerializer(comment)>>>serializerCommentSerializer(<Commentobject>):email=EmailField()content=CharField(max_length=200)created=DateTimeField()>>>serializer.data{'email':u'leonardo@mail.com','content':u'THIS IS A TESTING COMMENT','created':'2018-02-03T14:51:39.574410'}>>>fromrest_framework.renderersimportJSONRenderer>>>json=JSONRenderer().render(serializer.data)>>>json'{"email":"leonardo@mail.com","content":"THIS IS A TESTING COMMENT","created":"2018-02-03T14:51:39.574410"}'>>>>>># Deserializing objects section>>>>>>fromdjango.utils.siximportBytesIO>>>fromrest_framework.parsersimportJSONParser>>>>>>stream=BytesIO(json)>>>data=JSONParser().parse(stream)>>>data{u'content':u'THIS IS A TESTING COMMENT',u'email':u'leonardo@mail.com',u'created':u'2018-02-03T15:16:41.744807'}>>>>>>serializer=CommentSerializer(data=data)>>>serializer.is_valid()True>>>serializer.validated_dataOrderedDict([(u'email',u'leonardo@mail.com'), (u'content',u'THIS IS A TESTING COMMENT'), (u'created',datetime.datetime(2018,2,3,14,51,39,574410,tzinfo=<django.utils.timezone.LocalTimezoneobjectat0x7f1109752c90>))])>>>>>># Saving instances section>>>>>>classCommentSerializer(serializers.Serializer):... ...email=serializers.EmailField()...content=serializers.CharField(max_length=200)...created=serializers.DateTimeField()...defcreate(self,validated_data):...returnComment(**validated_data)...defupdate(self,instance,validated_data):...instance.email=validated_data.get('email',instance.email)...instance.content=validated_data.get('content',instance.content)...instance.created=validated_data.get('created',instance.created)...returninstance...>>>>>>serializer=CommentSerializer(data=data)>>>serializer=CommentSerializer(comment,data=data)>>>>>># Validation section>>>>>>serializer=CommentSerializer(data={'email':'foobar','content':'baz'})>>>serializer.is_valid()False>>>serializer.errors{'email': [u'Enter a valid email address.'],'created': [u'This field is required.']}>>>>>>serializer.is_valid(raise_exception=True)Traceback (mostrecentcalllast):File"<console>",line1,in<module>File"/home/leonardo/virtualenv/django27/local/lib/python2.7/site-packages/rest_framework/serializers.py",line245,inis_validraiseValidationError(self.errors)ValidationError: {'email': [u'Enter a valid email address.'],'created': [u'This field is required.']}>>>>>># Field-level validation section>>>>>>fromrest_frameworkimportserializers>>>classBlogPostSerializer(serializers.Serializer):...title=serializers.CharField(max_length=100)...content=serializers.CharField()...defvalidate_title(self,value):..."""... Check that the blog post is about Django.... """...if'django'notinvalue.lower():...raiseserializers.ValidationError("Blog post is not about Django")...returnvalue...>>>>>># Object-level validation section>>>>>>classEventSerializer(serializers.Serializer):...description=serializers.CharField(max_length=100)...start=serializers.DateTimeField()...finish=serializers.DateTimeField()...defvalidate(self,data):..."""... Check that the start is before the stop.... """...ifdata['start']>data['finish']:...raiseserializers.ValidationError("finish must occur after start")...returndata...>>>>>># Validators section>>>>>>defmultiple_of_ten(value):...ifvalue%10!=0:...raiseserializers.ValidationError('Not a multiple of ten')...>>>classGameRecord(serializers.Serializer):...score=serializers.IntegerField(validators=[multiple_of_ten])...>>>
About
Django Rest Framework 3.9.1 Quickstart Tutorial
Topics
Resources
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors2
Uh oh!
There was an error while loading.Please reload this page.