Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I get an appropriate loader to handle this file type in Django?
I have just started a django and react project. Whenever I try and load some css be it plain css or from bootstrap I get the following error: I followed the following tutorial: https://www.valentinog.com/blog/drf/ I move my .bablrc and my webpack.config.js into my project root folder. Previously it was inside the frontend app folder. Please let me know what I am missing! ERROR in ./src/components/App.js 39:6 Module parse failed: Unexpected token (39:6) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders | render() { | return ( > <Table striped bordered hover> | <thead> | <tr> @ ./src/index.js 1:0-35 Below are my files: My webpack.config.js: module.exports = { module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader" } } ] } }; My package.json: { "name": "frontend", "version": "1.0.0", "main": "index.js", "scripts": { "dev": "webpack --mode development ./src/index.js --output ./static/frontend/main.js", "build": "webpack --mode production ./src/index.js --output ./static/frontend/main.js" }, "keywords": [], "author": "", "license": "ISC", "description": "", "devDependencies": { "@babel/core": "^7.9.0", "@babel/plugin-proposal-class-properties": "^7.8.3", "@babel/preset-env": "^7.9.0", "@babel/preset-react": "^7.9.4", "babel-loader": "^8.1.0", "css-loader": "^3.4.2", "react": "^16.13.1", "react-dom": "^16.13.1", "ts-loader": "^6.2.2", "webpack": "^4.42.1", "webpack-cli": "^3.3.11" }, "dependencies": { … -
Python: Append a dictionary as a new object to a dictionary key
I am developing a Django API to populate certain sets of data under different sections/categories. In there each section/catergory will have multiple dictionaries. Requirement: "data": { "engineers": { {"id": 1, "name": "aaa"}, {"id": 2, "name": "bbb"}, {"id": 3, "name": "ccc"}, }, "doctors": { {"id": 5, "age": "50"}, {"id": 6, "age": "60"}, {"id": 7, "age": "70"}, }, } In this example I need to append new engineer objects to "engineers" node, and new doctor objects to "doctors" node. The method I've tried is as follows. data = {} data["engineers"].append({"id": 4, "name": "ddd"}) data["doctors"].append({"id": 8, "age": "45"}) Error: During handling of the above exception ('set' object is not subscriptable), another exception occurred: How can I do this? -
Django LDAP and docker: how i can manage to store a dynamic config?
i'm using Django-ldap-auth module (Git Repo), now, considering those deployment scenario: The container of the web application runs in a Docker swarm environment and it can be scaled I can't mount ANY volume, so, config files are out of questions due to data persistance The config needs to live in the settings.py How i can store the django-ldap-auth configuration that can be changed by the user directly from the frontend web application? I was considering to use docker secrets, but with docker-py i'm unable to retrieve a created secrets data. Does anyone has some ideas to solve this puzzle? -
What happens when data on Redis is not consumed?
I just got started with Redis and i'm trying to understand how does it work, so i apologize if what i'm gonna say is not correct. I want to build a real time system where a Python application retrieves stock market trades from around 600 markets. Those trades should be sent to a Django application and shown on the frontend in real time, so i would have Python retrieves the trades > Django receives them and sends them to the page. I did not know how would Django receive the trades, so i thought of making some research on Redis, to see if it would be useful for my case, so here is what i thought: i'm retrieving the trades from 600 markets, so for every market i would create a Redis channel, whenever a trade is received, my Python app will push it to the right Redis channel. On my Django app, whenever an user opens the market page, a connection will be established to the right Redis channel (according to the specifi market that the user requested), and in this way the user will receive the trades on their page. So it would be: Python app updates the … -
How do I hash passwords in DRF?
I have a problem with serialized data that Django REST Framework outputs because the password fields aren't hashed (especially the ones created direct from DRF). The user that I created using createsuperuser command has the serialized password hashed (pbkdf2) which is fine, but the ones that I create using DRF aren't. The serializer that I use looks like this (serializers.py): from users.models import User class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(style={'input_type': 'password'}) class Meta: model = User fields = '__all__' The model class looks like this (models.py): from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): class Role: ADMINISTRATOR = 'Administrator' PHARMACIST = 'Pharmacist' PATIENT = 'Patient' choices = { (ADMINISTRATOR, 'Administrator'), (PHARMACIST, 'Pharmacist'), (PATIENT, 'Patient'), } role = models.CharField(max_length=100, choices=Role.choices, default=Role.ADMINISTRATOR) first_name = models.CharField(max_length=100, blank=False) last_name = models.CharField(max_length=100, blank=False) email = models.EmailField(max_length=100, unique=True) birth_date = models.DateField(auto_now_add=False, blank=True, null=True) address = models.CharField(max_length=255) And the queryset looks like this (views.py): from django.shortcuts import render from users.models import User from rest_framework import viewsets from users.serializers import UserSerializer # Create your views here. class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() I am looking forward for your help. -
Django 2.2 disabled form field not passed to widget
I'm using the same form for creating and editing an object. One field cannot be edited when editing the object, so I passed it to self.fields['my_field'].disabled = True since django 1.9+ allow that (and it's cleaner). But whatever, the html doesn't change, the input is still editable and there's no disabled attribute on it. Checked in the view's context_data, my context_data['form'].fields['my_field'].disabled is True. So I don't understand what's happening. From what I saw here when the disabled is passed to the widget attributes. Am I missing somehting? When I manually do self.fields['my_field'].widget.attrs['disabled'] it's actually working. Do I have to add it myself to the widget ? Thanks in advance -
Non-pages in Django wagtail menu
I use wagtailmenus for my menus in Wagtail. This works fine for Wagtail pages. But sometime I wan't to include Django apps (e.g. photoalbum etc.) in the menu or submenu. Any ideas how to go about this? -
How to integrate Django and MySQL Server
How to integrate MySQL and Django? What are the scripts required? I cannot find anything on YouTube regarding this. I have installed both MySQL and Django. MySQL Workbench and Django using pip installer -
Django login page reloads and refreshes after entering username and password. Diagnosis says form is invalid but I don't know how?
It's a Django project. Upon entering the username and password, the login page refreshes and reloads instead of taking me to the homepage.html. When I ran a diagnostic in the view using print(form.is_valid()), it presented me with the base HTML code that makes up the built-in Django {{form}}, in the terminal. However, I'm unable to understand where exactly the fault lies. 1.The Login View def authentication(request): print(request.method) if request.method=='POST': form=LoginForm(request.POST) print(form.errors) print(form) print(form.is_valid()) if form.is_valid(): form.save() username=form.cleaned_data.get('username') password=form.cleaned_data.get('password') user=authenticate(username=username, password=password) login(request, user) return HttpResponse('Success') else: print('code failed') else: form=LoginForm() return render(request, 'TCloneTemplates/login.html', {'form':form}) 2.Forms.py class LoginForm(AuthenticationForm): username = forms.EmailField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': '', 'id': 'hello'})) password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '', 'id': 'hi',})) def is_valid(self): form = super(LoginForm, self).is_valid() for f, error in self.errors.items(): if f != '__all__': self.fields[f].widget.attrs.update({'class': 'error', 'value': strip_tags(error)}) return form 3.Login.html <body> <div class="pic"> <form method="POST"> {% block content %} {% csrf_token %} {{ form.non_field_errors }} {{form}} <button type="submit">Get Inside</button> {% endblock content %} </form> </div> </body> 4.The url that takes me there path('loginer/', views.authentication, name='loginer') The diagnostic message in the terminal POST <tr><th><label for="hello">Username:</label></th><td><input type="text" name="username" class="form-control" placeholder="" id="hello" maxlength="150" required></td></tr> <tr><th><label for="hi">Password:</label></th><td><input type="password" name="password" class="form-control" placeholder="" id="hi" required></td></tr> False code failed -
Implementing django guardian
Hello seniors and experts in programming , im having some problems implementing django guardian into my work flow engine , viewflow. I have read some example projects using django-guardian and viewflow , however i don't really understand how it works. From my understanding , django-guardian allows me to put restrictions on certain objects , how do i implement it in the case of view flow's process model ? What i wish to achieve is that at different phases of the process , I want different people to have access to it. For example , at phase 1 , only a people from group 'A' can approve it , in phase 2 , only people from group 'B' can approve it. It seems like an easy to do job but i have no clue on how to make it work. Here is some of my code: flows.py class Pipeline(Flow): process_class = PaymentVoucherProcess lock_impl = lock.select_for_update_lock #process starts here start = flow.Start( PVStartView, task_title="Processing New Voucher" ).Permission("preparer" ).Next(this.approve_by_preparer) #preparer will approve approve_by_preparer = flow.View( UpdateProcessView, form_class=PreparerApproveForm, task_title="Approval By Preparer" ).Assign(lambda act: act.process.assign_preparer #the permissions() method is really confusing, i don't understand how it works ).Permission("preparer" ).Next(this.documents) #not the end but just a … -
postgresql is connected in django but not in pgadmin 4
I have installed postgresql in ubuntu, it is working well. I am running django in locally too. This is my settings.py file: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'testdb', 'USER': 'postgres', 'PASSWORD': 'secret', 'HOST': '127.0.0.1', 'PORT': '5432' } } This is really working great with no objection, no complain, no error, no warning But i am experiencing a problem with connecting this testdb with pgadmin 4 My pgadmin 4 is running on docker. I am not getting why it is not connecting. pgadmin 4 saying: Unable to connect to server: could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? With the same information and credential, django sucessfully connected but why not on pgadmin 4? Can anyone help me to fix this issue? -
Why are Masonry (desandro) grid-items vertically overlapping? (Used with bootstrap 4 cards)
I have a hard time getting the DeSandro Masonry (https://masonry.desandro.com/) work together with bootstrap 4. What happens is that the bootstrap cards, which are children of the masonry grid-item, all overlap vertically on top of each other when the collapse button is clicked. Below can be seen the structure of the HTML file. I'm using python 3.8.2 together with django 3.0, as well as Bootstrap 4 and the latest version of Masonry. I've simplified the content for the sake of readability. <div class="container-fluid"> <div class="row justify-content-center"> <div class="col-2"> ...Some content here... <div class="col-9"> <!-- wrap all collapsible content --> <div id="entrycontent"> ...Some more content here... <div class="row"> <div class="col-12"> <div class="collapse multi-collapse" id="c{{entry.id}}" data-parent="#entrycontent"> ...Bootstrap Collapse Buttons here... <div class="grid"> <div class="grid-item"> <div class="collapse multi-collapse" id="onethinghere{{entry.id}}"> <div class="card p-2"> ...Main card content here... <div class="grid-item"> <div class="collapse multi-collapse" id="somethingelse{{entry.id}}"> <div class="card p-2"> ...Main card content here... <div class="grid-item"> <div class="collapse multi-collapse" id="somethingmore{{entry.id}}"> <div class="card p-2"> ...Main card content here... And so on... And initialized with jQuery at the bottom of the body tags.: <script> $('.grid').masonry({ // options itemSelector: '.grid-item', columnWidth: 200 }); </script> Also tried initializing with HTML as per the Masonry guide: <div class="grid" data-masonry='{ "itemSelector": ".grid-item", "columnWidth": 200 … -
Rendering Django template as an image [duplicate]
In my Django application, I have a model that I would like to render with a template (one image per object) and export the rendered output as an image with a given resolution. Is it possible? -
Django Python Forms - submitting complex view with multiple forms and formsets
Imagine this concept, I have a Taxi that can be ordered by a group for a full day multiple visits, and I should assign a group leader for each booking. now I have a Booking (PNR) that holds Clients traveling Routes, and a Group Leader (Operator) assigned for that booking. my view holds these: form for selecting the operator formset to add clients in this view I'm trying to make it easier for the user by giving the ability to save each form separately by ajax or save all data of forms by a button at the bottom of the view. I've been searching for a few days and I got the nearest approach on these two linkes 1 & 2 but still can't make my code run correctly and do what it's supposed to do. :( ANY SUPPORT WILL BE HIGHLY APPRECIATED! My models.py: class Operator (models.Model): name = models.CharField(max_length=50) # Other Fields def __str__(self): return self.code class PNR (models.Model): date_created = models.DateTimeField(auto_now_add=True) # Other Fields def __str__(self): return self.pk class Client (models.Model): related_pnr = models.ForeignKey(PNR, on_delete=models.CASCADE) name = models.CharField(max_length=200) # Other Fields def __str__(self): return self.related_pnr+" "+self.name My forms.py: class ChooseOperatorCode(forms.Form): operator = forms.ModelChoiceField(queryset=Operator.objects.all()) def clean(self, *args, **kwargs): … -
import datetime - Clarification
'''' from datetime import datetime now = datetime.now().time() print(now) o/p: 21:44:22.612870 '''' But, when i am trying: '''' import datetime now = datetime.now().time() print(now) '''' it give following error: Traceback (most recent call last): File "D:/3. WorkSpace/3. Django/datemodel/first.py", line 9, in now = datetime.now().time() # time object AttributeError: module 'datetime' has no attribute 'now' any one explain what is difference between both? -
Creating a Django form that allows "extra fields" on a "through" table to be edited
I have User, SocialNetwork, and UserSocialNetwork models in a Django 3.0.3 project. class User(AbstractUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) middle_name = models.CharField(blank=True, max_length=255, unique=False) bio = models.TextField(blank=True, default='') … socialnetworks = models.ManyToManyField(SocialNetwork, through='UserSocialNetwork') updated_at = models.DateTimeField(auto_now=True) class SocialNetwork(models.Model): name = models.CharField(blank=False, max_length=255) description = models.TextField(blank=True, default='') url = models.URLField(blank=False, max_length=255) format = models.CharField(blank=False, max_length=8, choices=[('handle', 'handle'), ('url', 'url')]) base_url = models.URLField(blank=True, max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['name'] def __str__(self): return self.name class UserSocialNetwork(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) socialnetwork = models.ForeignKey(SocialNetwork, on_delete=models.CASCADE) identifier = models.CharField(blank=False, max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['socialnetwork', ] verbose_name = "User's Social Network" I'm using django-formtools to step through profile creation. One of the steps should be a page where the profile creator is presented with a list of SocialNetworks and given the opportunity to enter their identifier on those networks. I've been struggling with this. It was suggested I use formsets and I've got this class UserSocialNetworkForm(BaseModelForm): class Meta: model = UserSocialNetwork fields = [ 'socialnetwork', 'identifier', ] labels = { 'socialnetwork': _('Social Network'), } UserSocialNetworkFormSet = formset_factory(UserSocialNetworkForm, extra=SocialNetwork.objects.count()) which yields this but all I really want is one line per … -
How to get details of a nested object in a serializer in DRF
So I'm trying to create a serializer that would return a bunch of details of a 'Post' model in my project, but I want to get details of a nested object as well, the output of which I will show below: Post model: class Post(models.Model): # Base post attributes user = models.ForeignKey(UserOfApp, related_name="posts", on_delete=models.CASCADE) ... # Repost post attributes original_repost = models.ForeignKey( to="self", related_name="reposted_post", null=True, blank=True, on_delete=models.CASCADE, ) # Quote post attributes is_quote_post = models.BooleanField(default=False) quoted_post = models.ForeignKey( to="self", null=True, blank=True, on_delete=models.CASCADE ) ... My serializer, using 'depth': class HomeSerializer(serializers.ModelSerializer): id_str = serializers.ReadOnlyField() ... quoted_post_id_str = serializers.ReadOnlyField() class Meta: model = Post depth = 2 fields = "__all__" This yields me an output like, the problem being it returns all sensitive data from my user model as well, like 'password' etc: { "id": 16, ... "is_quote_post": false, "user": { "id": 1, "password": "pbkdf2_sha256$180000$ni6drJvLjUU2$xoMt5tpJmz8TlmORfB/eTkYlGGpUGfriGz8rO7kVB8E=", "last_login": "2020-03-21T06:20:48Z", "is_superuser": true, "username": "manas", "first_name": "Manas", "last_name": "Acharekar", "email": "manas.acharekar98@gmail.com", "is_staff": true, "is_active": true, "date_joined": "2020-03-01T18:42:11Z", "dob": "1998-11-11", "gender": "M", "bio": "i own this place", "location": "", "website": "", "verified": true, "followers": [], "friends": [], "groups": [], "user_permissions": [] }, "original_repost": { "id": 1, ... "user": { "id": 1, "password": "pbkdf2_sha256$180000$ni6drJvLjUU2$xoMt5tpJmz8TlmORfB/eTkYlGGpUGfriGz8rO7kVB8E=", "last_login": "2020-03-21T06:20:48Z", "is_superuser": true, … -
How to implement Django Chained Drop Down using clever select
I'm using doing a small django project and using django-clever-select to created chained drop down select. I followed the exact instruction given in their installation useage guide at https://pypi.org/project/django-clever-selects/. But once i run the app in pycharm the dropdown doesn't show any data to be selected. models.py <pre> class Category(models.Model): mname = models.CharField(max_length=100, blank=False,unique=True) mdescription = models.CharField(max_length=255, blank=True) def __str__(self): return self.mname class Meta: ordering = ('mname',) class SubCategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE,null=True, blank=True) scname = models.CharField (max_length=100, blank=False,unique=True) scdecription = models.CharField(max_length=255, blank=True) def __str__(self): return self.scname class Meta: ordering = ('scname',) class Deals(models.Model): vendor_deal = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) subcategory = models.ForeignKey(SubCategory, on_delete=models.SET_NULL, null= True) description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateField(auto_now_add=True) expire_date = models.DateField(null=False) current_date = models.DateField(auto_now_add=True) def __str__(self): return self.description class Meta: ordering = ('description',) </pre> template file for the form ` {% extends 'base.html' %} {% load static %} {% block content %} </br></br></br></br> <div class="content"> <div class="row"> <div class="col-md-2"></div> <div class="col-md-6"> <form id="post_from" method="post"> {% csrf_token %} <div class="form-group"> {{ form.as_p }} </div> <button type="submit" class="btn btn-primary">Upload</button> </form> </div> <div class="col-md-2"></div> </div> <div class="row"> </div> <div class="row"> </div> </div> {% endblock %} </pre></code> ` form.py file `<pre> … -
Create a subclass not to repeat matching fields
I created two class models in Django. Is there a way not to repeat the same matching fields storing them in a different class or variable? This is what i got: class Post(models.Model): title = models.CharField(max_length=50) content = RichTextField(blank=True) category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE) posted_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) slug = models.SlugField(null=True, unique=True, editable=False) def __str__(self): return str(self.category) + self.slug + " " + str(self.id) def save(self, *args, **kwargs): self.slug = slugify(str(self.category)) + "/" + slugify(self.title+str(-self.id)) super(Post, self).save(*args, **kwargs) def __str__(self): return self.title class Post2(models.Model): title = models.CharField(max_length=50) content = RichTextField(blank=True) category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE) posted_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) slug = models.SlugField(null=True, unique=True, editable=False) def __str__(self): return str(self.category) + self.slug + " " + str(self.id) def save(self, *args, **kwargs): self.slug = slugify(str(self.category)) + "/" + slugify(self.title+str(-self.id)) super(Post2, self).save(*args, **kwargs) def __str__(self): return self.title -
prefetch_related on existing django instance
I have a prefetch_related defined on my ObjectManager - is it possible to get the prefetch_related functionality on an instance that wasn't retrieved by this manager? This would apply to something like a newly-created instance. class Foo(models.Model): objects = FooManager() class FooManager(models.Manager): return (...).prefetch_related("bars") fooA = Foo.objects.get(...).bars # prefetched + cached for later fooB = Foo.objects.create() fooB.bars # not prefetched fooB.bars # queries each time because not included in prefetch cache -
GeoDjango IntegrityError when following the Tutorial
I am precisely following the GeoDjango Tutorial: https://docs.djangoproject.com/en/3.0/ref/contrib/gis/tutorial/ and decided to use SpatiaLite instead of PostGIS as my db-Backend. In order to do that, i edited my projects settings.py-file: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.spatialite', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } Following the Tutorial worked up to the Part "LayerMapping". When running $ python manage.py shell >>> from world import load >>> load.run() i get the following error: django.db.utils.IntegrityError: NOT NULL constraint failed: world_worldborder.fips What can I do to fix this Error? Thanks in Advance! -
ImportError: cannot import name 'forms' from 'basicapp'
form.py: from django import forms class FormName(forms.Form): name=forms.CharField() email=forms.EmailField() text=forms.CharField(widget=forms.Textarea) views.py: from django.shortcuts import render from .forms import forms def index(request): return render(request,'basicapp/index.html') def form_page(request): Form = forms.FormName() return render(request,'basicapp/form_page.html',{'form':Form}) I dont know what is wrong here! when I run server, it makes an error, saying ImportError : cannot import name 'forms' from 'basicapp' -
Django form with only one select field is passing the input tag value instead of the selected one
Django beginner here. I have a form which asks the user to select an answer to be set as the correct one. Now my form is the following: class SelectCorrectAnswer(forms.Form): def __init__(self, choices, *args, **kwargs): super(SelectCorrectAnswer, self).__init__(*args, **kwargs) self.fields['correct_answer'].choices = choices correct_answer = forms.ChoiceField(choices=(), required=True) As you can see the choices are added dynamically, in fact, they are correctly displayed in the template, which is the following: <!--Select the correct answer--> <form action="{% url 'create-assessment' %}" method="post"> {% csrf_token %} {{ select_correct_form.as_p }} <input type="submit" value="Select" name="select-correct-answer" > </form> And retrieved in the view as shown below: # Initialize select correct answer form. problem_answers = Answer.objects.filter(creator=current_user, question=problem_to_be_answered) choices = [] for answer in problem_answers: choices.append((answer.answer, answer.answer),) select_correct_form = SelectCorrectAnswer(choices) print(choices) The view tries to handle the POST request as follows: # Set answer as correct. if request.method == 'POST' and 'select-correct-answer' in request.POST: print(f'CODE REACHED HERE {request.POST}') select_correct_form = SelectCorrectAnswer(request.POST) if select_correct_form.is_valid(): selected_answer = select_correct_form.cleaned_data['correct_answer'] correct_answer = Answer.objetcs.get(id=selected_answer.id) correct_answer.is_correct_answer = True correct_answer.save() print(f'THIS IS THE CORRECT ANSWER {correct_answer}') From the print statements, I can see that the correct request is being processed but the value I select is not passed. In fact, as you can see from the printed output, … -
Django blocked the raw socket connection
I build a socket server on the python and it worked. And when i call it as thread from django server the connection is refuse. This is my server code on thread: def add_device_to(self): socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostname() socket_server.bind((host, 5555)) socket_server.listen() while True: socket_c , address = socket_server.accept() print("ok") self.register(socket_c, address) This is my client code: socket_client1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostname() socket_client1.connect((host,5555)) The error on the client side is: socket_client2.connect((host, 5554)) ConnectionRefusedError: [Errno 111] Connection refused And when i tried that on windows it work fine. -
Use Django Queryset filter API on in-memory list of Model instances?
Is it possible to re-use the Django Queryset API when I've already retrieved a list of objects? i.e. foos = list(Foo.objects.filter(color="red")) large_foos = foos.filter(size="large") small_foos = foos.filter(size="small") I can of course iterate through my foos list, but it'd look cleaner to reuse the API. Use case is something like the color column being indexed but the result set small, and size isn't indexed (or size has high cardinality).