Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'PIL' For virtual Environment
The Pillow library is installed for my Python environment my_proj still it is throwing the Error PIL module is not there. -
Django(Python),Assign value stay or on_move to the field row in Model
def mark_stay_location(): if TestLocation.objects.filter(processed=None): k = TestLocation.objects.filter(processed=None).order_by("timestamp") p = len(k) list_lat1 = [] list_lat2 = [] list_long1 = [] list_long2 = [] for i in range(p - 1): rowpairs = k[i : i + 2] lat1 = rowpairs[0].latitude list_lat1.append(lat1) lat2 = rowpairs[1].latitude list_lat2.append(lat2) long1 = rowpairs[0].longitude list_long1.append(long1) long2 = rowpairs[1].longitude list_long2.append(long2) lat = abs(lat2 - lat1) long = abs(long2 - long1) a = sin(lat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(long / 2) ** 2 c = 2 * atan2(sqrt(a), sqrt(1 - a)) for rowpair in rowpairs: row_id = rowpair.id po = TestLocation.objects.filter(id=row_id) if lat < 0.0009 or long < 0.0009: po.update(stay="stay") po.update(processed=True) else: po.update(stay="on_move") po.update(processed=True) print(list_lat1) print(list_lat2) print(list_long1) print(list_long2) duration() return Response(status=status.HTTP_200_OK) else: return Response(status=status.HTTP_404_NOT_FOUND) in database,TestLocation model fields are getting stored with values ,In above function k is querying all rows which have processed=None so far example it gives 100,then I'm using for loop using it's range and iterating with each consecutive pair of rows .In this pair I have latitude and longitude in each item of list and I used if condition if either the difference between lat or long between both items of lists is less than 0.0009 then I should set the … -
Using Signals to create data in a Django project once a boolean is changed
I have a question regarding signals. So I have the following model that has a boolean defaulted as False. Once the user clicks on a button to make it true I want to create objects in another model. Here is what I have done but did not create or make any changes: Here is the Initial Model: class Initial_Model(models.Model): active = models.BooleanField(default=False) Here is the model that I want to create objects once the Initial_Model active boolean becomes True: class ActiveSession(models.Model): start_date = models.DateTimeField(auto_now_add=True,blank=True, null=True) end_date = models.DateTimeField(auto_now_add=True,blank=True, null=True) @receiver(post_save, sender=Initial_Model) def create_session(sender, instance, **kwargs): if Initial_Model.active == True: ActiveSession.objects.create() My question is this the correct way of creating the instances in a model. What am I doing wrong and how to fix it. -
request an memory-eating endpoint many times before cache reproduced
I have an endpoint which consume lots of memory, so I use caching to reduce the memory overhead, but the problem is that, if user request it manytimes before the cache produced, it will consume lots of memory and cause oom killer, how can I handle this ? I tried use some limiter like flask-limiter, it just stop request again. the request doesn't use cached results. any help would be appreciated -
How to prevent file corruption/damaging during download from FTP to Django FileField
I have some excel and pdf files that can be opened and viewed correctly. They are probably old versions of both. However, after downloading these files from FTP and saving them to a Django FileField, they become damaged and can no longer be opened. All I need is to maintain the file as is during the transition. Unfortunately, I can't share any of the files as they contain confidential information. Here is the part of the code used to download and save the files: with io.BytesIO() as f: ftplib_connection.retrbinary('RETR ' + filename, f.write) f.seek(0) content_file = ContentFile(f.read(), filename) # Try f.getvalue(), f.getbuffer() return content_file # This will be saved to a Django FileField About the mimetypes, I used python-magic. All the pdf files are application/pdf. The excel files however are mostly application/CDFV2. Please note that I can open and view these files in their original state. The problem is after they are fetched from an FTP server and saved to a Django FIleField. -
Why can't I delete a custom function in django models migration?
I created a custom function to use in another class models.py class DateRangeFunc(models.Func): function = "daterange" output_field = DateRangeField() class Foo(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=256) start_datetime = models.DateField() end_datetime = models.DateField() class Meta: constraints = [ ExclusionConstraint( name="exclude_overlapping", expressions=( ( DateRangeFunc( "start_datetime", "end_datetime", RangeBoundary() ), RangeOperators.OVERLAPS, ), ), ), ] DateRangeFunc is the custom method I created to help write an exclusion constraint. I want to delete the Foo model as well as the DateRangeFunc class because both are not used anymore. When I try to makemigrations after removing both from models.py I get the following error: File "foo/migrations/0012_auto_20220907_1238.py", line 31, in Migration constraint=django.contrib.postgres.constraints.ExclusionConstraint(expressions=((foo.models.DateRangeFunc('start_datetime', 'end_datetime', django.contrib.postgres.fields.ranges.RangeBoundary()), '&&')), name='exclude_overlapping'), AttributeError: module 'foo.models' has no attribute 'DateRangeFunc' because it is still present in the old migration file 0012_auto_20220907_1238.py https://docs.djangoproject.com/en/4.1/topics/migrations/#considerations-when-removing-model-fields I should be able to add a system_check_removed_details if necessary (it is not in my case) and then squash -> remove models -> remove migration file. i.e. "Keep this stub field for as long as any migrations which reference the field exist. For example, after squashing migrations and removing the old ones, you should be able to remove the field completely." However, I can't run a squash because the … -
cannot response 'passenger__email' on the tripview class
i try to response passenger_email field on trip view but cannot response. the code on my program is here below. the main problem is here passenger__email class TripView(viewsets.ReadOnlyModelViewSet): lookup_field = 'id' lookup_url_kwarg = 'trip_id' serializer_class = NestedTripSerializer permission_classes = (permissions.IsAuthenticated,) # call only id and status field of trip model def get_queryset(self): user = self.request.user if user.group == 'passenger': #request to all drivers passenger_trip = Trip.objects.filter(passenger=user) #display only id and status field of trip model and user.email return passenger_trip.values('id', 'status', 'created', 'updated', 'pick_up_address', 'drop_off_address', 'price', 'passenger__email') return Trip.objects.none() the response code on postman is here below:- [ { "id": "412f04aa-3b34-4ee4-a07f-e464cff148c3", "created": "2022-09-12T12:27:31.542074Z", "updated": "2022-09-12T12:27:31.542091Z", "pick_up_address": "pokhara", "drop_off_address": "kathmandu", "price": "20", "status": "REQUESTED" } ] The urls of the code is here below app_name = 'taxi' urlpatterns = [ path('', TripView.as_view({'get': 'list'}), name='trip'), path('<uuid:trip_id>/', TripView.as_view({'get': 'retrieve'}), name='trip'), path('create/', CreateTripView.as_view(), name='create_trip'), ] -
Setting a route for a specific method in Django
I'm working with REST API in django from scratch. I mean, I'm not working with DjangoRestFramework directly, but i am using Class-BasedViews and some things from RestFramework. So, I am trying to return a GET response for all my actors but the problem is that I already have another GET response into my urls.py for the list of movies and Django returns the one who is first. Do you have any idea to solve this? Here is my Models, Views, and urls.py class Actor(models.Model): full_name = models.CharField(max_length=125) role = models.CharField(max_length=125) def __str__(self): return self.full_name @classmethod def find_actors(cls): actors = Actor.objects.all().order_by('pk') actors_list = [] for actor in actors: actors_list.append({ "full_name": actor.full_name, }) return actors_list class Movie(models.Model): ACTION = 'AC' DRAMA = 'DR' COMEDY = 'CM' SCIENCE_FICTION = 'SF' THRILLER = 'TR' RELIGIOUS = 'RG' GENRE_CHOICES = [ (ACTION, 'Accion'), (DRAMA, 'Drama'), (COMEDY, 'Comedy'), (SCIENCE_FICTION, 'Ciencia Ficcion'), (THRILLER, 'Triler'), (RELIGIOUS, 'Religioso') ] title = models.CharField(max_length=155, blank=False) synopsis = models.TextField(max_length=1000, blank=True) genre = models.CharField(max_length=100, choices=GENRE_CHOICES, default='', blank=False) tag = models.JSONField(default=dict, blank=True) actors = models.ManyToManyField(Actor, related_name='movies', blank=True) def __str__(self): return self.title @classmethod def find_all_movies(cls): movies = Movie.objects.filter(actors__isnull=False).distinct().order_by('pk') movie_list = [] for movie in movies: movie_list.append({ "id": movie.id, "title": movie.title, "synopsis": movie.synopsis, "genre": movie.genre, "tag": … -
Automatically create a model when another with ForeignKey is created
I'm trying to create a registration process where a certain model (Member) is automatically created when I create the model UserFields, but I'm unable to find a solution; this is what I tried: Models.py class Member(models.Model): member_id = models.AutoField(primary_key=True) user_creation_date = models.DateField(auto_now_add=True) Forms.py class MemberFieldsForm(forms.ModelForm): class Meta: model = MemberFields fields = [ "social_security_id", "first_name", "last_name", "birth_date", "birthplace", "gender", "admission_date", ] labels = { "social_security_id": "SSN", "first_name": "First name", "last_name": "Last name", "birth_date": "Date of birth", "birthplace": "Place of birth", "sex": "Sex", "address": "Address", "admission_date": "Admission date", } widgets = { "member_type": forms.TextInput(attrs={'class': 'form-control'}), "social_security_id": forms.TextInput(attrs={'class': 'form-control'}), "first_name": forms.TextInput(attrs={'class': 'form-control'}), "last_name": forms.TextInput(attrs={'class': 'form-control'}), "birth_date": forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}), "birthplace": forms.Select(attrs={'class': 'form-control'}), "address": forms.Select(attrs={'class': 'form-control'}), "sex": forms.Select(attrs={'class': 'form-control'}), "admission_date": forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}), "member_type": forms.Select(attrs={'class': 'form-control'}), } Views.py def index(request): if request.method == 'POST': form = MemberFieldsForm(request.POST) if form.is_valid(): c = form.changed_data["Member"] member = Member.objects.filter(name=c).first() if not member: member = Member.objects.create(name=c) MemberFields = form.save(commit=False) MemberFields.Member = Member MemberFields.save() return HttpResponse("Member registered") else: form = MemberFieldsForm() return render(request, 'add-member.html', {'form': form}) -
Postmark Webhook Signature Security
https://postmarkapp.com/developer/webhooks/webhooks-overview https://<username>:<password>@example.com/webhook Looking through the Postmark API, there does not seem to be any information about webhook signatures or tokens or hmac for security. The only security mentioned is basic authentication or firewalls. How do you even set up basic authentication or firewalls to work with Postmark webhooks? Is there anything that needs to be done on nginx or apache? Basic authentication like this? requests.post('url',headers=headers,auth=('username','password'), json=json_data) To me that does not seem as secure than signature verification. Other APIs like Mailgun have signatures and tokens and hmac for verifying webhooks in the request header. Mailgun Example: import hashlib, hmac def verify(signing_key, token, timestamp, signature): hmac_digest = hmac.new(key=signing_key.encode(), msg=('{}{}'.format(timestamp, token)).encode(), digestmod=hashlib.sha256).hexdigest() return hmac.compare_digest(str(signature), str(hmac_digest)) @csrf_exempt def mailgun_webhook(request): body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) signature = body['signature']['signature'] token = body['signature']['token'] timestamp = body['signature']['timestamp'] webhook_signing_key = 'KEY' if verify(webhook_signing_key, token, timestamp, signature) is True: print('do something') return HttpResponse(status=200) -
How to loop through an array in python
how to loop through this array and display the values en python {"products":[ { "desi":"kakakaka", "price":1400 }, { "desi":"mamama", "price":5000 }, ] } -
How can i enable the agent instance to be available in my agent update form when the agent is connected to the user through a one to one field
models.py class Auto(models.Model): user = models.OneToOneField("User", on_delete=models.CASCADE) def __str__(self): return self.user.username class User(AbstractUser): pass # To categorize users either as an organisor or as an agent is_organisor = models.BooleanField(default=True) is_agent = models.BooleanField(default=False) agent_details = models.TextField(null = True, blank=True) class Agent(models.Model): user = models.OneToOneField("User", on_delete=models.CASCADE) organisation = models.ForeignKey("Auto", on_delete=models.CASCADE) def __str__(self): return self.user.username views.py class Agent_update(ManualLoginRequiredMixin, generic.UpdateView): template_name = 'agent-update.html' form_class = AgentUpdateForm queryset = Agent.objects.all() context_object_name = 'agents' def get_success_url(self): return reverse('reverse url') agent-update.html <form method="post"> {% csrf_token %} {{form|crispy}} <button>Update Agent</button> </form> After running the server the form works but dosen't display the instance of the particular agent being updated. I feel it is because the Agent model is connected to the User model. Any help would be appreciated -
django_celery_beat task one_off=True does not start
django_celery_beat task one_off=True не стартует Я создаю объект задачи celery_beat, но она не срабатывает по времени ClockedSchedule models.py clocked, _ = ClockedSchedule.objects.get_or_create( clocked_time=datetime.utcnow() + timedelta(minutes=1) ) PeriodicTask.objects.create( clocked=clocked, one_off=True, name=f'CERTIFICATE SMS TASK {self.id}', task='apps.discounts.tasks.send_certificate_message', args=json.dumps([self.id]), start_time=datetime.utcnow() + timedelta(minutes=1), expires=datetime.utcnow() + timedelta(days=1) ) tasks.py @app.task(bind=True) def send_certificate_message(self, certificate_id) -> None: """ Task is not running """ ... Help, what does it take to run a celery_beat task once by ClockedSchedule? -
How to search inside string and modify
Python newbie here. A script I am using has a method s_lower(value) to lowercase every text posted by user. Also there are some special syntax such as [spec sometexthere]. I want to not lowercase if the text has a special syntax (in this case [spec ...] but lowercase all other text. For example, THIS IS A TEXT [spec CAPITAL] EXAMPLE This should be rendered as this is a text [spec CAPITAL] example Unfortunately, I wasn't be able to see/write logs (maybe because of docker), so I am kind of blind but hopefully this code block below will give you some hint to guide me WEBURL = r"(?:(?:(?:(?:https?):)\/\/)(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[?") # actually much more longer def s_lower(value): url_nc = re.compile(f"({WEBURL})") # Links should not be lowered if url_nc.search(value): substrings = url_nc.split(value) for idx, substr in enumerate(substrings): if not url_nc.match(substr): substrings[idx] = i18n_lower(substr) return "".join(substrings) return value.lower() I want something like if the value has "[spec" then find the index number of "[" and "]", then do not lowercase the text between those parantheses but lowercase all other text. -
Please is there anything i'm doing wrongly, filtered base on datetime, empty QuerySet
i got an empty QuerySet<[]>, i'd like to confirm if my models filtered are working before proceeding but seems the queryset from SubscribeEmailModel filtered from topic__startdate coming out as empty query here is my models.py class Lesson(models.Model): name = models.CharField(max_length=234) startdate = models.DateField(auto_now=True) class SubscribeEmailModel(models.Model): topic = models.ForeignKey(Lesson) please here is my views.py class AutoSendNotification(ListView): subscriber =SubscribeEmailModel.objects.filter(topic__startdate=datetime.datetime.today(), sent_mail=False) print(subscriber) model = SubscribeEmailModel context_object_name = 'subscriber' template_name = 'superadmin/email/auto-send.html' -
Dockerizing Django with PostgreSQL. FATAL: password authentication failed for user "postgres"
I am trying to dockerize my Django application with its PostgreSQL database. I have the following config files: docker-compose.yml version: '3' services: web: container_name: web build: context: . dockerfile: Dockerfile env_file: - csgo.env environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres ports: - '8000:8000' volumes: - .:/code depends_on: - postgres_db postgres_db: container_name: postgres_db image: postgres:13 env_file: - csgo.env environment: - POSTGRES_DB='postgres' - POSTGRES_NAME='postgres' - POSTGRES_USER='postgres' - POSTGRES_PASSWORD='postgres' - POSTGRES_HOST='postgres_db' - POSTGRES_PORT='5432' ports: - '5432:5432' csgo.env POSTGRES_DB='postgres' POSTGRES_NAME='postgres' POSTGRES_USER='postgres' POSTGRES_PASSWORD='postgres' POSTGRES_HOST='postgres_db' POSTGRES_PORT='5432' settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'postgres_db', 'PORT': '5432', } } I get the most typical error: web | File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect web | conn = _connect(dsn, connection_factory=connection_factory, **kwasync) web | django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres" web | What is the problem? What did I miss? Why this error occurs, if everything appear working fine? Note: I know this kind of question is popular on the Internet. But no one of them has answer to my question. Because my question is probably about mistake I have made (or a type) which I can't figure out for a whole day. Please help! -
How to render json data in Python Django App
I am new to Python . I am trying to create a webapp from Django which will read data from Excel file and then it will show that data on webpage in a form of dropdown . This is the structure of my web app which is I am creating I have also created a python script which is parsing the excel data and returning the json data import pandas import json # Read excel document excel_data_df = pandas.read_excel('Test-Data.xlsx', sheet_name='Sheet1') # Convert excel to string # (define orientation of document in this case from up to down) thisisjson = excel_data_df.to_json(orient='records') # Print out the result print('Excel Sheet to JSON:\n', thisisjson) thisisjson_dict = json.loads(thisisjson) with open('data.json', 'w') as json_file: json.dump(thisisjson_dict, json_file) This is output of this script [{"Name":"Jan","Month":1},{"Name":"Feb","Month":2},{"Name":"March","Month":3},{"Name":"April","Month":4},{"Name":"May","Month":5},{"Name":"June","Month":6},{"Name":"July","Month":7},{"Name":"August","Month":8},{"Name":"Sep","Month":9},{"Name":"October","Month":10},{"Name":"November","Month":11},{"Name":"December","Month":12}] Now where I am stuck is how we can integrate this in my webapp and how we can use this Json data to create a dropdown list on my webpage. -
Best practice to use django db connection in network call
I have two Django projects with DRF and have some Rest API's I want to use db connection of one Django project to another so i need to pass db connection/credentials over api network. I know we can get connection object using following from django.db import connections db_conn = connections['default'] and what am thinking is 1- to pass above db_conn in an api call as parameter to second project api but when am getting on other side its showing as string not as db connection object. 2- Another option is to pass credentials and create connection using sql alchemy in second project. So what is the best approach in above two scenarios?. Also it would be great if you can answer how to pass db connection object in api params as object not string -
How to apply a filter for each row of the same queryset on Django
I have the a model Product which has a relation with itself using the key "parent". This way, to get the parent of a product i just do product.parent and if i want the children of a product i do product.product_set.all(). What i want to do is to do an annotate on a queryset of parent products and sum the stock of each product with the stock of its children. Something similar to this: qs = Product.objects.filter(is_parent=True) qs = qs.annotate(stock_sum=Sum(Product.objects.filter(parent_id=F('id')).values_list['stock'])) Is this possible? Will it result in many queries or django know a way of handling this with a few joins? -
How do I get signals.py executed in this django environment?
I'm trying to run the following signals.py from .models import Sale from django.db.models.signals import m2m_changed from django.dispatch import receiver print("running") @receiver(m2m_changed, sender=Sale.positions.through) def calculate_total_price(sender, instance, action, **kwargs): print('action', action) print("running2") total_price = 0 print("running3") if action == 'post_add' or action == 'post_remove': print("running4") for item in instance.get_positions(): total_price += item.price print("running5") instance.total_price = total_price instance.save() apps.py already signals in VSCode that signals is not used from django.apps import AppConfig class SalesConfig(AppConfig): #default_auto_field = 'django.db.models.BigAutoField' name = 'sales' def ready(self): import sales.signals and then the init.py file default_app_config = 'sales.apps.SalesConfig' For completeness I'll add the models.py from django.db import models from products.models import Product from customers.models import Customer from profiles.models import Profile from django.utils import timezone from .utils import generate_code # Create your models here. class Position(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() price = models.FloatField(blank=True) created = models.DateTimeField(blank=True) def save(self, *args, **kwargs): self.price = self.product.price * self.quantity return super().save(*args, **kwargs) def __str__(self): return f"id: {self.id}, product: {self.product.name}, quantity: {self.quantity}" class Sale(models.Model): transaction_id = models.CharField(max_length=12, blank=True) positions = models.ManyToManyField(Position) total_price = models.FloatField(blank=True, null=True) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) salesman = models.ForeignKey(Profile, on_delete=models.CASCADE) created = models.DateTimeField(blank=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return f"Sales for the amount of ${self.total_price}" def save(self, *args, **kwargs): … -
Django Query across multiple models
So I am looking for some help (and hopefully and explanation) of how I access data across my multiple models because this one has left me completely snookered. I have a system for the sale of events (events model) now these events have multiple products(products model) and variable prices dependant on when you book (prices model), this part is working fine. Where I am struggling is there are also bundles of products (bundles table) which contain multiple products, and I need to get their attached prices. Now I have a list of bundles attached to the products being viewed but am struggling to query the ORM and get a full record - <Products (multiple)> - . I'm not completely new at this but it has left my completely stumped so any help would be greatly received. I have attached a sketch of the DB to help visualise. Thanks -
django.db.utils.OperationalError: no such table: django_site_id_seq
I got this error when running command python manage.py test for testing purpose. I tried after delete my pycache and migration files then run the python manage.py makemigrations and python manage.py migrate again as well. But still got the same error... Here is my test.py from rest_framework.test import APITestCase from django.urls import reverse from rest_framework import status # Create your tests here. class UserTest(APITestCase): def setUp(self): register_url = reverse('user:register') data = { "username":"Tester", "email":"tester@gmail.com", "password":"tester123", "mobile_number":"03322917356" } self.client.post(register_url, data, format='json') def test_user_can_register(self): register_url = reverse('user:register') data = { "username":"Tester1", "email":"tester1@gmail.com", "password":"tester123", "mobile_number":"03322911356" } response = self.clent.post(register_url , data , format='json') self.assertEqual(response.status_code ,status.HTTP_201_CREATED) -
OnSubmit function not working for an input type= 'submit'
I am making a quiz app using django and it's my first ever work using django Everything else is working fine instead of one thing which is whenever i press the button to submit the answer, page simply reloads. Here's my html code: <section> <div id = "results"></div> <form name = "quizForm" onsubmit = "return submitAnswers(answers = [{% for q in questions%}'{{ q.answer }}',{% endfor %}])"> {% for q in questions %} <h3> {{ q.id }}. {{ q.question }}</h3> .......... {% endfor %} <input type = "submit" value = "Submit Answer"> </form> <br><br> </section> Here's the js code relevance to the button: function submitAnswers(answers) { var total = answers.length; var score = 0; var choice = [] //dynamic method to get selected option for (var i = 1; i <= total; i++) { choice[i] = document.forms["quizForm"]["q" + i].value; } //dynamic method 1 for checking answer for (i = 1; i <= total; i++) { if (choice[i] == answers[i - 1]) { score++; } } //Display Result var results = document.getElementById('results'); results.innerHTML = "<h3>You scored <span>" + score + "</span> out of <span>" + total + "</span></h3>" alert("You scored " + score + " out of " + total); return false; … -
How to connect to Django Dramatiq Pg
I am using this package to connect with dramatiq queue on an EC2 instance. Although, I am able to connect to RDS with the same username/password using SSH Tunnel but it gives an authentication error when I try to connect with dramatiq pg. I am making a connection string as postgres://username:password@db-rds-link/db-name -
Multiple StreamBuilder using same data source
Directly connecting to websocket using Streambuilder works seamlessly but I tried to make the stream part of the provider so that I can access the stream data in multiple widgets without encountering the "Bad State: Stream has already been listened to". Is this a best way of handling multistreaming of data, if not what are my options? Websocket server is part of Django Code for provider is mentioned below late final WebSocketChannel _fpdSockets; Map _webSocketMessages = {}; Map get webSocketMessages { return _webSocketMessages; } WebSocketStreamProvider() : _fpdSockets = IOWebSocketChannel.connect( Uri.parse('ws://127.0.0.1:8000/ws/socket-server/'), ); Stream<Map<String, dynamic>> get dataStream => _fpdSockets.stream .asBroadcastStream() .map<Map<String, dynamic>>((value) => (jsonDecode(value))); void sendDataToServer(dataToServer) { print("Sending Data"); _fpdSockets.sink.add( jsonEncode(dataToServer), ); } void closeConnection() { _fpdSockets.sink.close(); } handleMessages(data) { print(data); _webSocketMessages = data; // notifyListeners(); } }