Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can save file with names in utf-8
I need to save file with utf-8 names.but when I do it django error: UnicodeEncodeError at /uploaded/document/ 'فیلتر.png' 'ascii' codec can't encode characters in position 55-59: ordinal not in range(128) although, my filefield like it: # -*- coding: utf-8 -*- def get_path(instance, filename): return u' '.join((u'document', filename)).encode('utf-8').strip() class Document(models.Model): file_path = models.FileField(verbose_name='File', upload_to=get_path, storage=FileSystemStorage(base_url=settings.LOCAL_MEDIA_URL)) how can I fix it? I use tastypie api to upload file. -
How to mock view decorator in Django
Consider that I have a simple APIView as below, from rest_framework.views import APIView from rest_framework.response import Response def my_custom_decorator(func): def wrap(view, request): if request.method.lower(): raise ValueError("Just for testing") return func(view, request) return wrap class SomeAPIView(APIView): @my_custom_decorator def post(self, request): return Response({"message": "Success"}) Note that the view function post(...) is wrapped by the decorator @my_custom_decorator. Noe, I want to write the test for this API and I tried like this from rest_framework.test import APITestCase from django.urls import reverse from unittest.mock import patch class TestSomeAPIView(APITestCase): @patch("sample.views.my_custom_decorator") def test_decorator(self, mock_my_custom_decorator): url = reverse("some-api-view") response = self.client.post(url) self.assertEqual(response.status_code, 200) self.assertEqual(response.json(), {"message": "Success"}) This didn't mock the @my_custom_decorator properly and thus gave me an exception. Question: How can I mock the @my_custom_decorator to retrieve a successful response? Notes I have seen this SO post, Can I patch a Python decorator before it wraps a function?, I feel that post lacks some examples, -
Class Based View: CreateView success_url is not working
I have created a a class based view that inherits CreateView which dynamically generates a form based on the url parameters. I have other Views that also have the same functions but they do redirect to the ListView but this CBV gives 404 error with request url : http://127.0.0.1:8000/create/StudentPerformance/tblstandard/ (StudentPerformance is app_label, tblstandard is model_label) which is the url for below CreateView. And I am getting an Attribute Error: Generic detail view ModelObjectCreateView must be called with either an object pk or a slug in the URLconf. CreateView Only showing create view but ModelObjectUpadteView, ModelObjectDeleteView that work are of the same structure and they work. class ModelObjectCreateView(SuccessMessageMixin, PermissionRequiredMixin, LoginRequiredMixin, CreateView): context_object_name = 'object' app_label = "" model_label = "" fields_label = "" template_label = "" success_label = "" success_message = f"%(object)s successfully created!!!" def dispatch(self, request, *args, **kwargs): self.app_label = kwargs.get('app_label', None) self.model_label = kwargs.get('model_label', None) self.model = apps.get_model(self.app_label, self.model_label.capitalize()) self.get_modelobject_fields_label() self.template_label = kwargs.get('template_label', None) self.template_name = self.get_template_name_label() # ---------------------------------- # success_url is assigned # ---------------------------------- self.success_url = self.get_success_url_label() self.permission_required = self.get_permissions_required_label() try: ret = super(ModelObjectCreateView, self).dispatch(request, *args, **kwargs) except AttributeError as e: print(e) raise Http404 return ret def form_valid(self, form): form.instance.created_by = self.request.user return super().form_valid(form) def get_template_name_label(self): if self.template_label … -
Django Annotate - Concat from last created ManyToMany Object Fields
class User(models.Model): name=CharField() class Address(models.Model): user= Foreignkey(user, related_name="Addresses") buildingname=CharField() subbuildingname=CharField() town=CharField() ... I have a models like top and want to extract data as list below. { [ ['USERNAME1', 'A XYZBUILDING 14 Drain St. '], ['USERNAME2', 'C XXXBUILDING 13 Drain St. '], ['USERNAME3', 'B ZZZBUILDING 12 Drain St. '], ... ] } Also as a workaround, this is a closest thing to the answer but i could not make it done without looping every user or executing raw sql in extra field. I want to achive this with Django Object Relational Mapping. address_subquery = Address.objects.filter(user__id=F('pk')).order_by('created') User.objects.filter(**my_custom_filters).annotate( subbuildingname_str=Subquery(address_subquery.values('subbuildingname')[:1], output_field=CharField()), street_str=Subquery(address_subquery.values('street')[:1], output_field=CharField()), buildingname_str=Subquery(address_subquery.values('buildingname')[:1], output_field=CharField()), buildingnnumber_str=Subquery(address_subquery.values('buildingnnumber')[:1], output_field=CharField()), ).annotate( address_text_str=Concat( 'subbuildingname_str', Value(' '), 'buildingname', Value(' '), 'buildingnumber', Value(' '), 'street_str', output_field=CharField(), default="" ) ).values_list('name', 'address_text_str') -
How To Paginate Django REST API With Angular11?
I am trying to consume a Django REST pagination object using Angular 11. I not a total coding noob, but I am very new to Angular. Currently my Django REST api is configured to paginate every 6 items, and the total items in the object is 10. Django then outputs a "next" URL that would work fantastic with Django's string interpolation feature, but is not so easily figured with Angular. I followed this tutorial closely, not just because it has nearly complete codeblocks, but also because it's legit the only complete code example dealing with Django REST API and Angular pagination: Link to other stackoverflow question dealing with this same issue, but remains unreasolved The Django API outputs this object: Django REST API Paginated output My Angular model is thus: Angular model My pagination service: My pagination service My component: Component I'm trying to paginate My rendered result: enter image description here And the console error message: ERROR TypeError: Cannot read property 'results' of undefined Any help would be much appreciated! -
user: ["This field is required."] in DRF
I am trying to allow user to update the name of Lists they have created. However, when I attempt to POST the data I return the following error: user: ["This field is required."] I have racked my brain trying to solve this, hardcoded the username etc. but I keep turning up empty. I'd be grateful for some more expertise to assist me. Here is my view: class UpdateUserListViewSet(viewsets.ModelViewSet): serializer_class = UserListSerializer queryset = UserList.objects.all() def update(self, instance, validated_data): serializer_class = UserListSerializer if self.request.method == "POST": list_id = request.data.get('id') user = UserList(user=self.request.user.id) list_name = request.data.get('list_name') data = {'id':int(list_id), 'list_name': list_name} serializer = serializer_class(user, data=data) if serializer.is_valid(): serializer.update() return Response({'status' : 'ok'}, status=200) else: return Response({'error' : serializer.errors}, status=400) And here is my serializer: class UserListSerializer(serializers.ModelSerializer): class Meta: model = UserList fields = ['id', 'user', 'list_name'] -
Django multi tenant schemas errors while migrating
I'm working on a small project using Django and now I tried to install multi-tenant-schemas and I followed the documentation step by step but when I try to migrate I get some errors after doing this command: python manage.py migrate_schemas --shared Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/root/centrix/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/root/centrix/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/root/centrix/lib/python3.8/site-packages/django/core/management/base.py", line 322, in run_from_argv parser = self.create_parser(argv[0], argv[1]) File "/root/centrix/lib/python3.8/site-packages/django/core/management/base.py", line 296, in create_parser self.add_arguments(parser) File "/root/centrix/lib/python3.8/site-packages/tenant_schemas/management/commands/migrate_schemas.py", line 20, in add_arguments command.add_arguments(parser) File "/root/centrix/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 26, in add_arguments parser.add_argument( File "/usr/lib/python3.8/argparse.py", line 1398, in add_argument return self._add_action(action) File "/usr/lib/python3.8/argparse.py", line 1761, in _add_action self._optionals._add_action(action) File "/usr/lib/python3.8/argparse.py", line 1602, in _add_action action = super(_ArgumentGroup, self)._add_action(action) File "/usr/lib/python3.8/argparse.py", line 1412, in _add_action self._check_conflict(action) File "/usr/lib/python3.8/argparse.py", line 1551, in _check_conflict conflict_handler(action, confl_optionals) File "/usr/lib/python3.8/argparse.py", line 1560, in _handle_conflict_error raise ArgumentError(action, message % conflict_string) argparse.ArgumentError: argument --skip-checks: conflicting option st ring: --skip-checks Source : https://django-tenant-schemas.readthedocs.io/en/latest/install.html -
Send an email through Django in an if statement
I have an html template that looks like this: <table> {% for instance in queryset %} <tr> <td> {% if instance.quantity <= instance.reorder_level %} <div style="background-color: red;"> <a href="{% url 'item_detail' instance.id %}">{{instance.quantity}}</a></div> {% else %} <a href="{% url 'item_detail' instance.id %}">{{instance.quantity}}</a> {% endif %} </td> {% endfor %} </table> Basically an inventory system app. I want to send an email to a user when the item reorder level is at or below a certain amount. Right now I have it to just highlight red. I know I have to create a view to send an email, but how do I get a function to trigger in the: {% if instance.quantity <= instance.reorder_level %} **send_email right here** {% else %} `**don't send email**` {% endif %} if statement? I am new to django and I have seen a lot of tutorials to send emails by form submit but not in this way. Thank you for any help! -
How to populate select option dropdown with database info in django
I have a django project with a select dropdown. I have typed in the names of players that users can select, but i want to populate the dropdown with the same names but dynamically from the database. How can i go about this? This is my html so far, not sure how to write the views.py for this, or if i should do a for loop or and if. <form method="POST"> {% csrf_token %} <select id="playerselect" name="pitcher" class="player-dropdown"> <option value="{{ pitching.id}}">{{ pitching.player_name }}</option> <option value="2">Yadiel Lugo</option> <option value="3">Cody Reeds</option> <option value="4" >Xavier Colon</option> <option value="5" >Andy Smith</option> <option value="6" >Carson Rex</option> <option value="7" >Jalen Jackson</option> <option value="8" >Matthew Cobbs</option> <option value="9" >Matt Sampson</option> <option value="10" >John Harrison</option> <option value="11" >Robert Santiago</option> <option value="12" >Efrain Zuniga</option> <input type="submit" value="Search"/> </select> -
Is there way to confirm user email when user change his email inside his profile - django
I have an option that allows a user to change email in his profile but without confirming a new email so when he enters a new email I want activate the email to save it in his profile, how to add confirm I am using UserCreationForm is there 3rd party app i can use it ? (my django version is 2.2) models.py : from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() my code | forms.py : # Profile Form class EmailChangeForm(forms.ModelForm): email = forms.EmailField(required=True,label='Email',widget=forms.EmailInput(attrs={'class': 'form-control center container','style': 'width:85%;text-align: center;background-color:#f6f6f6','placeholder':' Enter Your New E-mail '}) ) class Meta: model = User fields = [ 'email', ] def clean_email(self): email = self.cleaned_data.get('email') if email and User.objects.filter(email=email).count(): raise forms.ValidationError('Email is already in use, please check the email or use another email') return email views.py : # Edit Profile View class EmailChange(UpdateView): model = User form_class = EmailChangeForm success_url = reverse_lazy('home') template_name = 'user/commons/EmailChange.html' def get_object(self, queryset=None): return self.request.user urls.py : from django.urls import path from blog_app.views import SignUpView, ProfileView, ActivateAccount,EmailChange urlpatterns = [ path('profile/change-email/me/', EmailChange.as_view(), … -
SSL for Django project on bitnami
I have an Django project deployed on ubuntu AWS instance with Bitnami and configured with Lightsail, Route53. The project is working for HTTP. I've tried to migrate to HTTPs using the bncert-tool and got DNS with HTTPS, although I see: "You are now running Bitnami Django 3.1.6 in the Cloud" instead of my project. HTTP://<static_ip> is showing my project. ps: I didn't enable: sample-vhost.conf and sample-https-vhost.conf, as if I do that I see "You don't have permission". Is there additional steps that should be executed after bncert-tool? -
Django queryset for Case object and When Object, ---
I would to get your help on the following : I have two models Parent model and a Child Model: class Rate(models.Model): RATE_VOLTAGE_CHOICES = ( (BAJA_TENSION, "Low tension"), (MEDIA_TENSION, "Mid tension"), (ALTA_TENSION, "High tension") ) rate_type = models.CharField(max_length=1, choices=RATE_TYPE_CHOICES, default="0") class ParentRate(models.Model): rate = models.ForeignKey(Rate, on_delete=models.SET_NULL, blank=True, null=True ) so front-end wants to "filter" rate_type choice by Low tension, Mid Tension, and High tension as strings, they send strings so I am trying to use When Case object so I can filter then: rates = ParentRate.objects.annotate(rate_voltage=Case( When(rate__rate_type=Rate.BAJA_TENSION, then=Value('Low tension')), When(rate__rate_type=Rate.MEDIA_TENSION, then=Value('Mid tension')), When(rate__rate_type=Rate.ALTA_TENSION, then=Value('High tension')), default=Value('Low tension'), ) ) but I am getting the following error: django.core.exceptions.FieldError: Cannot resolve expression type, unknown output_field -
My code is still throwing out httperror 403 forbidden i tried connecting to nasa api, i even tried using csfr_exempt
from django.shortcuts import render from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt import requests import json import os import urllib.request from django.http import HttpResponse from django.conf import settings from .models import Destination @csrf_exempt @login_required def apod(request): url = 'https://api.nasa.gov/planetary/apod?api_key=4ZafMxbFfczTLG5ScI4Iej3zrfkHeOOEYz21cc8h' os.environ['NO PROXY'] = 'api.nasa.gov/planetary' apod_url = urllib.request.urlopen(url) apod_read = apod_url.read() decode_apod = json.loads(apod_read.decode('utf-8')) return HttpResponse(decode_apod) -
How do I prevent Django from applying a migration
I am on a team working on a project using Django. Besides my local dev server, we also have the Test environment and Live environment. In the process of undoing changes and reverting PR, the test and Live environment databases are out of sync, but the codes are the same. In our workflow, we merge the feature branch into the test branch, then test branch into master(Live branch) The local dev server and the test DB have a table column that I need to remove. This column is not in the Live environment db. I make the appropriate change to the model class, generate and apply the migrations and push to test branch. The migration is applied in the test environment. My Challenge When test is merged to master, Django attempts to apply the migration to remove the column but fails to find the column. Hence, error is thrown. Is there a way to mark this migration so that on Live DB, Django does not apply it? Note: I do not have access to the Live Db, otherwise I would have manually added the column to be remove by the migration. Thanks. -
Can't get ModelForm ChoiceField return as string - Cannot assign "'5'": "Reclamacoes.uf" must be a "Estados" instance
This form gets entries from models Estados, Cidades, Categorias and Status from the database, to be displayed in ChoiceFields. The other fields are CharFields, EmailFields and a PhoneNumberField (from this lib). After pressing the submit button with proper data, I get the following error: "Cannot assign "'5'": "Reclamacoes.uf" must be a "Estados" instance." Tried several different widgets and form elements to try and get this input as string (including forms.Select), but they don't fulfill the purpose I'm looking for. models.py from django.db import models from phonenumber_field.modelfields import PhoneNumberField class Estados(models.Model): nome = models.CharField(("nome"), max_length=50) unidade = models.CharField(("unidade"), max_length=2) disponibilidade = models.BooleanField(("disponibilidade"), default=False) class Cidades(models.Model): nome = models.CharField(("nome"), max_length=50) uf = models.ForeignKey("Estados", on_delete=models.CASCADE) disponibilidade = models.BooleanField(("disponibilidade"), default=False) class Categorias(models.Model): tipo = models.CharField(("tipo"), max_length=50) disponibilidade = models.BooleanField(("disponibilidade"), default=False) nome = models.CharField(("nome"), max_length=50) class Status(models.Model): status = models.CharField(("status"), max_length=50) class Reclamacoes(models.Model): uf = models.ForeignKey("Estados", on_delete=models.CASCADE) cidade = models.ForeignKey("Cidades", on_delete=models.CASCADE) categoria = models.ForeignKey("Categorias", on_delete=models.CASCADE) autor = models.CharField(("autor"), max_length=50) email = models.EmailField(("email"), max_length=254) telefone = PhoneNumberField(null=False, blank=False, unique=False) reclamacao = models.CharField(("reclamacao"), max_length=50000) status = models.ForeignKey("Status", on_delete=models.CASCADE) forms.py from django import forms from django.db.models import fields from phonenumber_field.formfields import PhoneNumberField from .models import Estados, Cidades, Categorias, Status, Reclamacoes from django.core.exceptions import ValidationError class FormReclamacao(forms.ModelForm): uf = … -
Trying to add OCR to a PDF, then upload to AWS using Django
I'm developing a web app so I can OCR files while at work but not have Adobe tied up the whole time it's running the OCR. My goal is to allow a user to upload a non-OCR'd PDF, have it be OCR'd via the ocrmypdf tool, then have the resulting OCR'd file sent to an S3 bucket where it's downloadable by the user. I've verified that I can save a regular PDF to S3, but I'm getting hung up on how to actually save the OCR'd version to S3. Here is the view I currently have for doing the OCR'ing: class CreatePost(generics.CreateAPIView): permission_classes = [IsAuthenticated] parser_classes = [MultiPartParser, FormParser] def post(self, request, *args, **kwargs): posts_serializer = FileSerializer(data=request.data) if posts_serializer.is_valid(): uploaded = posts_serializer.save() ocr_pdf = subprocess.call(['ocrmypdf', uploaded.file.path, 'output.pdf']) return Response(ocr_pdf, status=status.HTTP_201_CREATED) else: print('error', posts_serializer.errors) return Response(posts_serializer.errors, status=status.HTTP_400_BAD_REQUEST) return uploaded I'd really appreciate any help with this. Thanks! -
Django Email Confirmation: Opening the email alone will fire user update, they don't even have to click the link
I have email confirmation set up so that when a user registers, they will have is_active set to true but my custom email_confirmed field will be false. For that to be updated to true, they must click on an email sent to them upon registration. This is what the email looks like: The weird thing is that as soon as I open this email, without even hovering or clicking the link, I can see in the Heroku logs that the activate() function in views.py (shown below) is firing! I don't even have to click the link. This is causing issues, is there any way I can block the function from firing just from someone opening an email? Preferably I would like a plaintext option, as not all email providers correctly present html emails. views.py function called upon click of the link in email: #View called from activation email. Activate user if link didn't expire (1 week). Offer to resend link if the first expired def activation(request, key): # key is the pk accepted in the url from clicking the link in the email. User may/may not be logged in... Actually maybe i will require login print('~~~in activation()~~~') user = User.objects.filter(activation_key=key).first() … -
how should I configure mailman on ubuntu 20.04
I'm having an ubuntu 20.04 and I want to send an email to a list email and all the members under the list receive the email. on my server there is a django-based website running using apache2 webserver. How should I install the mailman and config it to perform the task? -
Receive only one row, if multiple rows with same credentials exist in Django - SQLite
I am looking for an elegant way to do a query in Django on a SQLite and only get one result, if there is multiple rows with the same content. My example: I have multiple time slots, which I model like this: class Slots(models.Model): year = models.IntegerField(_("Year"), blank=False) month = models.IntegerField(_("Month"), blank=False) day = models.IntegerField(_("Day"), blank=False) hour = models.IntegerField(_("Hour"), blank=False) block = models.IntegerField(_("Block"), blank=False) date = models.DateTimeField(_("DateTimeField"), blank=False) Lets assume I have two entries with: year = 2021 month = 4 day = 22 hour = 15 block = 0 date = DateTimeField(2012/04/22,15:00:00) When I do a: Slots.objects.filter(year=2021, month=4, day=22, hour=15, block=0) I get two entries, but I only want one, as long as the condition is matched. -
How do I check if user exists in db given an email and a number and then create it or update it?
I wrote this code that does not work since it has some syntax errors among other things but I think the functionality I'm looking for can be seen in it. I basically need to check if given an email or a phone, the user exists and, if it does, return it. Then, if the user inputs both their email and phone, I need to get the user if it exists, update it if one of the fields is different, create it if it doesn't exist and, if there're two users (one with the same phone, another one with the same email) return none. How can I improve this so that it actually works? def create(self, validated_data): filters = {} if email = validated_data.get('email') or telefono = validated_data.get('telefono'): filters["email"] = email filters["telefono"] = telefono try: go = Cliente.objects.get(foo='bar') except Cliente.DoesNotExist: go = None elif email := validated_data.get('email') and telefono := validated_data.get('telefono'): filters["email"] = email filters["telefono"] = telefono try: go = Cliente.objects.get(foo='bar') except Cliente.DoesNotExist: cliente, _ = Cliente.objects.update_or_create(**filters) return user except Cliente.MultipleObjectsReturned: go = None This is the models: class Food(models.Model): nombre = models.CharField(max_length=100, unique=True) cant = models.IntegerField(default=0) def __str__(self): return self.nombre class Order(models.Model): fecha = models.DateField(auto_now_add=True) email = models.EmailField(max_length=200, null=True) telefono … -
Inserting javscript function parameters into django template syntax
I've got a setup where I basically have a button that passes an ID to a javascript function, like so: <script> function posted(key){ console.log("test is", `{{ appointments.appointments.106 }}'`) } </script> the appointments dictionary is in the front end, and something like this works fine. So, I wanted to use the key input here, and do something like this: <script> function posted(key){ console.log("test is", `{{ appointments.appointments.${key} }}'`) } </script> but for the life of me I cannot get this to work. Doing it like this throws a syntax error, so I've tried escaping the brackets, even tried concatenation, etc. and nothing works -- seems like Django refuses to dynamically inject variables like this. Is there any workaround here? Thanks. -
Adding image background using django-imagekit
I'm using django imagekit for generating thumbnails of transparent images(png) to jpeg using ImageSpecField. How can i use a image to make the background of jpeg thumbnails. Here is my code : class Image(Base): def get_image_path(instance, filename): ext = filename.split('.')[-1] filename = "%s.%s" % (uuid.uuid4(), ext) return os.path.join('images', str(instance.subcategory.category.category_slug), str(instance.subcategory.sub_slug), filename) image = models.ImageField(upload_to=get_image_path, null=True) image_thumbnail = ImageSpecField(source='image', processors=[ResizeToFit(480,480)], format='JPEG', options={'quality':60}) image_preview = ImageSpecField(source='image', processors=[ResizeToFit(800,800)], format='JPEG', options={'quality':60}) -
how can I redirect to a dynamic url using HTML?
My code is {% if user.employee.employee_id == 2 %} <head> <title>HTML Redirect</title> <meta http-equiv="refresh" content="1; url = employee/2/" /> </head> {% elif user.employee.employee_id == 4 %} <head> Wait! <title>HTML Redirect</title> <meta http-equiv="refresh" content="1; url = employee/4/" /> </head> As you can see from above, i am using if elif to access pages based on the id of employee and this method is not efficient. I want to change the employee_id to variable. something like this: x = user.employee.empolyee_id <head> Wait! <title>HTML Redirect</title> <meta http-equiv="refresh" content="1; url = employee/x/" /> </head> -
I can't load my method in the browser when i add the id number /id
I'm working on a small project using Django / Rest Framework. I try to access my show method in the browser but it doesn't work like that /contacts/show/15/ This is my class class ContactView(viewsets.GenericViewSet): @action(methods=['GET'], detail=True) def show(self, request, pk): return Response("i would like to get the id from the url") This is my urls from django.urls import path from contact.api.views import ContactView from rest_framework import routers router = routers.DefaultRouter() router.register(r'contacts', ContactView, basename="contact") urlpatterns = router.urls how can i access to the id (15) in my function -
Django Channels | Can you do a SQL Query in a Channels Consumer?
i am making a Tool which can show me the Temperature of an Connected thermostat via GPIO. I want to log the temperature by sending the current temperature via an SQL Query to the Django SQLITE DB using Models. It also logs the current time when the temperature was recorded so i maybe later can do graphs or stuff like that. When i do it nothing happens. I dont get an exception in the Webserver Shell or on the webpage itself. The SQL Query im sending simply dosent work. Note that the temperature fuction works i tried it out by only showing the current temperature on the website. Models.py from django.db import models class TempLog(models.Model): temp = models.CharField(max_length=10) time = models.DateTimeField(auto_now_add=True, auto_now=False, blank=False) consumers.py Im using the fuction temp_db to create the SQL Query. The Temperature Data is being saved in the Variable ctemp. And then the function is called in the loop within the consumer. import asyncio import json from django.contrib.auth import get_user_model from channels.consumer import AsyncConsumer from .tempclient import getTempTCP from tcore.models import TempLog async def temp_db(tcptemp): tempdb = TempLog() TempLog.objects.create(temp=tcptemp) class TempConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) await self.send({ "type" : "websocket.accept" }) i = 0 …