kandi background

django-rest-framework | Web APIs for Django. | REST library

Download this library from

kandi X-RAY | django-rest-framework Summary

django-rest-framework is a Python library typically used in Web Services, REST applications. django-rest-framework has no bugs, it has no vulnerabilities, it has build file available and it has high support. However django-rest-framework has a Non-SPDX License. You can install using 'pip install django-rest-framework' or download it from GitHub, PyPI.
Django REST framework is a powerful and flexible toolkit for building Web APIs.

kandi-support Support

  • django-rest-framework has a highly active ecosystem.
  • It has 22954 star(s) with 6060 fork(s). There are 627 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 113 open issues and 3609 have been closed. On average issues are closed in 410 days. There are 124 open pull requests and 0 closed requests.
  • It has a positive sentiment in the developer community.
  • The latest version of django-rest-framework is 3.12.4

quality kandi Quality

  • django-rest-framework has 0 bugs and 0 code smells.

securitySecurity

  • django-rest-framework has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • django-rest-framework code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.

license License

  • django-rest-framework has a Non-SPDX License.
  • Non-SPDX licenses can be open source with a non SPDX compliant license, or non open source licenses, and you need to review them closely before use.

buildReuse

  • django-rest-framework releases are available to install and integrate.
  • Deployable package is available in PyPI.
  • Build file is available. You can build the component from source.
  • Installation instructions, examples and code snippets are available.
  • django-rest-framework saves you 17797 person hours of effort in developing the same functionality from scratch.
  • It has 37833 lines of code, 2760 functions and 243 files.
  • It has low code complexity. Code complexity directly impacts maintainability of the code.
Top functions reviewed by kandi - BETA

kandi has reviewed django-rest-framework and discovered the below as its top functions. This is intended to give you an instant insight into django-rest-framework implemented functionality, and help decide if they suit your requirements.

  • Generates keyword arguments for a model field .
  • Returns a JSON - serializable representation of a field .
  • Get the field names for the serializer .
  • Convert a field to a JSON Schema .
  • Create a viewset from a viewset .
  • Raises errors if the serializer is not writable .
  • Render raw data form .
  • Decorator to define an API view .
  • Generate the kwargs for a relation .
  • Parse a dictionary .

django-rest-framework Key Features

The Web browsable API is a huge usability win for your developers.

Authentication policies including optional packages for OAuth1a and OAuth2.

Serialization that supports both ORM and non-ORM data sources.

Customizable all the way down - just use regular function-based views if you don't need the more powerful features.

Extensive documentation, and great community support.

django-rest-framework Examples and Code Snippets

  • Installation
  • Example
  • You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field
  • Checking properties of an object based on separete view (Django|Django-Rest-Framework)
  • Cannot access API view on post request using decorator [AllowAny]
  • DRF: Creating mixin using different serializers & objects
  • Index not being used for django desc
  • unable to Send compressed gzip data using Django Rest framework
  • Speeding up Django Rest Framework Model Serializer N+1 Query problem
  • Django SimpleJWT: Some questions with token authentication
  • Patch request not patching - 403 returned - django rest framework
  • In Django Rest Framework how can I return errors (warnings) from validation / serialization without failing the validation?

Installation

pip install djangorestframework

Community Discussions

Trending Discussions on django-rest-framework
  • You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field
  • Optional serializer field in Django Rest Framework
  • Checking properties of an object based on separete view (Django|Django-Rest-Framework)
  • Cannot access API view on post request using decorator [AllowAny]
  • DRF: Creating mixin using different serializers & objects
  • Django and react login with google authentication
  • Index not being used for django desc
  • unable to Send compressed gzip data using Django Rest framework
  • Speeding up Django Rest Framework Model Serializer N+1 Query problem
  • Django SimpleJWT: Some questions with token authentication
Trending Discussions on django-rest-framework

QUESTION

You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field

Asked 2022-Mar-02 at 21:42

I'm trying to setup the lookup field between two entities, but I can't fix this error.

I've already tried these solutions but none of them worked for me(What am I doing wrong?):

Django Rest Framework, improperly configured lookup field

Django Rest Framework - Could not resolve URL for hyperlinked relationship using view name "user-detail"

DRF Could not resolve URL for hyperlinked relationship using view name on PrimaryKeyRelatedField

here's my code Models:

class Category(models.Model):
    title = models.CharField(max_length=50, unique=True)
    slug = models.SlugField(max_length=80, default='')

    def __str__(self):
        return self.title

class Option(models.Model):
    title = models.CharField(max_length=80)
    slug = models.SlugField(max_length=80, unique=True)
    description = models.CharField(max_length=250)
    price = models.DecimalField(max_digits=7,  decimal_places=2)
    category = models.ForeignKey(Category, related_name='options', on_delete=models.CASCADE)
    photo = models.ImageField(upload_to='options', null=True)

    class Meta:
        ordering = ['title']
    
    def __str__(self):
        return self.title

Serializers:

class CategorySerializer(serializers.HyperlinkedModelSerializer):
    options = serializers.HyperlinkedRelatedField(many=True, view_name='option-detail', read_only=True)
    class Meta:
        model = Category
        fields = ('url', 'slug', 'title', 'options')
        lookup_field = 'slug'
        extra_kwargs = {
            'url': {'lookup_field': 'slug'}
        }

class OptionSerializer(serializers.HyperlinkedModelSerializer):
    category = serializers.ReadOnlyField(source='category.title')
    class Meta:
        model = Option
        fields = ('url', 'slug', 'title', 'description', 'price', 'category')
        lookup_field = 'slug'
        extra_kwargs = {
            'url': {'lookup_field': 'slug'},
            'category': {'lookup_field': 'slug'}
        }

Views:

class CategoryViewSet(viewsets.ReadOnlyModelViewSet):
    """
    Returns the Category list or the requested one
    """
    queryset = Category.objects.all()
    serializer_class = CategorySerializer
    lookup_field = 'slug'

class OptionViewSet(viewsets.ReadOnlyModelViewSet):
    """
    Returns the Option list or the requested one
    """
    queryset = Option.objects.all()
    serializer_class = OptionSerializer
    lookup_field = 'slug'

urls:

router = DefaultRouter()
router.register(r'options', views.OptionViewSet)
router.register(r'categories', views.CategoryViewSet)

urlpatterns = [
    path('', include(router.urls)),
]

This works for the Option model. When I hit the '[localhost]/options/' url, it correctly lists the options and when hitting '[localhost]/options/some-option-slug' it returns the correct option.

But none of that works for the Category model. Calls to '[localhost]/categories/' retuns "Could not resolve URL for hyperlinked relationship using view name "option-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field.". While calls to '[localhost]/categories/category-slug/' returns 404 Not Found.

My django version is 4.0.1 and my Django Rest Framework version is 3.13.1

EDIT As suggestted by @code-apprendice, here's the output of print('router'): [<URLPattern '^options/$' [name='option-list']>, <URLPattern '^options.(?P[a-z0-9]+)/?$' [name='option-list']>, <URLPattern '^options/(?P[^/.]+)/$' [name='option-detail']>, <URLPattern '^options/(?P[^/.]+).(?P[a-z0-9]+)/?$' [name='option-detail']>, <URLPattern '^categories/$' [name='category-list']>, <URLPattern '^categories.(?P[a-z0-9]+)/?$' [name='category-list']>, <URLPattern '^categories/(?P[^/.]+)/$' [name='category-detail']>, <URLPattern '^categories/(?P[^/.]+).(?P[a-z0-9]+)/?$' [name='category-detail']>, <URLPattern '^$' [name='api-root']>, <URLPattern '^.(?P[a-z0-9]+)/?$' [name='api-root']>]

The DRF correctly generated the views option-list, option-detail, category-list and category-detail

ANSWER

Answered 2022-Mar-02 at 21:42

Defining the lookup_field attribute for the options in the CategorySerializer solved the problem.

Here's the CategorySerializer class:

class CategorySerializer(serializers.HyperlinkedModelSerializer):
options = serializers.HyperlinkedRelatedField(
    view_name='option-detail',
    lookup_field = 'slug',
    many=True,
    read_only=True)

class Meta:
    model = Category
    fields = ('url', 'slug', 'title', 'options')
    lookup_field = 'slug'
    extra_kwargs = {
        'url': {'lookup_field': 'slug'}
    }

The problem was that the CategorySerializer set an explict options HyperlinkedRelatedField and it's lookup_field needs to be configured too.

Feel free to edit this answer to add a deeper explanation.

Source https://stackoverflow.com/questions/71312665

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install django-rest-framework

Add 'rest_framework' to your INSTALLED_APPS setting.

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. You may also want to follow the author on Twitter.