Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-filters filter by Boolean field with DRF
I'm following the tutorial here: https://www.django-rest-framework.org/api-guide/filtering/#djangofilterbackend (specifically the django-filter-backend section) and I am unable to get this to work. My goal is to retrieve a list of "containers" that have the "in_use" field set to True, but it keeps returning all the records in the table. I can't really see what I am missing. I have added django-filters to my installed apps list and also added this to my REST_FRAMEWORK block: 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'] This is the API endpoint I'm trying to hit in postman: http://127.0.0.1:8000/displaydata/containers?in_use=True I've tried passing both 'True' and 'true', as well as 0s and 1s. views.py class ContainerViews(APIView): def get(self, request, id=None): if id: container = Container.objects.get(id=id) serializer = ContainerSerializer(container) return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: containers = Container.objects.all() serializer = ContainerSerializer(containers, many=True) filter_backends = [DjangoFilterBackend] filterset_fields = ['in_use'] return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) -
Can't reach local server while Django app is running
When I run python manage.py runserver I get Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). December 29, 2021 - 17:45:15 Django version 4.0, using settings 'webapp.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. but when I try to open it in Chrome I'm only getting ERR_CONNECTION_REFUSED. Only a few hours ago it worked, I changed nothing. -
i create two function for dispaly place and blog in my project(web site) but only one function displaying
views.py def fun(request): obj=place.objects.all( ) return render(request,"index.html",{'results':obj}) def func(request): obj=blog.objects.all( ) return render(request,"index.html",{'blogresults':obj}) urls.py urlpatterns = [ path('', views.fun, name='fun'), path('', views.func, name='func'), ] -
Django startproject fails: No module named zoneinfo
I am creating a new project in Django. My set up is Windows 10 Django 4.0 Python 3.8 On running django-admin startproject myproject, I recieve the following error: ... ModuleNotFoundError: No module named 'zoneinfo' During handling of the above exception, another exception occurred: ... ModuleNotFoundError: No module named 'backports' Any clues on how to resolve this issue? -
Django - How to register route with query parameters?
Im very new to Django, struggling to find the answer Im looking for. Please bear with me. In my app/urls.py file I have router = routers.DefaultRouter() router.register(r'drugs', views.DrugViewSet) In my views.py file I have class DrugViewSet(viewsets.ModelViewSet): queryset = Drug.objects.all().order_by('name') serializer_class = DrugSerializer And my DrugSerializer class looks like class DrugSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Drug fields = ('id', 'name', 'description', 'recommended_dose_mg', 'count', 'create_date', 'update_date') So when I do a GET on /drugs, I correctly get the list of drugs. And when I take a UUID (primary key) on a specific drug and do a GET on /drugs/<primary_key>, it correctly pulls the specific drug. However, I want the GET on /drugs/<primary_key> to display different data. I want to join it with another model that I have and return a new json response. How exactly would I do this? -
my chat app doesn't work after deployement - heroku django
I did a chatting part in my web app with django it works perfectly in local but after I deployed it to heroku , it doesn't work: this is my consumers.py class: from channels.generic.websocket import AsyncWebsocketConsumer from django.contrib.auth.models import User from django.db.models import Q from asgiref.sync import sync_to_async import json from chat.models import Thread, Message from users.serializers import UserSerializer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): friend = None me = self.scope['user'] # logged in user friend_name = self.scope['url_route']['kwargs']['friend'] # get the username of that user, whoom you want to chat friend_instance = await sync_to_async(User.objects.get, thread_sensitive=True)(username=friend_name) # get user object of friend # create a new Thread object if thread of specific chat does not exists, otherwise return the thread thread = None try: thread = await sync_to_async(Thread.objects.get, thread_sensitive=True)((Q(user1=me) & Q(user2=friend_instance)) | (Q(user1=friend_instance) & Q(user2=me))) except: thread = await sync_to_async(Thread.objects.create, thread_sensitive=True)(user1=me, user2=friend_instance) self.room_name = thread.room_name # room name await self.channel_layer.group_add( self.room_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): ''' disconnect the websocket connection. ''' await self.channel_layer.group_discard ( self.room_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] from_user = text_data_json['user'] to_user = text_data_json['friend'] from_user_instanse = await sync_to_async(User.objects.get, thread_sensitive=True)(username=from_user['username']) # get user object of friend to_user_instanse = await sync_to_async(User.objects.get, … -
How to actually prove that the user consented to data processing while he submitted the form?
A user submits a form and opts in to receive a newsletter. What do I need to do to prove later that he actually did opt in? If I store submitted form data in a db table then I am able to manually create and modify entries, so I could just change his False to True and therefore db entries don't prove anything. I have a django website if it makes any difference. -
Django render_to_string Returns NoneType Error
Using Django Pagination I'm trying to do endless pagination using AJAX. I followed the example here: https://www.progerhub.com/tutorial/adding-pagination-with-infinite-scroll-in-django/ My view returns the first page of results just fine, but when I attempt to build the content for the additional pages and return it as JSON using render_to_string I get an error while appending data onto my content variable. error message web_1 | Traceback (most recent call last): ... web_1 | File "/usr/src/django/media/views.py", line 74, in get web_1 | content += render_to_string('media_item.html', {'media': media, }, request=request) ... web_1 | new_obj = func(obj, *arg_vals) web_1 | File "/usr/local/lib/python3.8/site-packages/django/template/defaultfilters.py", line 784, in divisibleby web_1 | return int(value) % int(arg) == 0 web_1 | TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' models.py class Media(Audit): title = models.CharField( max_length=255) description = models.CharField( max_length=500, blank=True, null=True) poster = ProcessedImageField( blank=True, null=True, format='JPEG', options={'quality': 100}, processors=[ResizeToFill(1000, 1500)], upload_to=get_poster_path) class Meta: ordering = ( 'title', 'year') def __str__(self): return self.title views.py class MediaView(LoginRequiredMixin, JsonMixin, View): def get(self, request, *args, **kwargs): context = self.get_context_data() media = models.Media.objects.filter() page = int(request.GET.get('page', 1)) p = paginator.Paginator(media, 24) # number of media per page # try to get media for the given page try: media_page … -
Docker with venv or without?
I am new in Docker and learning it, and my question is that do I have to use venv in Docker or isn't it important? Because I couldn't configure venv in docker, it gives me an error like cannot import Django activate venv..., I read some answers but couldn't get answer, some people say need to use venv others not important. My DOckerfile FROM python:3.8 #set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN python3 -m venv venv #Set work directory WORKDIR /code/ #Install dependencies COPY requirements.txt . RUN . /venv/bin/activate && pip install -r requirements.txt COPY . /code/ If I don't use venv Docker runs fine, but when it comes to install package it gives me warning like WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead:... Can someone explain clearly it? Thanks in advance -
django AttributeError when saving data with DRF
I have a problem when I make a POST. the entry is created (I can see it in django Admin panel) but DRF is throwing me an error AttributeError at /api/v1/reviews/ 'Review' object has no attribute 'review_score' review_score beeing a SerializerMethodField in serializer.py needed for the frontend (GET is working perfectly) model.py class Review(models.Model): company = models.ForeignKey(Company, related_name='company_review', on_delete=models.CASCADE) title = models.CharField(max_length=255) comments = models.TextField() validated = models.BooleanField(default=False) note_quality = models.DecimalField(max_digits=5, decimal_places=2) note_timing = models.DecimalField(max_digits=5, decimal_places=2) note_qualprix = models.DecimalField(max_digits=5, decimal_places=2) note_react = models.DecimalField(max_digits=5, decimal_places=2) note_followup = models.DecimalField(max_digits=5, decimal_places=2) note_clean = models.DecimalField(max_digits=5, decimal_places=2) created_at = models.DateField(auto_now_add=True) created_by = models.ForeignKey(User, related_name='created_review', on_delete=models.CASCADE) def __str__(self): return self.title views.py class ReviewViewSet(viewsets.ModelViewSet): serializer_class = ReviewSerializer queryset = Review.objects.all() def get_queryset(self): company_id = self.request.query_params.get('company_id', None) return self.queryset.filter(company_id=company_id, validated=True).annotate( review_score = Sum(F('note_quality')+F('note_timing')+F('note_qualprix')+F('note_react')+F('note_followup')+F('note_clean'))/6, ) def perform_create(self, serializer): obj = serializer.save(created_by=self.request.user) obj.save() serializer.py class ReviewSerializer(serializers.ModelSerializer): created_by = UserCreateSerializer(read_only=True) review_score = serializers.SerializerMethodField() def get_review_score(self, obj): rounded = round_up(obj.review_score, 0.5) return rounded class Meta: model = Review read_only_fields = ('created_at'), fields = ('id','company','title','comments','validated','note_quality','note_timing','note_qualprix','note_react','note_followup','note_clean','created_at', 'created_by', 'review_score') -
Django: How to add html tag from string to the html template
Details: Client framwork: Django Web server: Python + Flask I have an HTML page which rendered with a data array. Each item in the array contains some fields. And one of the fields is a json object. In order to improve the visibility of the json i've converted the json obj to html table. Currently it's does't work. The results (on the browser) looks like that: PasswordPolicy <table border="1"><tr><th>MinimumPasswordLength</th><td>16</td></tr><tr><th>RequireSymbols</th><td>True</td></tr><tr><th>Re Flask code: @app.route("/PasswordPolicy", methods=["GET"]) @login_required def get_password_policy(): get_table_content = list(db_object.get_password_policy()) search_event = request.args.get('searchquery') at_type = request.args.get('audittype') print("**************") for e in get_table_content: print("Before:") print(e['PasswordPolicy']) e['PasswordPolicy'] = json2html.convert(json = e['PasswordPolicy']) print("After:") print(e['PasswordPolicy']) print("get_table_content:") print(get_table_content[0]) print("**************") return render_template( 'soc2/password_policy.html', get_list=get_table_content ) Html content: <table id="datatable-buttons" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%"> <thead> <tr class="headings"> <th class="column-title">BusinessUnit </th> <th class="column-title">ControllerNumber </th> <th class="column-title">PasswordPolicy </th> </tr> </thead> <tbody> {% for elements in get_list %} <tr class="even pointer"> <td> {{ elements["BusinessUnit"] }} </td> <td> {{ elements["ControllerNumber"] }} </td> <td> {{ elements["PasswordPolicy"] }} </td> </tr> {% endfor %} </tbody> </table> The question is how to tell to the browser to parse the table as html instead of simple string -
Is it safe to delete a Django QuerySet that may be empty?
Is it safe to attempt to delete a QuerySet that might be empty? In other words, if I am not sure if the name "MJ" exists, is there any functional difference between these 2 approaches? Is either preferred? 1) query = m.objects.filter(name="MJ") if query.exists(): query.get().delete() m.objects.filter(name="MJ").delete() -
Django model, ImportError attempted relative import with no known parent package
I'm making a small Django app, and i just want to make some tests over the QuerySet of my model. However, when running code outside the manage.py runserver environment, i get this error : from .models import Article Error: ImportError: attempted relative import with no known parent package As already said, this works perfectly when making views, i can import my Article model and create Articles from the admin dashboard. My app structure looks like this: app/ admin.py apps.py models.py (this contains my Article model) views.py file_where_ihave_my_error.py -
Django NEWBIE - TemplateDoesNotExist
(My project directory is called test and the app in question is called posts) Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: /path-to-app-dir/virtual/test/posts/templates/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /path-to-app-dir/virtual/platform/lib/python3.10/site-packages/django/contrib/admin/templates/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /path-to-app-dir/virtual/platform/lib/python3.10/site-packages/django/contrib/auth/templates/index.html (Source does not exist) Views.py from django.shortcuts import render from django.http import HttpResponse def index(request): return render(request,'templates/index.html') Urls.py from django.urls import path from . import views urlpatterns=[ path('', views.index) ] I have mentioned the app in Settings.py so that probably shouldn't be an issue. What am I doing wrong ? -
Интеграция данных парсера с Django [closed]
Я хочу сделать сайт, на котором можно будет посмотреть информацию о разных вузах. У меня готовы парсеры, но я не понимаю, как можно правильно интегрировать парсеры в Django приложение... Когда я искал информацию по этому поводу, одним рекомендовали использовать django-admin команды, другим использовать парсеры. Я не понимаю, что использовать лучше, у чего какие плюсы и что стоит в итоге выбрать? На данный момент у меня парсеры заливают информацию в стороннюю бд и через класс вытягивается в html форму. Не думаю, что это правильное решение... -
Why am I getting a 404 Error when I've clearly defined my urlpatterns?
My project is storefront and when I run the server I get the error message "Page not found". I have my urls.py file in the storefront folder for you to look at. I've looked around on the internet and have had no luck yet. urlpatterns = [ path('admin/', admin.site.urls), path('playground/', include('playground.urls')) ] I thik the problem is in my urls.py specifically with "include" but not sure. -
Django Haystack select which fields to search
Suppose I have a Person model looking like this: class Person(models.Model): title = models.CharField(max_length=300, blank=True, null=True) first_name = models.CharField(max_length=300, blank=True, null=True) last_name = models.CharField(max_length=300, blank=False, null=False) And a Haystack search index like this: class NoteIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) title = indexes.CharField(model_attr='title') first_name = indexes.CharField(model_attr='first_name') last_name = indexes.CharField(model_attr='last_name') Say the template includes all three fields(firstname, lastname and title). If users should be able to choose in which fields to search for, do I need to build seperate indices for all possible permutations? Or can I narrow down the search to one or two of the three fields? If so how? I know that I am able to filter SearchQuerySets using .filter(). SearchQuerySet().filter(first_name='foo') But this filters the set for exact values. Even __icontains is limited to one field filtering. -
How to make django not render html?
I have model: class NewsItem(models.Model): meta_title = models.CharField(_('Meta title'), max_length=255, blank=True, null=True, help_text=mark_safe('Tag <title>')) But on the page I have: <div class="form-row field-meta_title"> <div> <label for="id_meta_title">Meta title:</label> <input type="text" name="meta_title" class="vTextField" maxlength="255" id="id_meta_title"> <div class="help">Tag <title></div> </div> </div> How to tell django not render html? -
Python Flask - Errors after creating a new project
After creating a new project and trying to run it, I get something like this: * Environment: development * Debug mode: off Traceback (most recent call last): File "C:\Users\Sebastian\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 192, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\Sebastian\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\flask\__main__.py", line 3, in <module> main() File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\flask\cli.py", line 994, in main cli.main(args=sys.argv[1:]) File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\flask\cli.py", line 600, in main return super().main(*args, **kwargs) File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\click\core.py", line 1053, in main rv = self.invoke(ctx) File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\click\core.py", line 1659, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\click\core.py", line 1395, in invoke return ctx.invoke(self.callback, **ctx.params) File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\click\core.py", line 754, in invoke return __callback(*args, **kwargs) File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\click\decorators.py", line 84, in new_func return ctx.invoke(f, obj, *args, **kwargs) File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\click\core.py", line 754, in invoke return __callback(*args, **kwargs) File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\flask\cli.py", line 853, in run_command run_simple( File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\werkzeug\serving.py", line 1010, in run_simple inner() File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\werkzeug\serving.py", line 950, in inner srv = make_server( File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\werkzeug\serving.py", line 782, in make_server return ThreadedWSGIServer( File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\werkzeug\serving.py", line 688, in __init__ super().__init__(server_address, handler) # type: ignore File "C:\Users\Sebastian\AppData\Local\Programs\Python\Python38-32\lib\socketserver.py", line 452, in __init__ self.server_bind() File "C:\Users\Sebastian\AppData\Local\Programs\Python\Python38-32\lib\http\server.py", line 139, in server_bind self.server_name = socket.getfqdn(host) File "C:\Users\Sebastian\AppData\Local\Programs\Python\Python38-32\lib\socket.py", line 756, in getfqdn hostname, aliases, ipaddrs = gethostbyaddr(name) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe6 in … -
Getting error while using migrate after inspectdb using sqlite
I need to make an API from an existing sqlite db. I used inspectdb for creating models from the database. Do I need to manually add the primary keys(id) for all tables after inspect in my models.py? After that what should I do, migrate? Makemigrations? I am getting error related to one of the tables in the databases after doing migrate,(issue with one table referencing other). Is there an issue with the db? Here is my settings.py """ Django settings for IMS project. Generated by 'django-admin startproject' using Django 4.0. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-u@yr4&95+m=v*6o53in2*82xn@292n(6-#ixj38-^8l8e3(4$h' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "Api.apps.ApiConfig", "rest_framework", ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'IMS.urls' TEMPLATES … -
Truncated or oversized response headers received from daemon process error with PiCamera library
I am hosting a simple Django website using Apache2 and WSGI. The website works fine but when I attempt to instantiate a PiCamera() object I get this error. All I am trying to do is initiate a photo capture and update the image on the website every time the website is refreshed. I feel like it should not be this difficult. I have searched all over and cannot find a solution. I have attempted to add WSGIApplicationGroup %{GLOBAL} to my sites-available/000-default.conf as well as my apache2.conf. I have also attempted to increase the head buffer size and neither solution work. Any help would be appreciated. Views.py from django.shortcuts import render from django.http import HttpResponse from .models import RelayList from .forms import RelayControl from .gpio import Update_Relays from django.contrib.auth.decorators import login_required from picamera import PiCamera from time import sleep def Snapshot(): camera = PiCamera() #<---THIS IS WHAT CAUSES THE TRUNCATED ERROR # camera.start_preview() # sleep(5) # camera.capture('/home/calabi/relay_site/power_relay/media/snapshot.jpg') # camera.stop_preview() # Create your views here. @login_required def index(response): curList = RelayList.objects.get(id=1) #retrieves the database object and places it into a variable Snapshot() #takes a photo and saves it to images directory # camera = PiCamera() # camera.start_preview() # sleep(5) # camera.capture('/home/calabi/relay_site/power_relay/media/snapshot.jpg') # … -
AttributeError: module 'PrivateSchools.views' has no attribute 'HomePage'
Am getting the above error when try to run the server. Below is the full error. AttributeError: module 'PrivateSchools.views' has no attribute 'HomePage' File"C:\Users\admin\Desktop\InstitutionFinderWebsite\ InstitutionFin derWebsite\urls.py", line 26, in <module>path('HomePage/', views.HomePage), AttributeError: module 'PrivateSchools.views' has no attribute 'HomePage' I had imported all the views from the three apps as below from django.conf.urls import include from django.contrib import admin from django.urls.conf import path from HomePage import views from PublicSchools import views from PrivateSchools import views On the urls.py have tried the 2 methods below but the are not all working. Method one here i used views. to map the urls. urlpatterns = [ path('admin/', admin.site.urls), path('HomePage/', views.HomePage), path('PublicSchools/', views.PublicSchools), path('PrivateSchools/', views.PrivateSchools), ] This is Method two in trying to solve it by trying to give the names. urlpatterns = [ path('admin/', admin.site.urls), path('HomePage/', views.HomePage, name='PrivateSchools'), path('PublicSchools/', views.PublicSchools, name='PublicSchools'), path('PrivateSchools/', views.PrivateSchools, name='PrivateSchools'), ] Kindly help out. Am stuck. -
AttributeError: 'Post' object has no attribute 'post_image'
I am using DRF and Django(4.0) to make posts in a Instagram Clone. The models of the following are available below. I have successfully implemented post request, but am having problems implementing get request. I have tried to nest two serializer inside the PostViewSerializer to serialize the data. However I am getting the following error when I do a get request. Got AttributeError when attempting to get a value for field 'post_image' on serializer 'PostViewSerializer'. The serializer field might be named incorrectly and not match any attribute or key on the `Post` instance. Original exception text was: 'Post' object has no attribute 'post_image'. Now, I should tell you that there is not requirement that the post should contain atleast one image or video it could contain entirely either videos or posts. So, could that be the cause of the above error. If so, how can I solve it? #models.py class Post(Authorable, Model): created_at = models.DateTimeField(default=timezone.now) caption = TextField(max_length=350) class Images(Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) images = models.FileField(upload_to="images/") class Videos(Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) videos = models.FileField(upload_to="videos/") #behaviours.py class Authorable(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: abstract = True def get_user(self): return self.user.id #serializers.py class ImageViewSerializer(serializers.ModelSerializer): class Meta: model = Images … -
Understanding Model.from_db() in Django
I was reading Django Official Doc for Model, it reads: classmethod Model.from_db(db, field_names, values)¶ The from_db() method can be used to customize model instance creation when loading from the database. The db argument contains the database alias for the database the model is loaded from, field_names contains the names of all loaded fields, and values contains the loaded values for each field in field_names. The field_names are in the same order as the values. If all of the model’s fields are present, then values are guaranteed to be in the order __init__() expects them. That is, the instance can be created by cls(*values). If any fields are deferred, they won’t appear in field_names. In that case, assign a value of django.db.models.DEFERRED to each of the missing fields. I am completely lost when reading above. 1st perception: "when loading from the database": for me, loading means reading / retrieving data from database, which means the model instance already exists or is created and stored in DB. 2nd perception: "be used to customize model instance creation", as well as the 2nd paragraph all makes me feel that this from_db() is for model instance creation, which conflicts with my 1st perception. Q: Can … -
How can I return the refresh token using python-social-auth and django-graphql-auth?
How can I return the refresh token when using social auth? I tried this solution here I don't know how to make this compatible with graphql. Here is my attempt: import graphql_social_auth from graphql_jwt.shortcuts import get_token class SocialAuth(graphql_social_auth.SocialAuthJWT): refresh_token = graphene.String() token = graphene.String() @classmethod def resolve(cls, root, info, social, **kwargs): return cls( user=social.user, token=get_token(social.user), refresh_token=social.extra_data['refresh_token'] ) The user and token fields are alright when I comment out the refresh token. I just don't know where to get the refresh token, it seems to be not in the extra_data. I am already dealing with this problem for hours and all the search results are no help. Please, any guidance is really appreciated.