Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ba0ff2a

Browse files
committed
Added Serializers Api guide examples
1 parent a16e060 commit ba0ff2a

File tree

6 files changed

+408
-17
lines changed

6 files changed

+408
-17
lines changed

‎README.md‎

Lines changed: 230 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -39,49 +39,57 @@ $ python manage.py runserver
3939

4040
- Open your web browser with the following URL: [http://0.0.0.0:8000/](http://0.0.0.0:8000/) and see the Django Web app.
4141

42-
- Open your web browser with the following URL: [http://0.0.0.0:8000/admin/](http://0.0.0.0:8000/admin/) and see the Django Admin Interface, use the user **admin** and password **admin**.
42+
- Open your web browser with the following URL: [http://0.0.0.0:8000/admin/](http://0.0.0.0:8000/admin/) and see the Django Admin Interface, use the user **admin** and password **password123**.
4343

4444
**Tip:** PLEASE add two **groups**, two **users** and later add a user into a group.
4545

4646
### Testing the API
4747

4848
You have 2 API Rest for testing, now access to the APIs, both from the command-line, using tools like **curl**, please execute the following command:
4949

50+
#### Users endpoint
51+
52+
For testing the **users** API Rest, please execute the following command:
53+
5054
```bash
5155
$ curl -H 'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/users/
5256
[
5357
{
54-
"url": "http://127.0.0.1:8000/users/3/",
58+
"url": "http://127.0.0.1:8000/users/4/",
5559
"username": "rocio",
56-
"email": "rociogonzalez@gmail.com",
60+
"email": "rociogonzalez@mail.com",
5761
"groups": [
5862
"http://127.0.0.1:8000/groups/3/"
5963
]
6064
},
6165
{
62-
"url": "http://127.0.0.1:8000/users/2/",
66+
"url": "http://127.0.0.1:8000/users/3/",
6367
"username": "leonardo",
64-
"email": "leonardo@gmail.com",
68+
"email": "leonardo@mail.com",
6569
"groups": [
6670
"http://127.0.0.1:8000/groups/2/"
6771
]
68-
}
72+
},
6973
{
7074
"url": "http://127.0.0.1:8000/users/1/",
7175
"username": "admin",
7276
"email": "admin@mail.com",
73-
"groups": [
74-
"http://127.0.0.1:8000/groups/1/"
75-
]
77+
"groups": []
7678
}
7779
]
7880
```
7981

80-
The previus command testing the **users** API Rest, for testing the **groups** API Rest, please execute the following command:
82+
#### Groups endpoint
83+
84+
For testing the **groups** API Rest, please execute the following command:
8185

8286
```bash
8387
$ curl -H 'Accept: application/json; indent=4' -u admin:password123 htp://127.0.0.1:8000/groups/
8488
[
89+
{
90+
"url": "http://127.0.0.1:8000/groups/1/",
91+
"name": "Administrators"
92+
},
8593
{
8694
"url": "http://127.0.0.1:8000/groups/2/",
8795
"name": "Plone"
@@ -93,6 +101,218 @@ $ curl -H 'Accept: application/json; indent=4' -u admin:password123 htp://127.0.
93101
]
94102
```
95103

104+
#### Events endpoint
105+
106+
For testing the **events** API Rest, please execute the following command:
107+
108+
```bash
109+
$ curl -H 'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/events/
110+
[
111+
{
112+
"name": "New Plone release for 2018",
113+
"description": "Plone will be release a new version at PloneConf 2018",
114+
"room_number": 201,
115+
"start_date": "2018年02月13日T19:42:31Z",
116+
"finish_date": "2018年02月14日T19:42:37Z"
117+
},
118+
{
119+
"name": "New Django release",
120+
"description": "Django will be release a new version at DjangoConf 2018",
121+
"room_number": 101,
122+
"start_date": "2018年02月12日T19:40:59Z",
123+
"finish_date": "2018年02月12日T20:41:04Z"
124+
}
125+
]
126+
```
127+
128+
#### Blog post endpoint
129+
130+
For testing the **blog post** API Rest, please execute the following command:
131+
132+
```bash
133+
$ curl -H 'Accept: application/json; indent=4' -u admin:password123 htp://127.0.0.1:8000/blog-post/
134+
[
135+
{
136+
"title": "Django project will be release a new version soon",
137+
"content": "Django will be release a new version at DjangoConf 2018"
138+
},
139+
{
140+
"title": "Plone is Cool",
141+
"content": "Plone is still in fashion with the latest Web technologies"
142+
}
143+
]
144+
```
145+
146+
#### Comments endpoint
147+
148+
For testing the **comments** API Rest, please execute the following command:
149+
150+
```bash
151+
$ curl -H 'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/comments/
152+
[
153+
{
154+
"email": "leonardo@mail.com",
155+
"content": "I want to dowload and test it",
156+
"created": "2018年02月03日T19:46:43Z"
157+
},
158+
{
159+
"email": "leonardoc@plone.org",
160+
"content": "#FuckYou Djanguero",
161+
"created": "2018年02月03日T19:22:02Z"
162+
},
163+
{
164+
"email": "djangueroguy@djangoproject.com",
165+
"content": "You are very pathetic you are still using Plone",
166+
"created": "2018年02月03日T19:21:33Z"
167+
}
168+
]
169+
```
170+
171+
## Django Interactive ConsCelebration of the fall of the dictatorship of Socialism of the 21st century
172+
For make some practices the Django ORM, please execute the following command:
173+
174+
```bash
175+
$ python manage.py shell
176+
Python 2.7.13 (default, Nov 24 2017, 17:33:09)
177+
[GCC 6.3.0 20170516] on linux2
178+
Type "help", "copyright", "credits" or "license" for more information.
179+
(InteractiveConsole)
180+
>>>
181+
```
182+
183+
At Python Interactive Console, please execute the following command:
184+
185+
```python
186+
>>>
187+
>>> # Serializers tutorial section
188+
>>>
189+
>>> # Declaring Serializers section
190+
>>>
191+
>>> from datetime import datetime
192+
>>>
193+
>>> class Comment(object):
194+
... def __init__(self, email, content, created=None):
195+
... self.email = email
196+
... self.content = content
197+
... self.created = created or datetime.now()
198+
...
199+
>>> comment = Comment(email='leonardo@mail.com', content='THIS IS A TESTING COMMENT')
200+
>>> comment
201+
<Comment object at 0x7f110aa91510>
202+
>>> from rest_framework import serializers
203+
>>> class CommentSerializer(serializers.Serializer):
204+
... email = serializers.EmailField()
205+
... content = serializers.CharField(max_length=200)
206+
... created = serializers.DateTimeField()
207+
...
208+
>>>
209+
>>> # Serializing objects section
210+
>>>
211+
>>> serializer = CommentSerializer(comment)
212+
>>> serializer
213+
CommentSerializer(<Comment object>):
214+
email = EmailField()
215+
content = CharField(max_length=200)
216+
created = DateTimeField()
217+
>>> serializer.data
218+
{'email': u'leonardo@mail.com', 'content': u'THIS IS A TESTING COMMENT', 'created': '2018年02月03日T14:51:39.574410'}
219+
>>> from rest_framework.renderers import JSONRenderer
220+
>>> json = JSONRenderer().render(serializer.data)
221+
>>> json
222+
'{"email":"leonardo@mail.com","content":"THIS IS A TESTING COMMENT","created":"2018年02月03日T14:51:39.574410"}'
223+
>>>
224+
>>> # Deserializing objects section
225+
>>>
226+
>>> from django.utils.six import BytesIO
227+
>>> from rest_framework.parsers import JSONParser
228+
>>>
229+
>>> stream = BytesIO(json)
230+
>>> data = JSONParser().parse(stream)
231+
>>> data
232+
{u'content': u'THIS IS A TESTING COMMENT', u'email': u'leonardo@mail.com', u'created': u'2018年02月03日T15:16:41.744807'}
233+
>>>
234+
>>> serializer = CommentSerializer(data=data)
235+
>>> serializer.is_valid()
236+
True
237+
>>> serializer.validated_data
238+
OrderedDict([(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.LocalTimezone object at 0x7f1109752c90>))])
239+
>>>
240+
>>> # Saving instances section
241+
>>>
242+
>>> class CommentSerializer(serializers.Serializer):
243+
...
244+
... email = serializers.EmailField()
245+
... content = serializers.CharField(max_length=200)
246+
... created = serializers.DateTimeField()
247+
... def create(self, validated_data):
248+
... return Comment(**validated_data)
249+
... def update(self, instance, validated_data):
250+
... instance.email = validated_data.get('email', instance.email)
251+
... instance.content = validated_data.get('content', instance.content)
252+
... instance.created = validated_data.get('created', instance.created)
253+
... return instance
254+
...
255+
>>>
256+
>>> serializer = CommentSerializer(data=data)
257+
>>> serializer = CommentSerializer(comment, data=data)
258+
>>>
259+
>>> # Validation section
260+
>>>
261+
>>> serializer = CommentSerializer(data={'email': 'foobar', 'content': 'baz'})
262+
>>> serializer.is_valid()
263+
False
264+
>>> serializer.errors
265+
{'email': [u'Enter a valid email address.'], 'created': [u'This field is required.']}
266+
>>>
267+
>>> serializer.is_valid(raise_exception=True)
268+
Traceback (most recent call last):
269+
File "<console>", line 1, in <module>
270+
File "/home/leonardo/virtualenv/django27/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 245, in is_valid
271+
raise ValidationError(self.errors)
272+
ValidationError: {'email': [u'Enter a valid email address.'], 'created': [u'This field is required.']}
273+
>>>
274+
>>> # Field-level validation section
275+
>>>
276+
>>> from rest_framework import serializers
277+
>>> class BlogPostSerializer(serializers.Serializer):
278+
... title = serializers.CharField(max_length=100)
279+
... content = serializers.CharField()
280+
... def validate_title(self, value):
281+
... """
282+
... Check that the blog post is about Django.
283+
... """
284+
... if 'django' not in value.lower():
285+
... raise serializers.ValidationError("Blog post is not about Django")
286+
... return value
287+
...
288+
>>>
289+
>>> # Object-level validation section
290+
>>>
291+
>>> class EventSerializer(serializers.Serializer):
292+
... description = serializers.CharField(max_length=100)
293+
... start = serializers.DateTimeField()
294+
... finish = serializers.DateTimeField()
295+
... def validate(self, data):
296+
... """
297+
... Check that the start is before the stop.
298+
... """
299+
... if data['start'] > data['finish']:
300+
... raise serializers.ValidationError("finish must occur after start")
301+
... return data
302+
...
303+
>>>
304+
>>> # Validators section
305+
>>>
306+
>>> def multiple_of_ten(value):
307+
... if value % 10 != 0:
308+
... raise serializers.ValidationError('Not a multiple of ten')
309+
...
310+
>>> class GameRecord(serializers.Serializer):
311+
... score = serializers.IntegerField(validators=[multiple_of_ten])
312+
...
313+
>>>
314+
```
315+
96316
# Reference
97317

98318
- [Django 1.9 Project tutorial](https://docs.djangoproject.com/en/1.9/intro/).

‎quickstart/admin.py‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,19 @@
11
# -*- coding: utf-8 -*-
22

33
from django.contrib import admin
4-
from quickstart.models import Comment, Event
4+
from quickstart.models import BlogPost, Comment, Event
55

6-
# Register your models here.
76

8-
admin.site.register(Comment)
9-
admin.site.register(Event)
7+
class CommentAdmin(admin.ModelAdmin):
8+
list_display = ('content', 'created', 'email', 'blog_post')
9+
list_filter = ['email', 'created']
10+
search_fields = ['content']
11+
12+
class EventAdmin(admin.ModelAdmin):
13+
list_display = ('name', 'description', 'start_date', 'finish_date')
14+
list_filter = ['start_date', 'finish_date']
15+
search_fields = ['name', 'description']
16+
17+
admin.site.register(BlogPost)
18+
admin.site.register(Comment, CommentAdmin)
19+
admin.site.register(Event, EventAdmin)

‎quickstart/models.py‎

Lines changed: 69 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,73 @@
33
from __future__ import unicode_literals
44

55
from django.db import models
6+
from datetime import datetime
67

7-
# Create your models here.
8+
# Event's room numbers
9+
ROOM1 = 101
10+
ROOM2 = 102
11+
ROOM3 = 102
12+
ROOM4 = 201
13+
ROOM_NUMBER = (
14+
(ROOM1, "101"),
15+
(ROOM2, "102"),
16+
(ROOM3, "103"),
17+
(ROOM4, "201"),
18+
)
19+
20+
21+
class BlogPost(models.Model):
22+
title = models.CharField(max_length=1000, help_text="Enter the post's title.")
23+
content = models.CharField(max_length=100, help_text="Enter the post's content.")
24+
created = models.DateTimeField(help_text="Enter the post's date that which was created.")
25+
26+
class Meta:
27+
verbose_name = "Blog Post"
28+
verbose_name_plural = "Blog Posts"
29+
30+
def __str__(self):
31+
return self.title
32+
33+
34+
class Comment(models.Model):
35+
blog_post = models.ForeignKey(BlogPost, on_delete=models.CASCADE,
36+
related_name='post',
37+
verbose_name='Blog Post')
38+
email = models.EmailField(help_text="Enter the comment's author email.")
39+
content = models.CharField(max_length=128, help_text="Enter the comment.")
40+
created = models.DateTimeField(help_text="Enter the comment's date that which was created.")
41+
42+
class Meta:
43+
verbose_name = "Comment"
44+
verbose_name_plural = "Comments"
45+
46+
def __str__(self):
47+
return self.content
48+
49+
def create(self, validated_data):
50+
return Comment.objects.create(**validated_data)
51+
52+
def update(self, instance, validated_data):
53+
instance.email = validated_data.get('email', instance.email)
54+
instance.content = validated_data.get('content', instance.content)
55+
instance.created = validated_data.get('created', instance.created)
56+
instance.save()
57+
return instance
58+
59+
60+
class Event(models.Model):
61+
name = models.CharField(max_length=100,
62+
help_text="Enter the event's name.")
63+
description = models.CharField(max_length=100,
64+
help_text="Enter the event's description.")
65+
room_number = models.IntegerField(choices=ROOM_NUMBER, default=ROOM4,
66+
help_text="Select the event's room number.")
67+
start_date = models.DateTimeField(help_text="Select the event's start date.")
68+
finish_date = models.DateTimeField(help_text="Select the event's finish date.")
69+
70+
class Meta:
71+
verbose_name = "Event"
72+
verbose_name_plural = "Events"
73+
74+
def __str__(self):
75+
return self.name

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /