Skip to main content

Web APIs for Django with comments, made easy.

Project description

[I forked this from DRF]

Django REST framework

build-status-image coverage-status-image pypi-version

Awesome web-browsable Web APIs.

Full documentation for the project is available at https://www.django-rest-framework.org/.


Funding

REST framework is a collaboratively funded project. If you use REST framework commercially we strongly encourage you to invest in its continued development by signing up for a paid plan.

The initial aim is to provide a single full-time position on REST framework. Every single sign-up makes a significant impact towards making that possible.

Many thanks to all our wonderful sponsors, and in particular to our premium backers, Sentry, Stream, Spacinov, Retool, bit.io, PostHog, CryptAPI, FEZTO, and Svix.


Overview

Django REST framework is a powerful and flexible toolkit for building Web APIs.

Some reasons you might want to use REST framework:

Below: Screenshot from the browsable API

Screenshot


Requirements

  • Python 3.8+
  • Django 5.0, 4.2

We highly recommend and only officially support the latest patch release of each Python and Django series.

Installation

Install using pip...

pip install djangorestframework

Add 'drf_comments' to your INSTALLED_APPS setting.

INSTALLED_APPS = [
    ...
    'drf_comments',
]

Example

Let's take a look at a quick example of using REST framework to build a simple model-backed API for accessing users and groups.

Startup up a new project like so...

pip install django
pip install djangorestframework
django-admin startproject example .
./manage.py migrate
./manage.py createsuperuser

Now edit the example/urls.py module in your project:

from django.urls import include, path
from drf_comments import routers, serializers, viewsets, generics
from django.db import models
from django.contrib.auth.models import User
from drf_comments.comments import Comment, CommentSerializer, CommentCreateSerializer
from drf_comments.permissions import IsAuthenticated
from django.contrib.contenttypes.models import ContentType

# model for API you want comments added to
class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=255)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title


# Serializers define the API representation.
class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = ['id', 'user', 'title', 'content', 'created_at', 'updated_at']

class PostCommentSerializer(CommentSerializer):
    class Meta(CommentSerializer.Meta):
        model = Comment
        fields = ['id', 'user', 'text', 'created_at', 'updated_at', 'replies', 'parent']

class PostCommentCreateSerializer(CommentCreateSerializer):
    class Meta(CommentCreateSerializer.Meta):
        model = Comment
        fields = ['id', 'user', 'text', 'parent', 'content_type', 'object_id']


# ViewSets define the view behavior.

class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer
    permission_classes = [IsAuthenticated]

class PostCommentViewSet(viewsets.ModelViewSet):
    serializer_class = PostCommentSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        post_id = self.kwargs['post_id']
        content_type = ContentType.objects.get_for_model(Post)
        return Comment.objects.filter(content_type=content_type, object_id=post_id)

    def get_serializer_class(self):
        if self.action in ['create', 'update', 'partial_update']:
            return PostCommentCreateSerializer
        return PostCommentSerializer

    def perform_create(self, serializer):
        post_id = self.kwargs['post_id']
        content_type = ContentType.objects.get_for_model(Post)
        serializer.save(user=self.request.user, content_type=content_type, object_id=post_id)


# Routers provide a way of automatically determining the URL conf.
router = DefaultRouter()
router.register(r'posts', PostViewSet)

# Wire up our API using automatic URL routing.
urlpatterns = [
    path('', include(router.urls)),
    path('posts/<int:post_id>/comments/', PostCommentViewSet.as_view({'get': 'list', 'post': 'create'}), name='post-comments-list-create'),
    path('posts/<int:post_id>/comments/<int:pk>/', PostCommentViewSet.as_view({'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy'}), name='post-comments-detail'),
]

We'd also like to configure a couple of settings for our API.

Add the following to your settings.py module:

INSTALLED_APPS = [
    ...  # Make sure to include the default installed apps here.
    'drf_comments',
]

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'drf_comments.permissions.DjangoModelPermissionsOrAnonReadOnly',
    ]
}

That's it, we're done!

./manage.py runserver

You can now open the API in your browser at http://127.0.0.1:8000/, and view your new 'users' API. If you use the Login control in the top right corner you'll also be able to add, create and delete users from the system.

You can also interact with the API using command line tools such as curl. For example, to list the users endpoint:

$ curl -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/users/
[
    {
        "url": "http://127.0.0.1:8000/users/1/",
        "username": "admin",
        "email": "admin@example.com",
        "is_staff": true,
    }
]

Or to create a new user:

$ curl -X POST -d username=new -d email=new@example.com -d is_staff=false -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/users/
{
    "url": "http://127.0.0.1:8000/users/2/",
    "username": "new",
    "email": "new@example.com",
    "is_staff": false,
}

Documentation & Support

Full documentation for the project is available at https://www.django-rest-framework.org/.

For questions and support, use the REST framework discussion group, or #restframework on libera.chat IRC.

Security

Please see the security policy.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

drf-comments-0.2.tar.gz (1.1 MB view details)

Uploaded Source

Built Distribution

drf_comments-0.2-py3-none-any.whl (1.1 MB view details)

Uploaded Python 3

File details

Details for the file drf-comments-0.2.tar.gz.

File metadata

  • Download URL: drf-comments-0.2.tar.gz
  • Upload date:
  • Size: 1.1 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.0 CPython/3.11.9

File hashes

Hashes for drf-comments-0.2.tar.gz
Algorithm Hash digest
SHA256 5e4a1664e265afe750998c44acd1f8256eb824737bca4020f425ef344166d3ec
MD5 6d4090c2eed0b3e9ef70fb65aa47ca94
BLAKE2b-256 a8023cd45be507202bbaa5f09cc9ec0e3d96cd9ea1082a00e5919b774f6a811f

See more details on using hashes here.

File details

Details for the file drf_comments-0.2-py3-none-any.whl.

File metadata

  • Download URL: drf_comments-0.2-py3-none-any.whl
  • Upload date:
  • Size: 1.1 MB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.0 CPython/3.11.9

File hashes

Hashes for drf_comments-0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 744388f1ba091847525c9ab1a7d8bf890ebd80cc9d4058788c2dda55a8e49b49
MD5 8ebed32b448fbb6ef68f83842f69875b
BLAKE2b-256 f3b49656595800d2958687cd03db21261ae0b342033b1b0b79a826550901cf3d

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page