Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How in CBV correctly redirect user if he dont have permission?
I want to redirect user to url (reverse_lazy('dashboard')) if Class Based View is not available to user (he dont have permission). I use next code but it dont redirect user. Whats wrong? views.py: from django.contrib.auth.mixins import PermissionRequiredMixin from django.core.urlresolvers import reverse_lazy class UserEditView(PermissionRequiredMixin, UpdateView): template_name = 'users/edit_user.html' form_class = UserEditForm model = User permission_required = ('auth.change_user') login_url = None redirect_field_name = reverse_lazy('dashboard') LOG in terminal: LevelName: WARNING | Message: Not Found: /accounts/login/ LevelName: WARNING | Message: "GET /accounts/login/?/=/user/50/edit/ HTTP/1.1" 404 2838 Also I tried next. If in settings.py I set LOGIN_URL = reverse_lazy('administration_login')in terminal I see but it dont redirect user: LevelName: INFO | Message: "POST /user/50/edit/ HTTP/1.1" 302 0 LevelName: INFO | Message: "GET /login/?/=/user/50/edit/ HTTP/1.1" 302 0 LevelName: INFO | Message: "GET / HTTP/1.1" 200 2427 QUESTION: Can someone say how to make correct redirection to custom url if user don't have permission? -
Django - get_queryset() missing 1 required positional argument: 'request'
I was trying to make an API using REST Framework for uploading a file to the server and my codes are below. If you have any other easy method to do the same please post your code. models.py from django.db import models # Create your models here. class FileUploader(models.Model): file = models.FileField() name = models.CharField(max_length=100) #name is filename without extension version = models.IntegerField(default=0) upload_date = models.DateTimeField(auto_now=True, db_index=True) owner = models.ForeignKey('auth.User', related_name='uploaded_files') size = models.IntegerField(default=0) def __str__(self): return self.name serializers.py class FileUploaderSerializer(serializers.ModelSerializer): class Meta: model=FileUploader fields='__all__' read_only_fields = '__all__' def validate(self, validated_data): validated_data['owner'] = self.context['request'].user validated_data['name'] = os.path.splitext(validated_data['file'].name)[0] validated_data['size'] = validated_data['file'].size return validated_data def create(self,validated_data): return FileUploader.objects.create(**validated_data) views.py class FileUploaderViewSet(viewsets.ModelViewSet): serializer_class = FileUploaderSerializer parser_classes=(MultiPartParser,FormParser) def get_queryset(self,request, *args, **kwargs): qs = super(FileUploaderViewSet, self).get_queryset(self,request, *args, **kwargs) qs = qs.filter(owner=self.request.user) return qs urls.py from django.conf.urls import url from django.conf.urls import url,include from django.contrib import admin from rest_framework import routers from rest_framework.authtoken.views import obtain_auth_token from rest_framework.urlpatterns import format_suffix_patterns from webapp import views from webapp.views import( UserCreateAPIView, UserLoginAPIView, FileUploaderViewSet, ) router = routers.DefaultRouter() router.register(r'upload', views.FileUploaderViewSet,base_name='file-view') urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include(router.urls)), #url(r'^upload/$',FileUploaderViewSet.as_view()), ] My requirement is that i need to upload a file to the server and the details of the uploaded file is to … -
django - remember data between bound and unbound forms
I'm defining a new Form, using __init()__ to modify the queryset for a ModelMultipleChoiceField and also adding a variable that i will use for the query: class ProductPickerForChangeForm(forms.Form): products = forms.ModelMultipleChoiceField(queryset=None) def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) total_amount = kwargs.pop('total_amount', None) super(ProductPickerForChangeForm, self).__init__(*args, **kwargs) if user and total_amount: self.fields['products'].queryset = # stuff self.total_amount = total_amount now, in views.py I'm creating a new unbound form for the GET request (and the parameters are coming from the user): form = ProductPickerForChangeForm(user=request.user, total_amount=amount) but, how to recover the data previously used for creating the unbound form when I'm creating the bound form from the POST request (the queryset could have changed in the meantime) - and without the risk of users messing with the posted data, too? -
Mixin fields not existing on Django migrations
Let's say I have this mixing: class Test(object): ...some logic... class TestMixin(models.Model): db_field = django database field test = Test() # not a database field class Meta: abstract = True class Foo(TestMixin, models.Model): ... more db fields ... I am having a strange issue here. If I inspect Foo through django shell I can see both fields, db_field and test But if I create this migration: from __future__ import unicode_literals from django.db import migrations def custom_operation(apps, schema_editor): Foo = apps.get_model('django_app', 'Foo') stuffs = Foo.objects.all() for stuff in stuffs: print stuff.test # this doesnt exist class Migration(migrations.Migration): dependencies = [ ... ] operations = [ migrations.RunPython(custom_operation), ] And if I add a breakpoint at Test() __init__ it gets called through the shell or Django but not when running the migration. Which is the differente between with using the model through the migration? -
DJango REST Framework: add additional functionality to ModelViewSet create method
I am attempting to add to the django server additional functionality upon different host requests. To do do so, I overridden the ModelViewSet functions with thought to add functionality within those functions. What I saw is that when setting a breakpoint on retrieve and list (GET requests), the debugger stopped. But when trying to break on create or update (POST requests) the debugger didn't break. How to resolve this? class GraphViewSet(ModelViewSet): queryset = Graph.objects.all() serializer_class = GraphSerializer def create(self, request, *args, **kwargs): response = super(ModelViewSet, self).create(request, args, kwargs) return response def retrieve(self, request, *args, **kwargs): response = super(ModelViewSet, self).retrieve(request, args, kwargs) return response def update(self, request, *args, **kwargs): response = super(ModelViewSet, self).update(request, args, kwargs) return response def partial_update(self, request, *args, **kwargs): response = super(ModelViewSet, self).partial_update(request, args, kwargs) return response def destroy(self, request, *args, **kwargs): response = super(ModelViewSet, self).destroy(request, args, kwargs) return response def list(self, request, *args, **kwargs): response = super(ModelViewSet, self).list(request, args, kwargs) return response def post(self, request, *args, **kwargs): response = super(ModelViewSet, self).post(request, args, kwargs) return response Python 3.6.3 Django 1.11.7 djangorestframework 9.0.1 Appreciate also any additional possible solutions for adding functionality on the server side to the different client requests. -
Unable to debug with DRF and GCP in Pycharm
I'm using Pycharm to develop a REST API (with Django Rest Framework - DRF). I started the project without Google Cloud Plateform (GCP) and could debug locally without any problem. Now I'm using GCP with Google App Engine (GAE) and run/debug buttons on Pycharm don't launch the project locally. When pushing the "Run" button I got this message: /Users/XXX/Collector/bin/python /Users/XXX/PycharmProjects/XProject/manage.py runserver 127.0.0.1:8000 Traceback (most recent call last): File "/Users/XXX/PycharmProjects/XProject/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/XXX/google-cloud-sdk/platform/google_appengine/lib/django-0.96/django/core/management.py", line 1520, in execute_from_command_line parser = DjangoOptionParser(usage=get_usage(action_mapping), version=get_version()) File "/Users/XXX/google-cloud-sdk/platform/google_appengine/lib/django-0.96/django/core/management.py", line 1501, in get_usage available_actions = action_mapping.keys() AttributeError: 'list' object has no attribute 'keys' I found a workaround to launch the project locally with "python manage.py runserver" but I can't run the server locally in debug which is very painfull for development. Does anybody know how to resolve this problem? -
I'm new in python/django thing so I can't access my project while running an virtual
enter image description here I can't oppen the "settings.py" file from here. Wich steps do I have do take to work it out? -
Form with list of members of my group [Django Admin]
How could I customize Django Admin (GROUP)? When I log in to system as no real admin, I would like to display only form with list of members of group in which I am. Thanks so much. -
Is there a way to host a django server on a mobile device?
Have a couple of unused android phones. As android has linux behind the scenes, wanting to know that is there a way to host a server using the phones? -
How can I change header when user is logged in django?
I have two headers header.html and headersuccess.html . I user is logged in, I need to change the header.html as headersuccess.html. How can I able to implement that? My views.py is.. By this I am going to loginsuccess.html.. So, if login is success I need to change header from header.html to hadersuccess.html def logsuccess(request): if('loggedIn' in request.session): id = request.session['uid']; return render(request,"loginsuccess.html",{'uid':id}); else: return render(request,"failed.html",{}); I am getting uid using this. I am using html and vue js for displaying. -
Django : can't add foreign key constraint while migrate table in mysql
I have bunch of tables and tried to do migration which is change Charfield into manytomany field. However while I am doing this I encountered this error. What I trying to do was alter columns in the table that already has data, and create two new tables that related to new columns. I have no idea how I can solve this. The error log is this. Operations to perform: Apply all migrations: food Running pre-migrate handlers for application food Running pre-migrate handlers for application admin_tools Running pre-migrate handlers for application theming Running pre-migrate handlers for application menu Running pre-migrate handlers for application dashboard Running pre-migrate handlers for application admin Running pre-migrate handlers for application auth Running pre-migrate handlers for application contenttypes Running pre-migrate handlers for application sessions Running pre-migrate handlers for application rest_framework Running migrations: Applying fiid.0113_auto_20171127_1852...Traceback (most recent call last): File "/home/i-06/PycharmProjects/food-front-service/.venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/home/i-06/PycharmProjects/food-front-service/.venv/lib/python3.5/site-packages/django/db/backends/mysql/base.py", line 101, in execute return self.cursor.execute(query, args) File "/home/i-06/PycharmProjects/food-front-service/.venv/lib/python3.5/site-packages/MySQLdb/cursors.py", line 250, in execute self.errorhandler(self, exc, value) File "/home/i-06/PycharmProjects/food-front-service/.venv/lib/python3.5/site-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler raise errorvalue File "/home/i-06/PycharmProjects/food-front-service/.venv/lib/python3.5/site-packages/MySQLdb/cursors.py", line 247, in execute res = self._query(query) File "/home/i-06/PycharmProjects/food-front-service/.venv/lib/python3.5/site-packages/MySQLdb/cursors.py", line 411, in _query rowcount = self._do_query(q) File "/home/i-06/PycharmProjects/food-front-service/.venv/lib/python3.5/site-packages/MySQLdb/cursors.py", line 374, in _do_query … -
Why does range is 'reversed' when filtering objects?
I've got a car database and I show "similar cars" on each car's page. To sort the similar cars, I'm going through this filter: min_power = int(float(car.power_ps) * .8) max_power = int(float(car.power_ps) * 1.2) similar_cars = Car.objects.filter(power_ps__range=(min_power, max_power)) This mostly works. However, similar cars don't show up on some cars' pages. When I tweaked my code a bit, I figured that If I use power_kw (another power unit and model field) instead of power_ps in my queryset, similar cars successfully show up on those pages. But this time, they don't show up on some other cars' pages. So, I have model instances that: don't show similar cars when used power_ps but get them with power_kw don't show similar cars when used power_kw but get them with power_ps show similar cars either when I use power_ps or power_kw When I investigated further, I found out that If I swap the min_power and max_power in my range filter, similar cars that don't show up before work successfully. All in all, my range variables are somehow 'reversed' in some instances. Any suggestion or feedback will be welcomed and greatly appreciated. Thank you. -
static files doesn't load on cache clear?
I have a Django project when I set Debug=true and cache clear when running the static files will not load. If I set it to false the page will load with static files. Any solution to this problem -
After I cut the model to other model file, I can not import it from the new model file now
After I cut the TradeRecord model from (xxxx管理员后台.财务管理.qiyun_admin_financialmanage_ordermanage.models) to (xxxx管理员后台.财务管理.qiyun_admin_financialmanage_financialmanage.models), you should pay attention the app name is qiyun_admin_financialmanage_financialmanage, upper it there are two level directories for grouping apps. and I also makemigrations and migrate, and now I import the TradeRecord: from xxxx管理员后台.财务管理.qiyun_admin_financialmanage_financialmanage.models import TradeRecord but get DoesNotExist: File "/Users/luowensheng/Desktop/QIYUN/Project/Qiyun02/用户管理后台/产品管理/user_admin_productmanage_cloudserver/api/views.py", line 102, in get raise e File "/Users/luowensheng/Desktop/QIYUN/Project/Qiyun02/用户管理后台/产品管理/user_admin_productmanage_cloudserver/api/views.py", line 100, in get verifyTradeRecord(traderecord_num=traderecord_num, user=user) File "/Users/luowensheng/Desktop/QIYUN/Project/Qiyun02/用户管理后台/产品管理/user_admin_productmanage_cloudserver/api/utils.py", line 108, in verifyTradeRecord traderecord = TradeRecord.objects.get(traderecord_num=traderecord_num) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/models/query.py", line 380, in get self.model._meta.object_name xxxx管理员后台.财务管理.qiyun_admin_financialmanage_financialmanage.models.DoesNotExist: TradeRecord matching query does not exist. -
Delete or Update if 3 object existed at the same time - Django Rest Framework
I'm building LIKE, UNLIKE and CLAPPING function for my blog website. I have models like this: Model REACTION (Like, unlike and clapping) class Reaction(models.Model): REACT_TYPES = ( (LIKE, 'Like'), (CLAPPING, 'Clapping') ) user = models.ForeignKey(User) react_type = models.CharField(max_length=100, choices=REACT_TYPES, default='LIKE') timestamp = models.DateTimeField(auto_now_add=True, null=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True) object_id = models.PositiveIntegerField(null=True) content_object = GenericForeignKey('content_type', 'object_id') class Meta: unique_together = ('user', 'content_type', 'object_id') Serializers model REACTION from models import Reaction class ReactCreateUpdateSerializer(ModelSerializer): class Meta: model = Reaction fields = [ 'user', 'react_type', 'content_type', 'object_id', ] I assumed there is a object with LIKE available created before. I want to build a function can do these things: If user use again POST methods with 4 objects existed: user, content_type, object_id, react_type=LIKE. It becomes deleting object. (UNLIKE). Then if post one more, it becomes creating object again. (LIKE) If user use POST methods with 4 objects existed: user, content_type, object_id, react_type=CLAPPING. It becomes updating the available reactions in database with update 2 fields: react_type and timestamp, all other fields not changed. I think this is a problem for every one when he build API for website needs reaction. So Hope your enthusiastic help. Thanks in advance! -
What django model field should I use to store a duration of time less than a full day?
I am storing the duration of time for a time keeping system. No need to store timezone info. Initially I decided to store the value a a DecimalField because there was a restriction of closest 15 minutes meaning the decimal would work as it would be restricted to 0.25 increments. Eventually I decided that is no good as what if in future the 15 minute increments requirement is removed. I do not need to store seconds I need to report on totals at the end of the month So I pretty much have these 3 data types and I am struggling to choose which would be best. TimeField PositiveIntegerField DurationField -
Python firebase admin sdk - Realtime update listener
Do you have any plan to add realtime update listener in python firebase admin sdk? I have django api service.I want to change my current authentication and authorization system to firebase authentication.Realtime data update listener is not available for python .So I have to call firebase server every time to authorize my user.It will make my api slower.What to do now for django in this situation? Thanks in advance. Goutom Roy -
ValueError: invalid literal for int() with base 10: '' Can't I cast int to None?
I got an error,ValueError: invalid literal for int() with base 10: '' . I wrote def convert_json(request): id = None print(type(id)) json_body = json.loads(request.body) for index, content in json_body.items(): if index == "ans": id = content id = int(id) return id When json_body does not have "ans" key,id has None and the error happens in the code of id = int(id) .print(type(id)) print out class 'str' so I really cannot understand why I cannot convert str into int.Is None special kind of str?I wanna put empty value to id when json_body does not have "ans" key.How should I fix this? -
Django error after changes to the model.py and then migrations
So before everything went south, i have this user model with a mobileNo attribute, it is using a CharField at first. So i decided to change it to IntegerField then proceed to do the makemigrations then migrate command. But suddenly this error pop up after doing that Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\Baka No Onii Chan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "C:\Users\Baka No Onii Chan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Baka No Onii Chan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Baka No Onii Chan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Users\Baka No Onii Chan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\migrate.py", line 204, in handle fake_initial=fake_initial, File "C:\Users\Baka No Onii Chan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\Baka No Onii Chan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\Baka No Onii Chan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\Baka No Onii Chan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\Baka No Onii Chan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\operations\fields.py", line 216, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "C:\Users\Baka No Onii Chan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\base\schema.py", line 515, in alter_field old_db_params, new_db_params, strict) File "C:\Users\Baka No Onii Chan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\postgresql\schema.py", line … -
Django page not found 404
i get this error while i am trying to run my django server and i am getting the following error I don't know why and the urls file is in the myproject/test/urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('wars.urls')), ] myproject/test/settings.py ROOT_URLCONF = 'test.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] in the same folder I have another folder wars which has the urls too , in myproject/wars/ursl.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^auth/$', views.authenticate_for_token, name='authenticate'), url(r'^records/all/(?P<token>[1-9]_[a-z]*)/$', views.records_list_all, name='records_all'), url(r'^records/(?P<offset>[0-9]*)/(?P<limit>[1-9][0-9]*)/(?P<token>[1-9]_[a-z]*)/(?P<comp_code>[0-9]{2,8})/$', views.records_list_subset, name='records_all'), url(r'^records/save/$', views.records_save, name='records_save'), url(r'^dropdown/(?P<comp_code>[0-9]{2,8})/(?P<token>[1-9]_[a-z]*)/$', views.get_dropdown_lists, name='dropdown_lists'), url(r'^approve/$', views.approve_category, name='approve_category'), url(r'^approve/delete/$', views.approve_category_delete, name='approve_category_delete'), url(r'^hide-sheet/$', views.hide_sheet, name='hide_sheet'), url(r'^hide-sheet/delete/$', views.hide_sheet_delete, name='hide_sheet_delete'), url(r'^template/download/$', views.template_download, name='template_download'), url(r'^template/upload/$', views.template_upload, name='template_upload'), url(r'^overview/$', views.Overview.as_view(), name='admin_overview'), url(r'^login/$', views.LoginView.as_view(), name='login'), url(r'^logout/$', views.logout_func, name='logout'), url(r'^user/$', views.UserManagement.as_view(), name='user_mgmt'), url(r'^user/upsert/$', views.user_create, name='user_create'), url(r'^debug/$', views.debug_func, name='debug'), ] I am trying to figure out the problem. it seems that i cant reach the page. and in the python server it says Not Found: / [27/Nov/2017 09:44:54] "GET / HTTP/1.1" 404 5189 -
How to delete a django model from an application to result in a table drop
I have a django model in my app that looks like this(assuming all required modules are imported) class profile(models.Model): user = models.OneToOneField(User) mobile_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="phone number must be entered in hte format '+23474857934'. Up to 15 digits allowed") mobile = models.CharField(validators=[mobile_regex], max_length=15, blank=True, null=True) I made a (silly)mistake spelling the profile name, and would like to correct this, is there a way to this without affecting the data that might already be stored. changing the name and making a migration doesn't reflect the change sorry if this question seems a bit trivial,I'm a newbie at django thanks for understanding -
django model field default function calls two times
I've got model FTPUser. Field password populates automatically by function pass_generator. class FTPUser(models.Model): ...... password = models.CharField(max_length=250, default=pass_generator) def pass_generator(size=12, chars=string.ascii_letters + string.digits): passwd = ''.join(random.choice(chars) for _ in range(size)) return passwd Model FTPUser is managed in django admin: class FTPUserAdmin(admin.ModelAdmin): readonly_fields = ['password', ] As shown above, field password is read only and when admin creates new instance in FTPUser model he can't change field password, only read it(what I need), vaule of password field generates by function. The problem is django calls function pass_generator two times! First time, when inicializes create form and second time whem saves instance to database. So in database we got absolutely different password than was shown to admin! I tested to set password filed editable and in that case it works correctly, so I think probles is when password filed is read only it shown as string at creation, not an inpun filed, so on save model FTPUser doesn't get that vaule from creation form and calls function pass_generator second time. How can I solve this? -
Workaround for missing Distance function in Django 1.8
Let consider the following models: class Event(models.Model): name = models.CharField(max_length=255) class Address(models.Model): event = models.ForeignKey(to=Event,related_name='addresses') coordinates = models.PointField() Now I want to find events within some proximity. I can do this: Event.objects.filter( addresses__in=Address.objects.filter( coordinates__distance_lte=(my_location, D(km=42)) ) ) However, I also want to have the distance value in that queryset but I don't know how to annotate this. In latest Django, I could use https://docs.djangoproject.com/en/dev/ref/contrib/gis/functions/#distance How can I achieve this 1.8? -
Unable to integrated bootstrap template into django (python)
I am new to Django and python. I am struggling with integrating bootstrap template into my simple django application. I tried all "static" related django stuffs at (https://docs.djangoproject.com/en/1.11/howto/static-files/) but not get solution yet. When I check under "Network" in Google chrome browser console all css, Javascript & images are loaded successfully and gives "200" code. But at the time of execution classes are not applied and simple html page appears. Project directory structure and template are loaded here : https://github.com/husainathar/parking/tree/master/parking Please advise me to resolve this issue. Thanks -
How to use authentication token in Django with Django OAuth Toolkit (not REST)
I'm using the following library http://django-oauth-toolkit.readthedocs.io/ which seems to not be as well documented as I would like, and after I followed its tutorial I am able to have a working system in which I have protected views that need the authorization token, and I can access them using curl and adding the token. Curl is nice to test, but it's not practical, and I failed at developing it. So I have a very simple protected view: class Test(ProtectedResourceView): def get(self, request, *args, **kwargs): return HttpResponse('Hello, OAuth2!') If I try to access, I will get a 403, and if I ask for the token and put it in the header using curl I can actually get it to work. In the other hand, I have another view that gets the authorization_token, lifetime, refresh_token, .. in a dictionary (after using JSON from Django). At this point I'm lost. I don't know what to do with the authorization token so that the user can actually use it and access to the protected view. I tried to manually add the token to the cookies but it didn't work and doesn't seem to be a good idea neither. I guess after I do something, …