Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Images slider with Django, Bootstrap, Javascript doesn't work properly
I am trying to use the static slider(javascript snippet) for dynamic data. From ListView I am getting to the image. I am sure, the loop in the template and javascript is wrongly built. Any suggestions? models.py class Gallery(models.Model): name = models.CharField(max_length=250) new_image = models.ImageField(upload_to='gallery_folder') day_publish = models.DateField() def save(self, *args, **kwargs): super().save(self, *args, **kwargs) img = Image.open(self.new_image.path) if img.height > 940 or img.width > 788: output_size = (820,720) img.thumbnail(output_size) img.save(self.new_image.path) def get_absolute_url(self): return reverse('detail-slug', kwargs={'pk': self.pk}) def __str__(self): return self.name views.py def slide_show_view(request, *args, **kwargs): all_images = Gallery.objects.all() choosen_image = Gallery.objects.get(**kwargs) context = { 'all_images': all_images, 'choosen_image': choosen_image } return render(request, "gallery/gallery_slide.html", context) urls.py urlpatterns = [ path('slug/<int:pk>/', views.slide_show_view, name="detail-slug"), ] I try with if statement for span(i don't know is correct or not) still not working. gallery_slide.html <div class="container"> <div class="carouselContainer"> <div class="carouselMainImage"> <img src="{{ choosen_image.new_image.url }}"> </div> {% for image in all_images %} <div class="carouselImgs"> <img src="{{ image.new_image.url }}"> </div> {% endfor %} <span class="prev" id="prev"> < </span> <span class="next" id="next"> > </span> </div> </div> <script src="{% static 'js/slideshow.js' %}"></script> slideshow.js var currentSlide = document.getElementsByClassName('carouselMainImage'); function showSlide(slideIndex) { const slides = document.getElementsByClassName('carouselImgs'); console.log(slides); if (slideIndex > slides.length) { currentSlide = 1 } if (slideIndex < 1) { currentSlide … -
step to save image file to server using django api
I am new in python and django, right now I would like to upload an image from postman (content type: form-data) and then save it in server. So far I have doing this @csrf_exempt def detector(request): data = {"success": False} if request.method == "POST": print("oke0") # check to see if an image was uploaded if request.FILES.get("image", None) is not None: ...# here I would like to save the image else: return JsonResponse(data) return JsonResponse(data) so the flow is: upload image from postman and then directory 'media' will be created and the image will be stored there so far I have been following this https://www.geeksforgeeks.org/python-uploading-images-in-django/ but I don't know how to try it in postman, anyone knows step by step to save image file to server in django? -
Error code H10 and H13 deploy django app to Heroku
this is my first time deploying a website and im new to Python, so i dont know how to fix this. I follow CoreyMS tutorial on YouTube, but I am stuck. I keep getting these H10, H13 and sometimes H14 errors. Im on a windows and im not sure if i got it pushed correctely, since Coreys commandline reads master and my commandline stays the same throughout. Note: I have already pip install gunicorn Here is my commandline: (djangoenv) C:\Users\aston\OneDrive\Skrivebord\mydjangoapp\django_project>heroku logs 2021-03-18T07:54:27.389903+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2021-03-18T07:54:27.389903+00:00 app[web.1]: django.setup(set_prefix=False) 2021-03-18T07:54:27.389904+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 19, in setup 2021-03-18T07:54:27.389904+00:00 app[web.1]: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2021-03-18T07:54:27.389904+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 57, in __getattr__ 2021-03-18T07:54:27.389905+00:00 app[web.1]: self._setup(name) 2021-03-18T07:54:27.389905+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 44, in _setup 2021-03-18T07:54:27.389905+00:00 app[web.1]: self._wrapped = Settings(settings_module) 2021-03-18T07:54:27.389906+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 107, in __init__ 2021-03-18T07:54:27.389906+00:00 app[web.1]: mod = importlib.import_module(self.SETTINGS_MODULE) 2021-03-18T07:54:27.389906+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module 2021-03-18T07:54:27.389907+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-03-18T07:54:27.389907+00:00 app[web.1]: File "/app/django_project/settings.py", line 123, in <module> 2021-03-18T07:54:27.389908+00:00 app[web.1]: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') 2021-03-18T07:54:27.393425+00:00 app[web.1]: NameError: name 'os' is not defined 2021-03-18T07:54:27.394367+00:00 app[web.1]: [2021-03-18 07:54:27 +0000] [10] [INFO] Worker exiting (pid: 10) 2021-03-18T07:54:27.399214+00:00 app[web.1]: [2021-03-18 07:54:27 +0000] [9] [ERROR] Exception in worker process 2021-03-18T07:54:27.399216+00:00 … -
django.db.utils.ProgrammingError: relation " - " does not exist
(New to Django) - I am looking to create two model with a foreign key. The first model is called Portfolio, and each Portfolio has many member through the second model Portfoliomember. It currently looks like this: class Portfolio(models.Model): portfolio_name = models.CharField(max_length=30, blank=True, null=True) def __str__(self): return self.portfolio_name class Meta: db_table = "portfolio" class PortfolioMember(models.Model): portfolio = models.ForeignKey(Portfolio, related_name = "portfoliomember", on_delete=models.CASCADE) quality = models.FloatField(blank=True, null=True) def __str__(self): return self.portfolio class Meta: db_table = "portfoliomember" Later i aim at using formset in a form. but for now, when i try to create the migration, i get the following : django.db.utils.ProgrammingError: relation "portfoliomember" does not exist Is there an obvious reason why this would not work ? -
Nginx error while using django-channels, nginx and daphne for websocket connection
#This is my nginx config location /order_history/ { proxy_http_version 1.1; proxy_pass http://0.0.0.0:8001; proxy_buffer_size 64k; proxy_buffers 16 32k; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } nginx error: upstream prematurely closed connection while reading response header from upstream -
Get logged user ip by models.py and Generic Cass Views in Django
i'd get the ip address all the time user do login. Please Help. my models.py user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ip_address = models.GenericIPAddressField() def __str__(self): return self.ip_address -
Error while building a simple project. Writes could not find the specified file
./project /site_ts /web Dockerfile requirements.txt docker-compose.yml my docker-compose.yml: version: '3' services: web: build: ./web command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/site_ts ports: - '8000:8000' my Dockerfile: FROM python:3.8 ENV PYTHONUNBUFFERED 1 RUN mkdir /site_ts WORKDIR /site_ts COPY requirements.txt /site_ts/ RUN pip install --upgrade pip && pip install -r requirements.txt ADD . /site_ts/ i write docker-compose up and take this Error: During handling of the above exception, another exception occurred: Traceback (most recent call last): File "docker-compose", line 3, in <module> File "compose\cli\main.py", line 67, in main File "compose\cli\main.py", line 123, in perform_command File "compose\cli\command.py", line 69, in project_from_options File "compose\cli\command.py", line 132, in get_project File "compose\cli\docker_client.py", line 43, in get_client File "compose\cli\docker_client.py", line 170, in docker_client File "site-packages\docker\api\client.py", line 188, in __init__ File "site-packages\docker\api\client.py", line 213, in _retrieve_server_version docker.errors.DockerException: Error while fetching server API version: (2, 'CreateFile', 'The specified file cannot be found.') [9356] Failed to execute script docker-compose -
Getting a particular value from QuerySet in django
how can I get to print "Mathematics" from this QuerySet? <QuerySet [<Schedule: Thursday - Class 1/2/3 Section A - Mathematics>]> -
How to solve this error in Django rest framework?
#My Model from django.db import models class Tutorial(models.Model): title = models.CharField(max_length=100, blank=False, default=''), description = models.CharField(max_length=250, blank=False, default=''), published = models.BooleanField(default=False) #my 0001.py migration file from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Tutorial', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('published', models.BooleanField(default=False)), ], ), ] Why is the model neglecting the title, description fields even I mentioned them clearly??? I deleted the init0001.py file re run the migrations again but not resolved -
drf- discord like role permissions checking
relevant discussion is here. So I am building an api with architecture inspired by discord. I have objects called Boxes and these boxes have their own set of Roles. The role object looks like this. class Role(CoreModel): class Meta: ordering = ('position', 'box') permission_flags = ( 'ADD_STARS', 'DOWNLOAD_FILES', 'SEND_UPLOADS', 'MANAGE_UPLOADS', 'MANAGE_ROLES', 'MANAGE_BOX', 'MANAGE_INVITES', 'KICK_MEMBERS', 'BAN_MEMBERS' ) default_flags = ( 'ADD_STARS', 'DOWNLOAD_FILES', 'SEND_UPLOADS', ) color = ColorField( verbose_name=_('color'), help_text=_("role's hex color code"), default='#969696' ) hoist = models.BooleanField( verbose_name=_('hoist'), help_text=_("whether the role can be pinned"), default=False ) is_default = models.BooleanField( verbose_name=_('default'), help_text=_("whether the role is default"), default=False ) position = PositionField( verbose_name=_('position'), help_text=_("position for the role"), collection=('box', 'is_default') ) box = models.ForeignKey( to='uploads.Box', verbose_name=_('box'), on_delete=models.CASCADE ) name = models.CharField( verbose_name=_('name'), help_text=_("role name"), default='new role', max_length=100, validators=[ MinLengthValidator(2) ] ) permissions = BitField( verbose_name=_('permissions'), help_text=_("permission bit set"), flags=permission_flags, default=default_flags ) REQUIRED_FIELDS = (name, box) I am using the bitfield extension provided by disqus here. Roles have a set of predefined permissions which can be allowed or denied for a specific role, like MANAGE_ROLES # allows to manage box roles MANAGE_BOX # allows to manage and edit the box Now, users can be a part of the box, through a model called member, and … -
how to use inlineformset with js to add extra fields
i want to use inlineformset factory for my project ! i have write my own js to add more fields , but it only save the last form in child form ! i dont want to use jquery.formset.js this is my models.py class Main(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) company = models.ForeignKey(Companies,on_delete=models.CASCADE) items = models.ManyToManyField(Item,through='Child') invoice_number = models.IntegerField() class Child(models.Model): main = models.ForeignKey(Main,on_delete=models.CASCADE) item = models.ForeignKey(Item,on_delete=models.CASCADE) quantity = models.IntegerField() and this is my views.py , i have used class based view class CreateMainInlineFormset(LoginRequiredMixin,SuccessMessageMixin,CreateView): model = Main form_class = MainForm template_name = 'main/create.html' def get_context_data(self, *args,**kwargs): data = super().get_context_data(*args,**kwargs) if self.request.POST: data['items'] = ChildInlineFormSet(self.request.POST) data['items'].full_clean() else: data['items'] = ChildInlineFormSet() return data def form_valid(self, form): context = self.get_context_data() items = context['items'] with transaction.atomic(): self.object = form.save(commit=False) form.instance.admin = self.request.user if items.is_valid() and form.is_valid() and items.cleaned_data!={}: items.instance = self.object form.save(commit=True) items.save() else: return render(self.request,self.template_name,context) return super().form_valid(form) def get_success_url(self): return reverse_lazy('maininfo:list-item') and this is my template html + js script ,i think the problem is here , i dont know how increase child forms in a right way ! $("#addRow").click(function () { var html = $("#relInputs").clone(); $('#relatiedInput').append(html); }); $(document).on('click', '#removeRow', function () { if ($("#relatiedInput> #relInputs").length != 1) $(this).closest('#relInputs').remove(); }); <div class="mt-1 text-right mx-auto" style="direction: rtl;"> … -
Django Channels - Mark user as online and offline
How can we use django channels to mark user as online and offline? Means using websocket is it possible to mark user as offline or online? If not, what all are the other possible ways to mark user as online and offline, like how it is done in facebook, instagram and all? In frontend, I want to show green ball in case user is online and red ball in case user is offline. -
Django to modify value in body and return it
class LocationRetrieveSerializer(serializers.ModelSerializer): class Meta: model = UserAttributes fields = '__all__' def create(self, validated_data): logger.info(self.context["request"].user.aerosimple_user) if UserAttributes.objects.filter(user_id=self.context["request"].data['user']).exists(): raise serializers.ValidationError("User Already exists.") user_attributes = UserAttributes.objects.create(**validated_data) return user_attributes i want to change the value in the body and should return it with the changed value in the body -
What is the difference between the types of CORS settings?
I searched to solve the cross domain that occurs when deploying django to the google cloud app engine and found three solutions. The cross domain problem has not been solved yet, but I have a question. GCP storage CORS setting https://cloud.google.com/storage/docs/cross-origin?hl=en GCP app.yaml setting https://cloud.google.com/appengine/docs/standard/python3/config/appref?hl=en django-cors-headers https://pypi.org/project/django-cors-headers/ Are there any differences between the three? -
Chartjs not parsing JsonResponse (Django and Chartjs)
I'm trying to get a pie chart (Chart.js) rendered from my django model; however, instead I'm getting my Json data rendered to my localhost (see picture). here's my code for reference (also, the JsonReponse is a class because I'm using Django 1.6.11 and JsonReponse was only formally added to django >= 1.7) views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, Http404 from django.contrib import messages from django.utils import simplejson from django.middleware.csrf import get_token from django.db.models import Count from .models import Member, Driver, Order, Distance import json class JsonResponse(HttpResponse): # Code for JSONResponse - not in Django 1.6.11 def __init__(self, content, mimetype='application/json', status=None, content_type=None): super(JsonResponse, self).__init__( content=simplejson.dumps(content), mimetype=mimetype, status=status, content_type=content_type, ) def homepage(request): # pie chart for payment type queryset = Order.objects.order_by('payment').values('payment').annotate(payment_type=Count('payment')) data = list(queryset.values_list('payment_type', flat=True)) labels = list(queryset.values_list('payment', flat=True)) return JsonResponse({ 'labels' : labels, 'data' : data, }) urls.py from django.conf.urls import patterns, include, url from django.contrib import admin from mysite import views urlpatterns = patterns('', url(r'^$', 'mysite.views.homepage', name='payment-chart'), ) base.html <div class="payment_chart"> <canvas id="payment_chart" data-url="{% url 'payment-chart' %}"> </canvas> </div> <script> $(function () { var $paymentChart = $("#payment-chart"); $.ajax({ url: $paymentChart.data("url"), success: function(data) { var ctx = $paymentChart.getContext("2d"); new Chart(ctx, { type: 'pie', data: { labels: labels, … -
How to Router Redirect After Login in Django
from django.urls import reverse from django.http import HttpResponseRedirect from django.shortcuts import redirect def auth_middleware(get_response): def middleware(request): #print(request.session.get('customer')) returnUrl = request.META.get('PATH_INFO') #print(request.build_absolute_uri()) if not request.session.get('customer'): return HttpResponseRedirect(reverse(f'store:login?return_url={returnUrl}')) print('middleware') response = get_response(request) return response return middleware -
Django Query results null queryset
In my models I have an Allotment model: class AllotmentFlow(models.Model): flow = models.ForeignKey(Flow, on_delete=models.CASCADE) kit = models.ForeignKey(Kit, on_delete=models.CASCADE) asked_quantity = models.IntegerField(default=0) alloted_quantity = models.IntegerField(default=0) class Allotment(models.Model): transaction_no = models.IntegerField(default=0) dispatch_date = models.DateTimeField(default=datetime.now) send_from_warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE) sales_order = models.ForeignKey(MaterialRequest, on_delete=models.CASCADE) flows = models.ManyToManyField(AllotmentFlow) I am querying this model like following: for k in d_o.demand_flows.all(): print("k", k.kit.kit_name) items = Allotment.objects.filter(dispatch_date__year = m.year, dispatch_date__month = m.month, flows__kit=k.kit.pk).aggregate(Sum('flows__alloted_quantity')) print("items", items) While running this query I can see in the terminal that k.kit.pk, m.year and m.month are being passed correctly and it still return the empty queryset m 1 y 2020 k KIT1182D items <QuerySet []> Whereas, I can see from other module that the ORM contains the data: Is there a problem with the query? -
Refused to execute script from 'bundle.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled
I have an application with CRA with frontend and django backend. I use react-app-rewired to override webpack configuration on frontend so that to save output from webpack-dev-server for django to use. But I hit the issue as shown in below screenshot. Below is my override-config.js which used to override out-of-box CRA webpack config Weird thing is that there is no such issue for frontend product build(run yarn build and then open localhost:8000 in browser and I can get frontend correctly). Above Refuse to execute ... issue only happen when I run yarn start for development mode. Here is my package.json And django frontend.html Relative part in django settings.py Thanks in advance for any help! -
Django form instance value not displayed in Pop-up form
I'm working on task where I want to update data with bootstrap Modal(Pop-Up) form. I can able to update the data but I couldn't see the previous data(instance not displayed in the pop-up form). Example. If I have data with the name apple and I want to update it to banana that apple value instance was not displayed in the pop-up form. models.py class Todo(models.Model): date_created = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) title = models.CharField(max_length=200) user_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.title class Task(models.Model): heading = models.CharField(max_length=100) todo = models.ForeignKey(Todo, on_delete=models.CASCADE, related_name='tasks') date_created = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.heading views.py from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse, Http404, HttpResponseNotFound, JsonResponse, HttpResponseRedirect from .models import Todo, Task from .forms import * from django.utils import timezone from django.contrib.auth.forms import UserCreationForm from django.views.decorators.csrf import csrf_protect from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.views.generic import View from django.contrib.auth.models import User from django.core.paginator import Paginator from django.views.decorators.http import require_POST def register(request): form = userRegisterForm() if request.method == 'POST': form = userRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password2') return redirect('login') else: form = userRegisterForm() context = {'form': form} return … -
How to provide a console connection to a kubernetes pod on a django app
I have a Kubernetes cluster with pods in it. I want to provide a console connection to a pod on a HTML page in a Django app. -
Cookie only set on login page
I'm trying to set a cookie application wide but it only gets set on the path /login. Here's my code axios .post("api/auth-token"/, {username, password}) .then(response => { const { token } = response.data; document.cookie = "authtoken=" + token; // Registering cookie window.location.replace("/app/dashboard"); }); But when I visit other pages, this cookie is not present. When I check the Applications section in the developer tools, I noticed the cookie has a path of /login so I guess this is why other pages can't see it. But when I try to add a path using this document.cookie = `authtoken=${token}; path=/;max-age=120`; My token still gets set to /login only. The max-age is just for development purposes. I've even tried to use a library like https://github.com/js-cookie/js-cookie and set my cookie using Cookies.set('authtoken', token, { path: '/' }); but my cookie still only gets set for that page. What could the be the cause of my cookie getting registered only on the login page. Not sure if this is useful information but my backend is in Django and my pages are django templates. But I get data from the server using REST. -
How to direct a page from a form Django
I am working on a dictionary app, i am allowing a user to enter a word through a form. When the word is entered in the form and a submit button is pressed i want the form to be maintained on the same page however when the user enter the word and presses submit the form disappears leaving only the submit button and the search results Here is the dictionary/form code class NameForm(forms.Form): your_name = forms.CharField(max_length=100, label=False) the dictionary/view code def index(request): if request.method == 'POST': form = NameForm(request.POST) if form.is_valid(): word = form.cleaned_data['your_name'] print(word) if Dictionary.get_verb(word): verb = Dictionary.get_verb(word) else: verb = False print(verb) if Dictionary.get_noun(word): noun = Dictionary.get_noun(word) else: noun = False print(noun) synonyms = Dictionary.get_synonyms(word) print(synonyms) form = NameForm() context = { 'verb':verb, 'noun':noun, 'synonyms':synonyms, } return render(request,'index.html' ,context) else: form = NameForm() context = { 'form': form, } return render(request, 'index.html', context) and the index.html form action="" method="post"> {% csrf_token %} {{form}} <br> <input type="submit" value="Submit"> </form> <hr> {% if noun %} <h2>Noun</h2> {% for noun_word in noun %} <p>{{noun_word}}</p> {% endfor %} {% else %} <!-- print nothing--> {% endif %} <br> <hr> {% if verb %} <h2>Verb</h2> {% for verb_info in verb %} <p>{{verb_info}}</p> … -
Django dropdown select get data from database
I have a table : Cars with field carID,CarName PaymentType field paymentTypeID, PaymentTypeName Carprice field priceID,CarID,paymentTypeID, amountPrice I already show Cars and paymentType to dropdown select. how i can show Carprice after user selectCar and selectPayment? best regards, Capah Maga -
Django service worker deletes cache when offline
thanks for your time. I'm trying to get a a django PWA to work offline. I'm able to install the app, save the cache but when i try to load it offline, the cache that had created desapear. note: i'm passing the sw.js and manifest.json files trough urls with TemplateView class. sw.js: { const cacheName = 'cache-v1'; const resourcesToPrecache = [ "{% url 'sw.js' %}", "{% url 'home' %}", "{% url 'install_sw' %}" ]; self.addEventListener('install', function (event) { console.log('sw install event!'); event.waitUntil( caches.open(cacheName) .then(function (cache) { console.log('cache added') return cache.addAll(resourcesToPrecache); } ) ); }); self.addEventListener('fetch', function (event) { console.log(event.request.url); event.respondWith( caches.match(event.request).then(function (response) { return response || fetch(event.request); }) ); }); }; console.log('ok') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('config/', include('config.urls')), path('products/', include('products.urls')), path('cart/', include('cart.urls')), path('accounts/', include('allauth.urls')), path('home/', home_view, name='home'), path('sw.js/', (TemplateView.as_view(template_name="admin/sw.js", content_type='application/javascript', )), name='sw.js'), path('manifest.json/', (TemplateView.as_view(template_name="admin/manifest.json", content_type='application/json', )), name='manifestjson'), path('install_sw/', (TemplateView.as_view(template_name="admin/install_sw.html", content_type='text/html', )), name='install_sw'), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) manifest.json { "short_name": "Mega", "name": "MegaMagazine", "scope": "/", "icons": [ { "src": "/static/m1.png", "type": "image/png", "sizes": "144x144" } ], "start_url": "/", "background_color": "#3367D6", "display": "standalone", "theme_color": "#3367D6", "prefer_related_applications": false } install_sw.html <!doctype html> <head> <link rel="manifest" href="{% url 'manifestjson' %}"> </head> <title>installing service worker</title> <body> <img src="/static/m1.png" … -
Django Rest Framework and Channels, You cannot call this from an async context
What i am trying to do is to nest a DRF model serializer into another model serialiser's field like so class username_serial(ModelSerializer): class Meta: model = User fields = ['username','email'] class game_serial(ModelSerializer): user_01 = username_serial() class Meta: model = game fields = ['id','user_01','user_02','is_private','is_accepted'] Error : Exception inside application: You cannot call this from an async context - use a thread or sync_to_async. Traceback (most recent call last): File "C:\Users\baza\Desktop\production\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 173, in get rel_obj = self.field.get_cached_value(instance) File "C:\Users\baza\Desktop\production\venv\lib\site-packages\django\db\models\fields\mixins.py", line 15, in get_cached_value return instance._state.fields_cache[cache_name] KeyError: 'user_01' This works normally without Django Chennels because channels is async and i can't use sync code with, works fine by using: os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" In the settings file but it's not a safe approach when it comes to production. i tried using channel's database_sync_to_async as a decorator and as well as a function with a SerializerMethodField like so: class game_serial(ModelSerializer): user_01 = SerializerMethodField(read_only=True) @database_sync_to_async def get_user_01(self, obj): username = obj.user_01.username return str(username) class Meta: model = game fields = ['id','user_01','user_02','is_private','is_accepted'] but i get back: [OrderedDict([('id', 23), ('user_01', <coroutine object SyncToAsync.__call__ at 0x0000000005DF6678>), ('user_02', None), ('is_private', False), ('is_accepted', False)]), OrderedDict([('id', 24), ('user_01', <coroutine object SyncToAsync.__call__ at 0 x0000000005DF6D58>), ('user_02', None), ('is_private', False), ('is_accepted', False)])] with …