django-rest-framework | 🎸 | REST library
kandi X-RAY | django-rest-framework Summary
kandi X-RAY | django-rest-framework Summary
Django REST framework is a powerful and flexible toolkit for building Web APIs.
Support
Quality
Security
License
Reuse
Top functions reviewed by kandi - BETA
- Paginate a queryset
- Helper to get the position of an instance
- Decode the cursor
- Return a positive integer
- Get the fields of the serializer
- Build a nested field
- Build a field
- Convert a viewset into a view set
- Return a list of items from the context
- Save the model instance
- Get the attribute value for the field
- Include documentation for documentation
- Resolve internal value
- Authenticate the request
- Parse HTML dictionary
- Filter queryset
- Dispatch the request
- Convert value to date
- Render the data
- Return a list of urls
- Select a renderer from a list of renderers
- Return the hyperlink representation of the target
- Parse a dictionary
- Create a new model instance
- Create a link object
- Save a serializer instance
django-rest-framework Key Features
django-rest-framework Examples and Code Snippets
def restore_object(self, attrs, instance=None):
if instance:
# Update existing instance
instance.title = attrs.get('title', instance.title)
instance.code = attrs.get('code', instance.code)
instance.linenos = attrs.
class HighScore(models.Model):
created = models.DateTimeField(auto_now_add=True)
player_name = models.CharField(max_length=10)
score = models.IntegerField()
class HighScoreSerializer(serializers.BaseSerializer):
def to_representation
class UppercaseCharField(serializers.CharField):
def to_internal_value(self, data):
value = super(UppercaseCharField, self).to_internal_value(data)
if value != value.upper():
raise serializers.ValidationError('The inpu
class GroupSerializer(serializers.ModelSerializer):
empty = serializers.SerializerMethodField()
class Meta:
# …
def get_empty(self, obj):
return not group.users_group.exists()
building 'psycopg2.\_psycopg' extension
creating build/temp.linux-x86_64-3.9
creating build/temp.linux-x86_64-3.9/psycopg
x86_64-linux-gnu-gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-st
py38 inst-nodeps: /home/dafrandle/PycharmProjects/djangoProject/.tox/.tmp/package/1/UNKNOWN-0.0.0.tar.gz
backend_1 | 172.19.0.1 - - [16/Mar/2022 00:58:14] "DELETE /api/products HTTP/1.1" 405 -
path('profiles', ProductViewSet.as_view({
'get': 'list',
'post': 'create'
})),
pip install djangorestframework-simplejwt
from django.db.models import Q
from django_filters import rest_framework as filters
from django_filters import CharFilter
class BlogFilter(filters.FilterSet):
blog_category = CharFilter(field_name='blog_category_mast',
from rest_framework.exceptions import APIException
from rest_framework import status
class OkException(APIException):
status_code = status.HTTP_200_OK
default_detail = "error happens!!"
default_code = "error_happens"
Community Discussions
Trending Discussions on django-rest-framework
QUESTION
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
DRF Could not resolve URL for hyperlinked relationship using view name on PrimaryKeyRelatedField
here's my code Models:
...ANSWER
Answered 2022-Mar-02 at 21:42Defining the lookup_field attribute for the options in the CategorySerializer solved the problem.
Here's the CategorySerializer class:
QUESTION
How can I set a serializer field to optional in Django REST Framework?
I have the following serializer:
...ANSWER
Answered 2022-Feb-15 at 09:31The doc says required=False
to have None values, not required=None
.
QUESTION
I am using django-rest-framework and React.js. I need a seperate function in the backend to check if CartItem.amount
is lower then ProductStock.quantity
, if CartItem.product
equals ProductStock.id
of course (this part does not work). For the same function I need to check if the pricing is the same as in Product
model, but suprisingly this part of a function works. What can I do to make sure CartItem.amount
will get lowered if it is higher than ProductStock.quantity
?
Code below:
Product
is a blueprint for the rest of the models.
ProductStock
tracks the amount of different sizes of all of products.
CartItem
is a model used for tracking how many products a user bought.
models.py
...ANSWER
Answered 2022-Feb-13 at 19:40You need to change indentation of JsonResponse
cause it ends after first stock
in product_stock
. Also item.save()
and more probably need indentation change. Revise that in clean Python.
QUESTION
I have a simple function-based @api_view(['POST'])
with @permission_classes([AllowAny])
and DRF settings in settings.py are:
ANSWER
Answered 2022-Feb-08 at 19:00According to this, the position of decorator is wrong. The first decorator to be executed should be on the top. Change your decorator to the bottom like this:
QUESTION
I have two APIView classes with almost similar behaviour (and code). Different are only serializers and models object (Favorite & FavoriteSerializer for first class and PurchaseList and PurchaseListSerializer for second). As far as I understand it is a perfect usecase for mixin, according to DRF docs ([DRF: Creating custom mixins] 1https://www.django-rest-framework.org/api-guide/generic-views/).
Unfortunately, I'm struggling with how to define mixin without the definition of serializer & obj in it.
...ANSWER
Answered 2022-Jan-17 at 11:31You can create your own mixin like this:
QUESTION
I was trying set up google authentication with react frontend and django rest framework backend. I set up both the frontend and backend using this two part tutorial, PART1 & PART2. When I try to login with google in the frontend I get POST http://127.0.0.1:8000/google-login/ 400 (Bad Request)
I think it's because my google api needs an access token and an authorization code to be passed. After debugging the react js, I noticed the response I get from google doesn't have an authorization code. I suspect because responseType
is permission
(by default), Source:React login props , instead of code
. I was wondering how would you change the response type in react? (I'm not even sure if this alone is the issue)
Here's my backend code
In my views.py file
...ANSWER
Answered 2021-Nov-04 at 23:26After investigating a bit on my end, I think I might have a solution that works for you.
I've messed with OAuth before, and it's quite tricky sometimes because it has to be robust. So a bunch of security policies usually get in the way.
I'll provide my full step-by-step, since I was able to get it working, trying my best to match what you posted.
Firstly, to have a clean slate, I went off the example code linked in the tutorials. I cloned and built the project, and did the following:
- Creating a new project on GCP
- Configured the OAuth consent screen
- I set the User type to "internal". This options may not be available if you're not using an account under GSuite (which I am). "External" should be fine though, just that "internal" is the easiest to test.
- Created a OAuth 2.0 Client
- Added
http://localhost:3000
to the "Authorized JavaScript origins" and "Authorized redirect URIs" sections
- Added
- Configured the OAuth consent screen
- Register a Django superuser
- Registered a
Site
, with value oflocalhost:8000
for both fields. - Went into the admin panel, and added a
Social Application
withClient ID
andSecret Key
as the "Client ID" and "Client Secret" from GCP, respectively. I also picked the localhost site that we added earlier and added it to the right hand box. (I leftKey
blank)
- Registered a
Example of my Application Page
- Filled in the
clientId
field inApp.js
, in the params of theGoogleLogin
component.
Here's where I ran into a bit of trouble, but this is good news as I was able to reproduce your error! Looking at the request in the network inspector, I see that for me, no body was passed, which is clearly the direct cause of the error. But looking at App#responseGoogle(response)
, it clearly should pass a token of some sort, because we see the line googleLogin(response.accessToken)
.
So what is happening is that accounts.google.com is NOT returning a proper response, so something is happening on their end, and we get an invalid response, but we fail silently because javascript is javascript.
After examining the response that Google gave back, I found this related SO post that allowed me to fix the issue, and interestingly, the solution to it was quite simple: Clear your cache. I'll be honest, I'm not exactly sure why this works, but I suspect it has something to do with the fact that development is on your local machine (localhost
/127.0.0.1
difference, perhaps?).
You can also try to access your site via incognito mode, or another browser, which also worked for me.
I have knox token set up, can I use it instead of the JWT tokens?
I don't think I have enough knowledge to properly answer this, but my preliminary research suggests no. AFAIK, you should just store the token that Google gives you, as the token itself is what you'll use to authenticate. It seems that Knox replaces Django's TokenAuthentication
, which means that Knox is in charge of generating the token. If you're offloading the login work to Google, I don't see how you could leverage something like Knox. However, I could be very wrong.
Does the
class GoogleLogin(SocialLoginView)
, take care of the steps of validating the access token and code with google and creating the user with that email in database?
I believe so. After successfully authenticating with Google (and it calls the backend endpoint correctly), it seems to create a "Social Account" model. An example of what it created for me is below. It retrieved all this information (like my name) from Google.
Example of my "Social Accounts" page
As for how to retrieve the login from the browser's local storage, I have no idea. I see no evidence of a cookie, so it must be storing it somewhere else, or you might have to set that up yourself (with React Provider
s, Service
s, or even Redux
.
QUESTION
I have a django model with the following indexes:
...ANSWER
Answered 2022-Jan-11 at 03:48An index can be scanned in both directions, but it needs to be sorted exactly like the ORDER BY
clause it is intended by default. A plain index is sorted in ASC NULLS LAST
order, so it can support that order or the reverse, namely DESC NULLS FIRST
. To create an index that can support your ORDER BY
clause, use
QUESTION
I am sending JSON file in Django Rest APIView framework. I want to reduce the size of the file. Implemented below code but Receving below error:
...ANSWER
Answered 2021-Dec-22 at 18:47Well, I was having the same issue.
It is easier than expected. Just call the middleware in settings.py
as the first in the list (as explained in your link):
QUESTION
I have a DRF ModelSerializer
class that serializes anOrder
model. This serializer has a field:
num_modelA = serializers.SerializerMethodField()
`
ANSWER
Answered 2021-Dec-15 at 17:38You can work with an annotation:
QUESTION
I am implementing authentication in Django using SimpleJWT, and have a few questions regarding the same. To give some background I have multiple domains with my backend, some with normal login (username and password), and some with SSO logins.
Question 2: Suppose, I store the access tokens in local storage and send the access token to all APIs, and I'm also refreshing it before it expires. But what will happen if the user closes the browser, and we are not able to refresh the access token. The access token expires and the user gets logged out. How can we keep the user logged in for a certain amount of time (say 30 days)?
...ANSWER
Answered 2021-Dec-08 at 12:47For Question 2, add this code on your settings.py file
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install django-rest-framework
Support
Reuse Trending Solutions
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesStay Updated
Subscribe to our newsletter for trending solutions and developer bootcamps
Share this Page