Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Editing a photo using PIL - Django 2+ "required positional argument: 'fp'"
I am new to Django and for the first time trying to use the Pillow library to edit my photo without changing the aspect ratio. I created the following code: if request.method == 'POST' and 'btn_custom_img' in request.POST: custom_img_form = CustomImgForm(request.POST, request.FILES) if custom_img_form.is_valid(): cd = custom_img_form.cleaned_data #owner.basic_img = cd['custom_img'] image = Image.open(cd['custom_img']) (w, h) = image.size if (w > 1000): h = int(h * 1000. / w) w = 1000 image = image.resize((w, h), Image.ANTIALIAS) owner.basic_img = image.save() owner.save() else: custom_img_form = CustomImgForm() But I get the following error. owner.basic_img = image.save() TypeError: save() missing 1 required positional argument: 'fp' I think this is due to the lack of file name. ut I don't want to give it. I would like django to always automatically uniquely name my file (as it would do without using Pillow). How to fix my code to change the size of the photo and save it in my object correctly. Any help will be appreciated. -
Custom filtering and grouping in Django Rest Framework
I'm working on functionality which allows users to create custom filters on specific models and store those results as a group. As a working example (imports omitted for brevity): class Client(models.Model): email = CIEmailField() class Activity(models.Model): client = BaseForeignKey("client.Client", null=True, related_name="logged_activities") employee = BaseForeignKey("business.Employee", null=True, related_name="logged_activities") created = models.DateTimeField(auto_now_add=True) We want to create filters which will group Clients on Activitys based on the creation time and associated Employee and store those results in a group to be used later. This is pretty straightforward task, except a user is allowed to modify the filter configuration and update fields on a Client, both of which may change whether or not a Client matches the filter criteria. (Note: in this example it's not possible updating a Client could change the result set, but future filters will.) I'd like a many-to-many so we can easily get the groups a client is in, and conversely get the clients in a group, but it's not clear to me the best way to handle the filter configurations. This is currently supported in our system but the filters don't work correctly and the filter queries are run whenever information about a group needs to be used. Given that, … -
How to add Title/Customize response in DRF Browsable API
I want to add new Top Level Element in my Browsable API response. Currently, It displays like this:- This one is the response in browsable API { "count": 33, "next": "http://127.0.0.1:8000/api/apphosts/?page=2&search=test", "previous": null, "results": [ { "_meta": { "hostvars": { "wyak-tn-e2.kyisc.us.test.com": "{'environment': 'lab'}" } } }, { "_meta": { "hostvars": { "jsifn-tn-e3.kyisc.us.test.com": "{'environment': 'uat'}" } } }, But I need a response in this format, _meta and hostvars required at top level *{ "count": 33, "next": "http://127.0.0.1:8000/api/apphosts/?page=2&search=test", "previous": null, "results": [ { "_meta": { "hostvars": { "wyak-tn-e2.kyisc.us.test.com": "{'environment': 'lab'}" }, { "jsifn-tn-e3.kyisc.us.test.com": "{'environment': 'uat'}" }, { "pro-tn-e3.kyisc.us.test.com": "{'environment': 'pro'}" } } } ] }* My Serializer code is this one, This one contain def to_presentation method which converts output to new format. class AppHostSerializer(serializers.ModelSerializer): dynamic_data = serializers.CharField(read_only=True) def to_representation(self, instance): representation = super(AppHostSerializer, self).to_representation(instance) host_name = representation.pop('host_name') host_vars = representation.pop('host_vars') group_vars = representation.pop('group_vars') description = representation.pop('description') repackaged = {"_meta": {"hostvars": {host_name: host_vars} } } return repackaged class Meta: model = AppHost fields = ( 'description', 'host_name', 'host_vars', 'group_vars', 'dynamic_data', 'group_vars', ) -
Getting "detail": "Authentication credentials were not provided."
When I login via POSTMAN, I get a toke, when I try to use to the token to access the apartments endpoint, I get "detail": "Authentication credentials were not provided." Is there anything I am doing wrong? views.py class ApartmentList(APIView): permission_classes = [IsAuthenticated] serializer_class = ApartmentSerializer queryset = Apartment.objects.all() def get(self,request): apartments = Apartment.objects.all() serializer = ApartmentSerializer(apartments, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = ApartmentSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) views.py Login View @csrf_exempt @api_view(["POST"]) @permission_classes((AllowAny,)) def login(request): phone_number = request.data.get("phone_number") if phone_number is None: return Response({'error': 'Please provide your phone number'}, status=HTTP_400_BAD_REQUEST) user = authenticate(phone_number=phone_number) if user: serializer = TokenSerializer(data={ # using drf jwt utility functions to generate a token "token": jwt_encode_handler( jwt_payload_handler(user) )}) serializer.is_valid() return Response(serializer.data) return Response(status=status.HTTP_401_UNAUTHORIZED) settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASS':[ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], 'DEFAULT_AUTHENTICATION_CLASS':[ 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ], } -
Django - Model Meta options app_label not working
I have following Django app structure apps ├── apartment │ ├── migrations │ ├── apps.py │ ├── models │ │ ├── apartment.py │ │ ├── core.py I added apps.apartment.apps.ApartmentConfig to INSTALLED APPS. And apartment.py look like: class Apartment(Model): class Meta: app_label = 'apartment' When I run makemigrations, it says no changes detected. And I wrote following code in my apps.py. class ApartmentConfig(AppConfig): name = 'apps.apartment' def ready(self): print(self.label) # returns 'apartment' from .models.apartment import Apartment Now it is working fine. Should I always do this when writing a new model?. As a documentation says: If a model is defined outside of an application in INSTALLED_APPS, it must declare which app it belongs to: app_label = 'myapp' Can anyone explain me why it's not working? Are there better ways to solved this without importing all the models? -
How to update foreignkey field manually in UpdateView post method?
I am trying to manually change a foreign key field (Supplier) of a model (Expenditure). I override the UpdateView post method of Expenditure and handle forms for other models in this method too. A new SupplierForm is also rendered in this view and I am tracking if this form is changed via has_changed() method of the form. If this form has changed, what I ask is overriding the related_supplier field of ExpenditureForm and picking newly created Supplier by this statement: if supplier_form_changed: new_supplier = related_supplier_form.save(commit=False) new_supplier.save() .... # This statement seems to have no effect self.object.related_supplier = new_supplier I override the post method with super(), so even though I explicitly state save() method for all related forms, however I don't call the save method of main model (Expenditure) since it is already handled after super(). This is what start and end of my method looks like; def post(self, request, *args, **kwargs): context = request.POST related_receipt_form = self.receipt_form_class(context, request.FILES) related_supplier_form = self.supplier_form_class(context, request.FILES) self.object = self.get_object() related_receipt = self.object.receipt related_supplier_form = self.supplier_form_class(context) expenditure_form = self.form_class(context) inlines = self.construct_inlines() .... return super().post(self, request, *args, **kwargs) You may find the full code of my entire view here: https://paste.ubuntu.com/p/ZtCfMHSBZN/ So my problem is self.object.related_supplier … -
Django Admin - Create object with data from external API
I'm not new to Django, actually I have been using it for a long time now, but I barely use the Django Admin, so there are still a few things that I still don't get completely. I have a model Profile which is created by an User providing an id. I get all the data for creating that profile from an external API with that id, so it is easy to do that in the main API: the User makes a call providing the id, I make a request to this external API, create the object with the provided information and get back to the User with the result. Since I'm starting to use Django admin for an quick/easier User interaction with the data, I wanted to modify the add_form (not the change_form) so there is form with one field, the username and a button to save the data. The idea is the same, get the username, make the cal to the external API, create the object and show it in the Django admin. But I'm not being able. I have tried with overriding the add_form and overriding the ProfileAdmin.save_form but when I save it will fail because of the … -
Python Celery callback failure method executing on each retry
I have a simple celery retry infrastructure but the issue I am facing is that my on_failure method is called on each retry. I am looking for a place where I can add logic that after retries are finished I would like to set an object status to failure. class BaseTask(Task): abstract = True def on_success(self, obj, **kwargs): # this is called only once when the task is completed obj.success=True obj.save() def on_failure(self, obj, **kwargs): # this is called everytime on retry. obj.error=True; obj.save() @task(bind=true, base=BaseTask, max_retries=5, default_retry_delay=60*60) def retry_my_logic_on_error(obj): try: obj.full_name = requests.get(foo) except Exception: self.retry() Is there a different method that is called on failure when the retries are exhausted? Thanks. -
Django test showing Assertion:Error even if the assertion is true
This might not be the best way to do it, as I am learning how to test with Django, but when I try to test a view that involves a form I get: AssertionError: <User[37 chars], fields=(email;first_name;last_name;role;password1;password2)> != <User[37 chars], fields=(email;first_name;last_name;role;password1;password2)> Without considering the fact that the message is not really helpful as the two sides of the equations look exactly the same, the test is the following: class SignUpViewTest(TestCase): def test_get_request(self): path = '/signup/' data = { 'email': '', 'first_name': '', 'last_name': '', 'role': 'Student', 'password1': '', 'password2': '', } form = UserCreationForm() response = self.client.get(path, data=data) print(response.context['form']) print(form) self.assertEqual(response.status_code, 200) self.assertEquals(response.context['form'], form) Being the view: def signup(request): form = UserCreationForm() if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() messages.success(request, f'Good news {form.cleaned_data["first_name"]}, you have successfully signed up.') return redirect(home) template_name = 'signup.html' context = { 'form': form, } return render(request, template_name, context) Now, as you can see, I am printing the two forms (one is the response context and one is the empty form I request. I don't think you need to see code from models and forms as the error message is quite explicit, even thou I can't see the error. Also, I have checked … -
Unable to restart apache server after updating config file
I have updated my config file so that i can run my django project and then enable config file using sudo a2ensite weeffective.com.conf And then i am trying to restart my apache server sudo service apache2 restart Which gives following error Job for apache2.service failed because the control process exited with error code. See "systemctl status apache2.service" and "journalctl -xe" for details. Then run following to identify whats wrong journalctl -xe Which gives me following error Mar 27 12:25:20 instance-weeffictive sudo[13187]: pam_unix(sudo:session): sessio Mar 27 12:25:59 instance-weeffictive sudo[13192]: root : TTY=pts/2 ; PWD=/et Mar 27 12:25:59 instance-weeffictive sudo[13192]: pam_unix(sudo:session): sessio Mar 27 12:25:59 instance-weeffictive systemd[1]: Starting The Apache HTTP Server -- Subject: Unit apache2.service has begun start-up -- Defined-By: systemd -- Support: http://www.ubuntu.com/support -- -- Unit apache2.service has begun starting up. Mar 27 12:25:59 instance-weeffictive apachectl[13198]: apache2: Syntax error on Mar 27 12:25:59 instance-weeffictive apachectl[13198]: Action 'start' failed. Mar 27 12:25:59 instance-weeffictive apachectl[13198]: The Apache error log may Mar 27 12:25:59 instance-weeffictive systemd[1]: apache2.service: Control proces Mar 27 12:25:59 instance-weeffictive sudo[13192]: pam_unix(sudo:session): sessio Mar 27 12:25:59 instance-weeffictive systemd[1]: apache2.service: Failed with re Mar 27 12:25:59 instance-weeffictive systemd[1]: Failed to start The Apache HTTP -- Subject: Unit apache2.service has failed -- … -
How can I place a block of my code into a function?
I have this code in views.py. '''UIERARCHY - INDEX PAGE - NACH LAENDER - COUNTRIES - DEBITORS - ORDERS LEVEL-3''' def uland_world_country_debitor(request, world_id, country_id, debitor_id): qset = BigTable.objects.values( 'deb_nr_f__dcountry__wcode_f__code', #world 'deb_nr_f__dcountry__wcode_f__code_name', #world 'deb_nr_f__dcountry__country_code', #country 'deb_nr_f__dcountry__country_name', #country 'deb_nr_f__dnr', #debitor 'deb_nr_f__dname', #debitor 'id_nr_f__idnr', #order 'id_nr_f__bezeichnung', #order ).annotate( tmp_code=F('id_nr_f__idnr'), tmp_descr=F('id_nr_f__bezeichnung') ).values('tmp_code','tmp_descr' ).order_by('-nerl_2019__sum' ).annotate( abs_2016__sum=Sum('abs_2016'), abs_2017__sum=Sum('abs_2017'), abs_2018__sum=Sum('abs_2018'), abs_2019__sum=Sum('abs_2019'), abs_2020__sum=Sum('abs_2020', output_field=FloatField())/Value(0.205, output_field=FloatField()), nerl_2016__sum=Sum('nerl_2016', output_field=FloatField())/Value(1000, output_field=FloatField()), nerl_2017__sum=Sum('nerl_2017', output_field=FloatField())/Value(1000, output_field=FloatField()), nerl_2018__sum=Sum('nerl_2018', output_field=FloatField())/Value(1000, output_field=FloatField()), nerl_2019__sum=Sum('nerl_2019', output_field=FloatField())/Value(1000, output_field=FloatField()), nerl_2020__sum=Sum('nerl_2020', output_field=FloatField())/Value(205, output_field=FloatField()), db2_2016__sum=Sum('db2_2016', output_field=FloatField())/Value(1000, output_field=FloatField()), db2_2017__sum=Sum('db2_2017', output_field=FloatField())/Value(1000, output_field=FloatField()), db2_2018__sum=Sum('db2_2018', output_field=FloatField())/Value(1000, output_field=FloatField()), db2_2019__sum=Sum('db2_2019', output_field=FloatField())/Value(1000, output_field=FloatField()), db2_2020__sum=Sum('db2_2020', output_field=FloatField())/Value(205, output_field=FloatField()), ).exclude(abs_2016__sum = 0, abs_2017__sum = 0, abs_2018__sum = 0, abs_2019__sum = 0 ).filter(deb_nr_f__dnr=debitor_id, ) Is there a way to assign a big piece of code, for example the large "annotate" block in the middle, to a function and thus shorten and simplify the notation? Thank you. -
Concurrency issue from read/write from table on multiple threads (race condition)
I am building an app where each user is assigned a task from a tasks table. In order to do so, we are going to mark an existing entry as deleted (flag) and then add an entry that holds the person responsible for the task in that table. The issue here is that if multiple users decide to get a task at the same time, the request would prioritize older entries over newer ones, so there is the chance they are going to read the same task and get assigned the same task. Is there a simple way around it? My first inclination was to create a singleton class that handles job distribution, but I am pretty sure that such issues can be handled by Django direct. What should I try? -
Find existing JWT token for user
I've got a function to manually create a new AccessToken for a user (using the rest_framework_simplejwt library): from rest_framework_simplejwt.tokens import AccessToken def create_access_token_for_user(user): access_token = AccessToken.for_user(user) Now I'm trying to write a test to verify that this is actually working as expected, and I can't seem to find any way of getting the AccessToken for a given user. The test should look something like: def test_access_token_created(client): user = create_user() create_access_token_for_user(user) access_token = AccessToken.get_token_for_user(user) # This, but real assert access_token is not None # Or some check to see if it exists The rest_framework_simplejwt docs don't seem to have anything that does this, or at least nothing that I've been able to use correctly. -
How do I get the ID of an image
I'm a Django beginner, how do I get the ID of each image uploaded with form? class Image(models.Model): imageuploader_profile=models.ForeignKey(settings.AUTH_USER_MODEL) upload_image=models.ImageField() def upload(request): if request.method == 'POST': form=UploadForm(request.POST, request.FILES) if form.is_valid(): post=form.save(commit=False) post.imageuploader_profile=request.user post.save() return redirect.... else: form=UploadForm -
How to return httpresponse in dajngo?
My scenerio I declare two functions and pass HTTP response also but it's not working .can you please tell me how to fix this issue. def sample1(): return HttpResponse('hi', status=200) def sample2(): sample1() return HttpResponse('hello', status=200) sample2() I got the output hello but i need hi only .what are mistake has occurred. -
2006, MySQL server has gone away
I’m running a Django application with MySQL db. An error 2006, MySQL server has gone away occurs some time after start when application tries to get query set of objects from database I have tried: set large value of wait_timeout at /etc/my.cnf (larger than CONN_MAX_AGE in settings.py in Django project) and restart server set large value of max_allowed_packet in /etc/my.cnf (up to 2G) make a thread that makes query to mySQL every minute call django.db.close_connection() before the access to db and nothing helps solving the problem -
Saving in django forms using FormView
I'm creating a form that will change the state of reserve book, I have this class LibraryReserveForm(CrispyFormMixin, forms.Form): def __init__(self, *args, **kwargs): self.manager = kwargs.pop('manager') super(LibraryReserveForm, self).__init__(*args, **kwargs) def save(self): self.instance.reserve_status = 'approved' self.instance.save() return self.manager models.py class ReservedBooks(TimeStampedModel): BOOK_RESERVE_STATUS = Choices( ('for_approval', "For Approval"), ('approve', "Approved"), ('cancelled', "Cancelled"), ('rejected', "Rejected") ) reserve_status = models.CharField( _('Status'), max_length=32, choices=BOOK_RESERVE_STATUS, default='for_approval' ) ... view class LibraryReserveView( ProfileTypeRequiredMixin, MultiplePermissionsRequiredMixin, FormView, ): model = ReservedBooks template_name = 'library/reserved_list.html' form_class = LibraryReserveForm def get_form_kwargs(self): kwargs = super(LibraryReserveView, self).get_form_kwargs() kwargs.update({ 'manager': self.request.user.manager, }) return kwargs urls url( r'^reserve/(?P<pk>\d+)/$', views.LibraryReserveView.as_view(), name='reserved' ), everytime I submit the button I print something in the save() method of the forms but its not printing something therefore that method is not called. How do you called the save method ? Thanks -
Django Queryset : Get the Max number of M2M items by M2M category
I've been stuck for hours on a queryset issue. Here are my models : class AssetCategory(models.Model): name = models.CharField('Category name', max_length=255) class Asset(models.Model): name = models.CharField('Asset name', max_length=255) category = models.ForeignKey(AssetCategory, on_delete=models.SET_NULL) class Product(models.Model): name = models.CharField('Product name', max_length=255) assets = models.ManyToManyField(Asset, related_name='products') I would like to be able to get the list of categories with the max number of assets a product has (whatever this product is) For example, if I have : Product 1: 2 assets in a category A 1 asset in a category B Product 2: 5 assets in a category A 0 assets in a category B I would like to be able to know that : the category A, in all my products, get a maximum of 5 assets the category B in all my products get a maximum of 1 asset I tried to play with aggregate or annotate, on different tables, but I don't succeed to get what I want.. The closest thing I tried was : asset_categories = AssetCategory.objects.annotate(max_in_product=Count('asset__products')) But of course it just gives me for each category, the sum of assets used in my products so in my example : Category A : 7 Category B : 1 -
'ModelFormOptions' object has no attribute 'concrete_fields' in django
I am updating a my model. but it's showing me this error: 'ModelFormOptions' object has no attribute 'concrete_fields'. kindly guide me what is mistake i'm doing. Your help will be appreciated. Thank You views.py class EditProduct(TemplateView): template_name = 'stock/editproduct.html' def get(self, request, product_id): productedit = get_object_or_404(Product, pk=product_id) data=Product.objects.get(id=product_id) form = EditProductForm(instance=data) args = {'form':form, 'productedit':productedit} return render(request, self.template_name, args) def post(self, request, product_id): data = Product.objects.get(id=product_id) form = EditProductForm(instance=data) form = EditProductForm(request.POST, request.FILES, instance=form) if form.is_valid(): productadded = form.save(commit=False) productadded.saler = request.user productadded.pub_date = timezone.datetime.now() productadded.save() return redirect('stock') else: args = {'form': form} return render(request, self.template_name, args) TRACEBACK File "C:\Users\Adil Ijaz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Adil Ijaz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Adil Ijaz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Adil Ijaz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\Adil Ijaz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Adil Ijaz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "C:\Users\Adil Ijaz\Desktop\onlineProject\market\stock\views.py", line 109, in post form = EditProductForm(request.POST, request.FILES, instance=form) File "C:\Users\Adil Ijaz\Desktop\onlineProject\market\stock\forms.py", line 39, in __init__ super(EditProductForm, self).__init__(*args, **kwargs) File "C:\Users\Adil Ijaz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\forms\models.py", line 293, in __init__ object_data = model_to_dict(instance, opts.fields, opts.exclude) File "C:\Users\Adil … -
How can i generate static api documentation for django rest APIs?
I went through the documentation and tried to use swagger and coreapi, but both are interactive, I want same api documation with out interation. Is is possible? -
Django select last rows of all types
In django I have a table that contains rows with a column "type" and a column "inserted_date". I would like to select the last inserted rows of all types. How can I do this in django? -
How to redirect the user to the desired link after registration?
How to redirect the user to the desired link after registration? What I do is not working. I want to redirect to "new_channel". Thanks in advance. views.py class RegisterFormView(FormView): form_class = UserCreationForm success_url = "main/my_newsagent/new_channel.html" template_name = "main/register.html" def form_valid(self, form): form.save() return super(RegisterFormView, self).form_valid(form) urls.py urlpatterns = [ path('', views.index, name='index'), path('main/register/', views.RegisterFormView.as_view(), name='register'), path('main/login/', views.LoginFormView.as_view(), name='login'), path('main/logout/', views.LogoutView.as_view(), name='logout'), path('main/my_news_agent/', views.my_newsagent, name='my_newsagent'), path('main/my_news_agent/new_channel', views.new_channel, name='new_channel'), path('main/edit_profile', views.edit_profile, name='edit_profile'), path('main/my_newsagent_page', views.my_newsagent_page, name='my_newsagent_page'), path('main/my_newsagent/new_channel.html', views.new_channel, name='new_channel'), ] -
Passing forms values/strings into views.py and back to template
I know that there's a lot of topics with this matter, but I just can't get my code working. Can you please help me what is wrong with my Django website school project. So the problem gets easier to understand lets assume that I want to make a basic search bar to my site, where: user can submit a word the word goes into views.py file where from views.py file it will get back to template with render function My current code looks like this: HOME.HTML CODE <!-- Submit hashtag search --> <form action="/search/" method="get" > <input type="text" name = "q"> <input type="submit"value="Search"/> </form> <h1> hashtag </h1> VIEWS.PY CODE from django.shortcuts import render import tweepy, csv, sys, re from website import twitterAPI # This is supposed to make the homescreen blank before submitting any word to the search box def home(request): return render(request, 'website/home.html') def about(request): return render(request, 'website/about.html') # When submitting a word to the search box this function should # return the word back to home.html as a 'context' def search(request): hashtag = 'You submitted: %r' % request.GET['q'] context = {'hashtag': hashtag} return render(request, 'website/home.html', context) Currently, the website opens like it should (blank page with a search … -
python project is not running in visual studio
hi i made this simple project https://github.com/dharmendrak603/myfirstproject and it was running properly earlier and i moved out to some other project, but now when i want to run this project it gives me error below. actually i don not remember the virtual envirment name aslo but i remember that it should be one of denvx or 111 . i am new to django and python. please help. django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
Generate access token using user instance (not username, password and grant_type)
I'm using Django REST Framework and using this library to provide token based authentication to the frontend applications. There is Login with Google implementation using django-allauth plugin. I want to generate access token when user login using social account. For handling social login and generating social account, I have created this view. class GoogleLoginView(LoginView): """ Enable login using google """ adapter_class = GoogleOAuth2Adapter serializer_class = CustomSocialLoginSerializer def login(self): self.user = self.serializer.validated_data['user'] self.token = TokenView().create_token_response(self.request) return self.token def post(self, request, *args, **kwargs): self.request = request self.serializer = self.get_serializer( data=self.request.data, context={'request': request} ) self.serializer.is_valid(raise_exception=True) url, header, body, status_ = self.login() return Response(json.loads(body), status=status_) The request data has user instance along with client_id and client_secret of the application. But this gives error '{"error": "unsupported_grant_type"}' Version django-oauth-toolkit==1.3.0