Git Product home page Git Product logo

rest-framework-tutorial's People

Contributors

auvipy avatar brumar avatar chadwhitacre avatar dependabot[bot] avatar jmsmkn avatar jpadilla avatar lurst avatar markotibold avatar matthewhegarty avatar parisk avatar rpkilby avatar tomchristie avatar xordoquy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rest-framework-tutorial's Issues

Part 1 - I got false in shell

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.

redundant import statement in Part 1

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.

Tutorial part 4 error

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.

NOT NULL constraint failed: snippets_snippet.owner_id

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 ?

IsOwner permission

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?

highlight url broken when GET with format specified

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

SnippetDetail and UserDetail returns all snippets - Parts 3 and 4

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.

3-class-based-views

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

报错404

您好,很抱歉我用的中文。
我根据你的教程写了代码,报错404, 然后下载您的代码发现跟教程的代码不一样??

Generics import on docs

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.

docs/tutorial vs Tutorial Repository

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

Uncomment the next line to enable the admin:

url(r'^admin/', include(admin.site.urls)),

In order to create consistency, we need to do something about them.
We have a number of options. We could:

  1. Add them to the deployed sandbox,
  2. Delete them as a part of the "Sandbox Deployment" commit,
  3. Delete them as if they had never existed, or
  4. Mention the deletion in docs/tutorial

Which is the preferred approach?

Cannot assign django.contrib.auth.models.AnonymousUser object

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.

Error during initial DB migration

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:

Add instructions to name the class views

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.

Tutorial 7 fails

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'

Add steps of tutorial all into one like the Angular Tutorial

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.

Could not resolve URL for hyperlinked relationship

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.

Django : DoesNotExist: User matching query does not exist.

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.

django.template.exceptions.TemplateDoesNotExist: rest_framework/api.html

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.

has_object_permission' obj parameter passed Page instead of Snippet object when paging enabled

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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.