Source code for the Django REST framework tutorial.
encode / rest-framework-tutorial Goto Github PK
View Code? Open in Web Editor NEWThe Django REST framework tutorial. 🎓
Home Page: http://www.django-rest-framework.org/tutorial/1-serialization/
The Django REST framework tutorial. 🎓
Home Page: http://www.django-rest-framework.org/tutorial/1-serialization/
Source code for the Django REST framework tutorial.
If you follow the docs, startproject
automatically places some entries (as comments) in settings.py and urls.py , These entries are not really used.
As an example, in urls.py, we find
In order to create consistency, we need to do something about them.
We have a number of options. We could:
Which is the preferred approach?
when runing command: python manage.py makemigrations snippets
there is an error: NameError: name 'STYLE_CHOICES' is not defined
what is the problem please?
I am new to the programming and following the tutorial as it is. But can't seem to get past the 4th chapter "Authentication and permissions". At the end of the tutorial I'm trying to create the snippet programmatically but I'm getting error "NOT NULL constraint failed: snippets_snippet.owner_id" . Am I missing something ?
when I tried to access '/docs', the error I wrote on the title came out.
The tutorial is a great guide in the low to high level features available but by the end only the most abstracted code is left and this is the only code in the example tutorial git repo.
It would be nice to have all the tutorial code available in similar fashion as the angualrjs tutorials where the learner can step through them one by one.
I'd like to see snippets for authenticated user only.
I added IsOwner permission class to permission.py
class IsOwner(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
return obj.owner == request.user
Changed permission_classes in SnippetViewSet:
permission_classes = (
permissions.IsAuthenticatedOrReadOnly,
IsOwner, )
Created some users and snippets. But I see all snippets.
What do I need to do to see only authenticated user's snippets?
On tutorial 4, http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/#adding-endpoints-for-our-user-models reference is made to the generics and no import is provided. All reference to generics is also no existent on the tutorial code on git.
I was able to find it here https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/generics.py and imported accordingly. However I believe it should be put on the documentation to save time to learers.
Replacing encode/django-rest-framework#5074
I need to use this workaround to make the tutorial 06 run without any exceptions.
permissions.py
:
from rest_framework import permissions
from django.core.paginator import Page
class IsOwnerOrReadOnly(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS:
return True
if isinstance(obj, Page):
for ob in obj:
return ob.owner == request.user
else:
return obj.owner == request.user
This error will happen if paging enabled on settings.py
.
AttributeError at /snippets/
'Page' object has no attribute 'owner'
Request Method: GET
Request URL: http://localhost:8000/snippets/
Django Version: 1.7.1
Exception Type: AttributeError
Exception Value:
'Page' object has no attribute 'owner'
Exception Location: /Users/taufik/Python/djangotutorial/tutorial/snippets/permissions.py in has_object_permission, line 8
Python Executable: /Users/taufik/.virtualenvs/djangotutorial/bin/python
Python Version: 2.7.6
Python Path:
['/Users/taufik/Python/djangotutorial/tutorial',
'/Users/taufik/.virtualenvs/djangotutorial/lib/python27.zip',
'/Users/taufik/.virtualenvs/djangotutorial/lib/python2.7',
'/Users/taufik/.virtualenvs/djangotutorial/lib/python2.7/plat-darwin',
'/Users/taufik/.virtualenvs/djangotutorial/lib/python2.7/plat-mac',
'/Users/taufik/.virtualenvs/djangotutorial/lib/python2.7/plat-mac/lib-scriptpackages',
'/Users/taufik/.virtualenvs/djangotutorial/Extras/lib/python',
'/Users/taufik/.virtualenvs/djangotutorial/lib/python2.7/lib-tk',
'/Users/taufik/.virtualenvs/djangotutorial/lib/python2.7/lib-old',
'/Users/taufik/.virtualenvs/djangotutorial/lib/python2.7/lib-dynload',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
'/Users/taufik/.virtualenvs/djangotutorial/lib/python2.7/site-packages']
Server time: Mon, 22 Dec 2014 15:39:19 +0000
For Parts 3 and 4 of the tutorial the SnippetDetail and UserDetail class views return all objects. I'm not sure if this is intended behaviour, I would think it should be a single item filtered by id? I don't know how I would do that with here though.
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
4-authentication-and-permissions
class UserDetail(generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
I get the following when I attempt tutorial 7. http://www.django-rest-framework.org/tutorial/7-schemas-and-client-libraries/
System check identified no issues (0 silenced).
July 19, 2016 - 19:12:01
Django version 1.8.5, using settings 'tutorial.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Internal Server Error: /
Traceback (most recent call last):
File "/Users/harrymoreno/programming/django/drfTutorial/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 119, in get_response
resolver_match = resolver.resolve(request.path_info)
File "/Users/harrymoreno/programming/django/drfTutorial/venv/lib/python2.7/site-packages/django/core/urlresolvers.py", line 365, in resolve
for pattern in self.url_patterns:
File "/Users/harrymoreno/programming/django/drfTutorial/venv/lib/python2.7/site-packages/django/core/urlresolvers.py", line 401, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/Users/harrymoreno/programming/django/drfTutorial/venv/lib/python2.7/site-packages/django/core/urlresolvers.py", line 395, in urlconf_module
self._urlconf_module = import_module(self.urlconf_name)
File "/usr/local/Cellar/python/2.7.10/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/harrymoreno/programming/django/rest-framework-tutorial/tutorial/urls.py", line 5, in <module>
router = DefaultRouter(schema_title='foo')
TypeError: __init__() got an unexpected keyword argument 'schema_title'
Once encode/django-rest-framework#5609 is released with DRF 3.8, it will be necessary to update the snippet urlpatterns to use router.urlpatterns
instead of router.urls
.
In Tutorial 7: Schemas & client libraries, the Adding a schema section says that after installing coreapi
and updating urls.py,
corejson
should be listed as an option in the GET dropdown menu at Api Root.
It does not appear, neither is it present in the sandbox example here
Following Part 1 of the tutorial fine until I got to the shell component, where I was told to type the following:
import io
stream = io.BytesIO(content)
data = JSONParser().parse(stream)
serializer = SnippetSerializer(data=data)
serializer.is_valid()
When I got here, False was returned, rather than True. I tried again copying all of the code for shell and got the same result.
When I try to POST a snippet while not authenticated, Django returns:
ValueError at /snippets/
Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x7fda1f500470>": "Snippet.owner" must be a "User" instance.
Instead I expect something like the sandbox returns:
{
"detail": "Authentication credentials were not provided."
}
I have double checked my code and as far as I can tell it is identical to the one in this repository.
Is there something I missed?
What is responsible for managing the unauthenticated requests?
Thanks.
I was going through the excellent tutorial when I hit an error in part 4. It says to add the perform_create method to the SnippetList view in order to assign an owner to the snippets pre-save. This, however, gave me an IntegrityError saying the snippet did not have an owner_id.
I created this StackOverflow question, and the answer I got seemed to work.
It seems that for the generic ListView class, pre_save is the correct method for this and not perform_create.
Django version 1.10.2, using settings 'tutorial.settings'
File ".../site-packages/django/template/loader.py", line 25, in get_template
raise TemplateDoesNotExist(template_name, chain=chain)
django.template.exceptions.TemplateDoesNotExist: rest_framework/api.html
After running
./manage migrate
./manage runserver
then attempting to view http://127.0.0.1:8000/
, the above error is raised.
The link below is not accessible. It show "Application error".
refer to below quote:
There is a live example API for testing purposes, available here.
Tutorial 5 introduces the root API endpoint as:
@api_view(('GET',))
def api_root(request, format=None):
return Response({
'users': reverse('user-list', request=request, format=format),
'snippets': reverse('snippet-list', request=request, format=format)
})
However, when class based views are introduced in Tutorial 3, we loose the names for the views. We might need something like this for api-root
view to work:
url(r'^snippets/$', views.SnippetList.as_view(), name='snippet-list'),
url(r'^users/$', views.UserList.as_view(), name='user-list'),
Note the added name parameters for URLConf.
您好,很抱歉我用的中文。
我根据你的教程写了代码,报错404, 然后下载您的代码发现跟教程的代码不一样??
Hi,
Great tutorial, thanks for putting it together. Found one issue in Tutorial 7 (https://www.django-rest-framework.org/tutorial/7-schemas-and-client-libraries/). To get the /schema/ endpoint to work in a browser, the pyyaml package is needed. This needs to be added to requirements.txt and also to the pip install line in the tutorial page above.
Thanks,
Ed
has an error at line 5 ("/snippets/models.py")
currently is:
import from pygments.formatters HtmlFormatter
but I believe that is correct:
import from pygments.formatters.html HtmlFormatter
see:
https://pygments-doc.readthedocs.org/en/latest/formatters/html.html
I'm getting the 2 errors while accessing the following urls
{
"snippets": "http://127.0.0.1:8000/snippets/snippets/",
"users": "http://127.0.0.1:8000/snippets/users/"
}
Error-1: Could not resolve URL for hyperlinked relationship using view name "snippet-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field
attribute on this field.
Error-2: Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field
attribute on this field.
url
is deprecated since django 3.1
Getting this message when attempting to run manage.py migrate:
django.db.utils.OperationalError: Problem installing fixture '/home/foo/rest-framework-tutorial/rest-framework-tutorial/snippets/fixtures/initial_data.json': Could not load auth.User(pk=2): no such table: auth_user
Same result if I remove the included tmp.db and allowing the app to create a fresh db.
Traceback (most recent call last):
File "/home/foo/rest-framework-tutorial/venv/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/home/foo/rest-framework-tutorial/venv/lib/python3.4/site-packages/django/db/backends/sqlite3/base.py", line 485, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: auth_user
The above exception was the direct cause of the following exception:
In the first tutorial here : https://www.django-rest-framework.org/tutorial/1-serialization/ .
The completed online implementation as a sandbox version is not working , the link is https://restframework.herokuapp.com , it gives application error , maybe due to heroku not having a free plan anymore or heroku not supporting the python version .
I am finished 4 - Authentication and permissions. And do login in superuser it can't run normal. Server error 500. User matching query does not exist. Look like user can't find in table. How to do can resolve. Make project normal run. Thanks.
To install requirements with a clean environment, appdirs
, packaging
and six
need to be added to the requirements.txt (with python2).
The link in the readme leads to a 404. Should the link be updated to http://www.django-rest-framework.org/tutorial/1-serialization/ ?
all in the question ;-)
Hello! Thanks for the great tutorial.
I've found a redundant import
statement in a section of Pt.1 that could be removed:
from rest_framework.renderers import JSONRenderer
Thanks, for less typing effort for future learners : )
Happy also to fix it and do a PR if that would help - just not sure where the page is built from.
As of Django 1.10, patterns
does not exist. tutorial/urls.py
attempts to import it, but it's no longer needed.
Django loads that Python module and looks for the variable urlpatterns. This should be a Python list of django.conf.urls.url() instances.
https://docs.djangoproject.com/en/1.10/topics/http/urls/#how-django-processes-a-request
As the version of Python specified in runtime.txt is not supported by Heroku 20.
New to DRF.
The problem is when GET with
GET /snippets/?format=api
it returns
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"url": "https://restframework.herokuapp.com/snippets/1/?format=api",
"id": 1,
"highlight": "https://restframework.herokuapp.com/snippets/1/highlight/?format=api",
"owner": "admin",
"title": "serializers.py",
"code": "from django.contrib.auth.models import User, Group\r\n...",
"linenos": false,
"language": "python",
"style": "default"
}
]
}
And both
GET https://restframework.herokuapp.com/snippets/1/highlight/?format=api
GET https://restframework.herokuapp.com/snippets/1/highlight/?format=json
return 404 Not Found
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.