Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django exclude() query with violation
I have this model: class SettingMenus(models.Model): cat = models.ForeignKey(Setting, on_delete=models.CASCADE, related_name="menus", null=True) index = models.SmallIntegerField(validators=[MaxValueValidator(32766)], default=0) name = models.CharField(max_length=100, null=True) path = models.CharField(max_length=200, null=True, blank=True) parent = models.ForeignKey('self', null=True, blank=True, related_name='sub_categories', on_delete=models.CASCADE) role = models.ManyToManyField(UserRole, related_name="settingMenus", blank=True) tables = models.ManyToManyField(AppModels, related_name="setting_menus", blank = True,) And a query in view: nv1menus = SettingMenus.objects.filter( cat__company__name=company, cat__application="common", index=0, role__in=request.user.groups.all() ).exclude(sub_categories__role__in=request.user.groups.all()).distinct() How I can violating sub_categories__role__in=request.user.groups.all() which is in exclude? I have tried: sub_categories__role__in!=request.user.groups.all() or not sub_categories__role__in=request.user.groups.all() But not works. -
Merging multiple querysets using union is showing error with Count in annotate
I have a simple django app and I am trying to merge multiple querysets using union but one of my queryset contains annotate with Count. I mean it is showing each UNION query must have the same number of columns LINE 1: ...::date GROUP BY 1 ORDER BY 15 DESC) UNION (SELECT I am using Count in annotate most liked blog post and most viewed blog post like filter_blog_posts = Blog.objects.annotate(f=Count("likes") + Count("views")) and other query which I am merging with is new_blogs = Blog.objects.order_by("-date") and like merged_q = Blog.objects.none() merged_q = merged_q.union(filter_blog_posts) merged_q = merged_q.union(new_blogs) and When I remove annotate then it is working fine but not with it. I saw many topics on showing error with annotate with union like this. and I also tried with it by adding values but my other queries will also need to be changed but I don't want to limit the fields. Any help would be much appreciated. -
How to show a list with ManyRelatedManager objects in nested serializer Django
I have a Category model (Parent) and a Product model (Child) with a FK to Category. Several products may belong to the same category and I want to show all products of a Category in GET request. But as a result, I get duplication of categories by the number of products. For example: If I have one cftegory "Milk" and 3 products with FK to "Milk", my GET method returns 3 instances of Category. my models.py class Category(models.Model): name = models.CharField(max_length=255) sku = models.CharField(max_length=255, blank=True, default="") class Product(models.Model): class Meta: default_related_name = "product" category = models.ForeignKey(CatalogItem, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=255, blank=True, default="") my views.py class CategoryApi(ListModelMixin, GenericViewSet): serializer_class = ProductCatalogSerializer def get_queryset(self): return Category.objects.all() My serializers.py class ProductCatalogSerializer(serializers.ModelSerializer): class Meta: model = CatalogItem fields = ( "sku", "name", "marketplaces", ) sku = serializers.SerializerMethodField(help_text="category SKU") marketplaces = serializers.SerializerMethodField(help_text="category products info") @staticmethod @swagger_serializer_method(serializer_or_field=serializers.CharField) def get_sku(obj): return obj.offer_id @staticmethod @swagger_serializer_method(serializer_or_field=serializers.ListField) def get_marketplaces(obj): results_data = MarketplaceInProductSerializer(list(obj.product.all()), many=True).data # results_data is a list with ordered dicts return results_data class MarketplaceInProductSerializer(serializers.Serializer): id = serializers.IntegerField(help_text="ID продукта") name = serializers.SerializerMethodField(help_text="Категория") @staticmethod @swagger_serializer_method(serializer_or_field=serializers.CharField) def get_name(data): return data.name I want to get in response a list with existing categories and products in it. -
Filtering ManyToMany in Django-Admin/Django-Form by related field
I want to filter my ManyToMany by related fields in the Django-Admin (create/edit object). For example i have 3 Models: Model 1 - Boardgame: Name (CharField), Genre (ForeignKey) Model 2 - Location: Name (CharField), Boardgame (ManyToMany) Model 3 - Genre: Name (CharField) Now in the django-admin when i edit a location i can add and remove boardgames via horizontal-filter. Now i want an extra select Field where i can define a genre, so the manyToMany choices change based on what i select on the genre-select. But i can't find an option to Include the genre-select To filter by the genre-select Anyone here having an idea, how to solve this? What i tried so far: Tried the django_advanced_filter because google lead me to it -> It is just for filtering in the "overview"-tab Tried to find a function that can do this natively in the admin -> Didn't find anything Had the idea to accomplish this via a modelsForm but wasn't able to find a possibility to add there a filter tab. Read something about django_filters, that maybe an option, but didnt find a possibility to integrate it in the forms.py -
strawberry-django isAuthenticated
I'm having a go at the Strawberry library for a new project. Actually, I'm quite liking it! However, in this project, pretty much everything needs authentication. But reading through the documentations, I would need to declare extension[IsAuthenticated()] on every field. This is not very DRY, nor very error-proof when more people get involved in the development. Can you point me in the direction, of give some suggestions how to implement this on a schema-level; where one can exclude specific field? -
Django uploads, video, images, pdf etc
Please I really need a solution, I’ve been trying to figure out on how I could create a model field where images, videos, pdf and other related files can be uploaded. Just like instagram where you can upload your file with Just one field, please I really need the solution please 🙏🙏🙏🙏🙏 I’ve tried using filefield, but the image tag in HTML keep giving me an error, image field has no attribute file -
__str__ returned non-string (type NoneType) I don't even where is the problem
I was making which user allowed to do what and which doesn't allowed by watching a video series. After I did something, which I don't know, I couldn't delete one user. Then I added one more user to see could I delete that one. First I added one user on admin panel then I deleted it, it worked. But when I tried to add one user with register page I couldn't delete it. Then I looked the customer's on admin panel and I couldn't see the name there was '-' instead of the name of user. decoraters.py from django.shortcuts import redirect from django.http import HttpResponse def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return redirect('home') return view_func(request, *args, **kwargs) return wrapper_func def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse('You are not autherized to view this page') return wrapper_func return decorator def admin_only(view_func): def wrapper_function(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group == "customer": return redirect('user') if group == "admin": return view_func(request, *args, **kwargs) return wrapper_function models.py from django.db import models from django.contrib.auth.models import User class Customer(models.Model): … -
How to implement google login in django?
I want to implement google login in Django without allauth or other packages. I wrote thisenter code here code. But only first function called " google_login is working ". google_call_back is not working and I can not capture user email. Here is my code. enter image description here -
I was trying to create register page by using `UserCreationForm` but getting empty `QueryDict` from post method
I was trying to create register page by using UserCreationForm but getting empty QueryDict from post method when I print it on console. There is no errors. I did research on it but could not figure it out. this is views.py file from django.shortcuts import render,redirect from django.contrib.auth import authenticate, login from django.contrib.auth.forms import UserCreationForm # Create your views here. def register(request): print('\n\n\n\n',request.POST,'\n\n\n') if request.method == 'POST': form=UserCreationForm() if form.is_valid(): form.save() return redirect('home/') else: form=UserCreationForm() context={'form':form} return render(request,'register/register.html',context) and this is my template: {% block content %} <form method="POST" class="form-group" action="#%"> {% csrf_token %} {{form}} <button type="submit", name="register", value="register1", class="btn btn-success" > Register </button> </form> {% endblock %}``` When I hit register button on website I am getting this traceback: ```System check identified no issues (0 silenced). September 21, 2023 - 10:00:05 Django version 4.2.5, using settings 'proproject.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. <QueryDict: {}> [21/Sep/2023 10:00:11] "GET /register/ HTTP/1.1" 200 3702 <QueryDict: {}> [21/Sep/2023 10:00:11] "GET /register/ HTTP/1.1" 200 3702 -
Is there a Node.js/Express.js library/framework for quick CRUD API setup like Django REST Framework?
I am currently working on a project in Node.js with Express.js, and I'm looking for a library or framework that can streamline the process of creating REST API endpoints for CRUD operations on my models, similar to how Django REST Framework simplifies this task in Django. In Django, I can quickly set up a model like this: from django.db import models class Artist(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name Then, I create a serializer: from rest_framework import serializers from songs.models import Artist class ArtistSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Artist fields = ['url', 'id', 'name', 'songs'] And finally, a viewset: class ArtistViewSet(viewsets.ModelViewSet): """ API endpoint that allows songs to be viewed or edited. """ queryset = Artist.objects.all() serializer_class = ArtistSerializer filter_backends = [filters.OrderingFilter] ordering_fields = ['name'] ordering = ['-name'] With these few lines of code, I can create API endpoints for creating, reading, updating, and deleting Artist records, as well as add sorting and filtering functionality. It's a very convenient and efficient approach. I'm wondering if there is a similar library or framework in the Node.js/Express.js ecosystem that offers a similar level of simplicity and ease of use. I find that in Node.js, there tends to be more boilerplate code … -
Django Graphql Auth mutations failing with error unexpected keyword argument 'refresh_token'
In my project I am using below libraries for django graphql authentication, django-graphql-jwt django-graphql-auth PyJWT I am running below mutation and some other similar mutations. mutation Register { register( email: "appleorange@gmail.com" password1: "Abcd@2023" password2: "Abcd@2023" ) { success errors refreshToken token } } From yesterday suddenly all mutations started failing with error, { "errors": [ { "message": "Register.__init__() got an unexpected keyword argument 'refresh_token'", "locations": [ { "line": 47, "column": 5 } ], "path": [ "register" ] } ], "data": { "register": null } } I tried changing the library versions for above package by switching to the old one but that did not help. I don't understand what exactly changed. Please suggest. -
Why the self.field returns no value, but getting it from a query.get returns the value?
I have this function that receives self as a parameter and im trying to check some fields in the object. The problem is when i do this checking, the self.field returns nothing but when i do a get in the object the field returns the correct value. Look def aguardando_exames_email_html(self): pedido = PedidoPlaca.objects.get(pk=self.pk) exame_escaneamento = pedido.exame_escaneamento #returns the obj #exame_escaneamento = self.exame_escaneamento #returns nothing ... I just need to understand what happens in django in this case and when to use self and when to use the object from database. -
Python/Javascript Websocket disconnects after first message
I have this python code (Server) async def chatProcess(websocket): message = await websocket.recv() print(f"<<< {message}") ints = predict_class(message) res = get_response(ints, intents) print("Category"+ints) await websocket.send(res) print(f">>> {res}") async def main(): async with websockets.serve(chatProcess, "localhost", 8765): await asyncio.Future() # run forever if __name__ == "__main__": asyncio.run(main()) and this javascript client in my webpage let websocket = new WebSocket("ws://localhost:8765"); const generateResponse = (chatElement) => { const messageElement = chatElement.querySelector("p"); try{ websocket.send(userMessage); websocket.onmessage = function(event) { messageElement.textContent = event.data; console.log("[message] Data received from server:"+ event.data); return false; }; } catch(error) { console.log(error) messageElement.classList.add("error"); messageElement.textContent = "Somethings wrong. Try Again"; } finally{ chatbox.scrollTo(0, chatbox.scrollHeight); } But keeps disconnectong after first message and get this error enter image description here What can I do so that it doesn't disconnect and I can send messages between client and server? -
Installed module causes 'ModuleNotFoundError' when executing script from Python. How can I use installed modules in my scripts?
We develop using the django framework. When using subProcess.run() to run a python file, a pip installed module is causing a 'ModuleNotFoundError'. Is the module not loaded in the file executed by subProcess.run? Also, how do I use the module? The development environment is built on AmazonLinux2 within docker. ・Process for calling Python files # No error occurs in this file. import yaml script = os.path.join(os.path.dirname(__file__), "script.py") subprocess.run( [script, args1, args2], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) ・Python file to be called #!/usr/bin/env python3 # os is loaded import os import yaml def main() { ~~~~~~~~ } ・Error Description ModuleNotFoundError: No module named 'yaml' ・install pip install pyyaml -
SEO for every blog post in Django Python framework
I am working on Django application for rendering blog posts on various topics. As you know, in WordPress Yoast / math rank plug in there is an option for SEO for every blog post using meta tags. My question is can we use meta tags in the {% block content %} within the body of the blog post in Django, or otherwise. Bear in mind that Django documentation recommends, using meta tags in the base.html file and in the head section only. If we use the meta tags in the head section in HTML, then how it can be altered for each and every blog post. Thanks -
overriding behavior when 'submit' button clicked in Django
I am trying to develop a tennis ladder Django website that has classes for Player, Match, and Ladder. I have imported some dummy data and also have Create, Delete, Update, and List views for players and matches. But when a player is created, I need to also create a new Ladder object that will contain the new state of the ladder. Likewise, when a player is deleted (or is unavailable due to injury), the ladder state must change, and a new ladder is created. (I want to retain a historical record of each ladder state in case something is done by mistake ... this lets me revert to an earlier verson of the ladder). Finally, ladder positions change if a challenger defeats his or her opponent. Here's my question. How do I trigger such code in a DeleteView (e.g. deleting a player). For a CreateView, I use this approach: class PlayerCreateView(CreateView): model =Player num_players = Player.objects.count() context_object_name = 'player' fields = ['ranking', 'first', 'last', 'cell', 'email', 'availability'] template_name = 'player_create.html' success_url = reverse_lazy('players') def form_valid(self, form): response = super().form_valid(form) num_players = Player.objects.all().count() ladders = Ladder.objects.all() # <CALL CODE TO CREATE NEW LADDER OBJECT> return response But what about other scenarios … -
Django-channels Problems
Good day, I am currently learning how to implement WebSocket with Django and I have encountered some roadblocks. I'm using uvicorn and Django channels for my project, I am trying to implement a feature whereby I would be able to retain the previous message that I have been sent in a group chat. But this is my errors anytime I try to send messages. Traceback (most recent call last): File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/uvicorn/protocols/websockets/websockets_impl.py", line 247, in run_asgi result = await self.app(self.scope, self.asgi_receive, self.asgi_send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/uvicorn/middleware/proxy_headers.py", line 84, in __call__ return await self.app(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/channels/routing.py", line 62, in __call__ return await application(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/channels/routing.py", line 116, in __call__ return await application( ^^^^^^^^^^^^^^^^^^ File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/channels/consumer.py", line 94, in app return await consumer(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/channels/consumer.py", line 58, in __call__ await await_many_dispatch( File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/channels/utils.py", line 50, in await_many_dispatch await dispatch(result) File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/asgiref/sync.py", line 479, in __call__ ret: _R = await loop.run_in_executor( ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/concurrent/futures/thread.py", line 58, in run result = self.fn(*self.args, **self.kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/channels/db.py", line 13, in thread_handler return super().thread_handler(loop, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/asgiref/sync.py", line 538, in thread_handler return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/channels/consumer.py", line 125, in dispatch handler(message) File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/channels/generic/websocket.py", line 59, in … -
How can I perform a SQL JOIN using Django ORM when the models are not related?
I have two models that look like this: (tableA) class ModelA(models.Model): student_id = models.TextField() name = models.TextField() age = models.IntegerField() (tableB) class ModelB(models.Model): student_id = models.TextField() report_card_file_id = models.TextField() # Other fields in ModelB I created a sql query to join them that looks like this: SELECT tableA.*, tableB.report_card_file_id FROM tableA LEFT JOIN tableB ON tableA.student_id = tableB.student_id where tableB.report_card_file_id is not null; But how can I transform this query into Django orm so that I will have a QuerySet with student_id, name, age, and report_card_file_id? Here is some code I have, but I am not sure how to fill in the ?: a = ModelA.objects.all() a = a.annotate(?) I also tried using .raw() but then I get a RawQuerySet instead of just a QuerySet. -
django queryset that counts occurrences of sub string in field
I have a model called Animal that contains a field called text that starts with the animal name followed by optional text e.g. cat - grey long hair class Animal: text = models.TextField() I want to count the occurrences of text that start with cat, dog or fish and return that count per animal category. I assume something like this wold work: queryset = models.Animal.objects.all() animal_summary = ( queryset .annotate( cats=Count( Case( When(text__startswith="cats", then=1), default=0, output_field=IntegerField(), ) ) ) .annotate( dogs=Count( Case( When(text__startswith="dogs", then=1), default=0, output_field=IntegerField(), ) ) ) .annotate( fish=Count( Case( When(text__startswith="fish", then=1), default=0, output_field=IntegerField(), ) ) ) .values('cats', 'dogs', 'fish') ) return {"animal_count": animal_summary} But it appears to count the number of entries irrespective of the sub-string. -
NoReverseMatch error following Python Crash Course Book
I have been working through the Django chapter of the Python Crash Course book and have run into an issue with the 'Create new entry' page. When I try to access the page it gives me this error: NoReverseMatch at /topics/2/ Reverse for 'new_entry' with arguments '('',)' not found. 1 pattern(s) tried: ['new_entry/(?P<topic_id>[0-9]+)/\\Z'] and displays an error on my topic.html file: {% extends 'learning_logs/base.html'%} {%block content%} <p>Topic: {{topic}}</p> <p>Entries:</p> <p> <a href="{% url 'learning_logs:new_entry' topic.id %}">Add new entry</a> </p> <ul> {%for entry in entries%} <li> <p>{{ entry.date_added|date:'M d, Y H:i' }}</p> <p>{{ entry.text|linebreaks }}</p> </li> {%empty%} <li>There are no entries for this topic yet.</li> {%endfor%} </ul> {%endblock content%} As followed in the book I also wrote the view and URL path for the page def new_entry in views.py: def new_entry(request, topic_id): #add new entry for particular topic topic = Topic.objects.get(id=topic_id) if request.method != 'POST': #no data submitted, create blank form form = EntryForm() else: #POST data submitted, process data form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit = False) new_entry.topic = topic new_entry.save() return redirect('learning_logs:topic', topic_id=topic_id) #display blank or invalid form context = {'topic': topic, 'form': form} return render(request, 'learning_logs/new_entry.html', context) urls.py urlpatterns = [ #home page path('',views.index, name='index'), #topics … -
How to create tables in different schemas using Geodjango and Postgres/ PostGIS?
My question is very similar to the question asked and answered here, using the Meta class and db_table = 'schema"."tablename' approach to use multiple schemas: How to create tables in a different schema in django? This solution worked for me under the standard Django project framework (using django.db models); however, once I attempted to use this method in a Geodjango project (using django.contrib.gis.db models), I received the following error when trying to migrate a model that included geospatial fields (PointField, LineStringField, and PolygonField): django.db.utils.ProgrammingError: syntax error at or near "." LINE 1: CREATE INDEX "schema"."tablename_geom_point_id" ON "sch... How can I implement this approach using Geodjango to leverage the benefits of schemas directly in the model? Example code of what I tried and resulted in the error message has been presented below. models.py import uuid from django.contrib.gis.db import models class TableName(models.Model): id = models.UUIDField(primary_key = True, default = uuid.uuid4, editable = False) ... geom_point = models.PointField(blank=True, null=True) geom_line = models.LineStringField(blank=True, null=True) geom_polygon = models.PolygonField(blank=True, null=True) ... class Meta: managed = True db_table = 'schema"."tablename' Thank you for any support you can provide! -
Django 4.2: Pagination doesn't work for me
I'm trying to use pagination in Django. Here is my code: Views.py from catalog.models import Book from django.views import generic class BookListView(generic.ListView): """Display authors per 10""" model = Book paginate_by = 10 author_list.html {% extends "catalog/base.html" %} {% load static %} {% block content %} <h1> Authors </h1> {% if perms.catalog.can_add_author %}<p> <a href="{% url "author-create" %}"> New author </a></p>{% endif %} <figure> <img src="{% static "catalog/images/author.png" %}" alt="library" width=300/> </figure> {% if author_list %} <ul> {% for author in author_list %} <li> <a href="{{author.get_absolute_url}}"> {{author}} </a> </li> {% endfor %} </ul> {% else %} <p> No author. </p> {% endif %} {% endblock content %} base.html {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static "catalog/css/style.css" %}"/> {% block title %}<title> Local Library </title>{% endblock title %} </head> <body> {% block sidebar %} {% if user.is_authenticated %} <p> <u> Hello {{user.get_username}} </u> </p> {% endif %} <nav> <ul> <li> <a href="{% url "index" %}"> Home </a> </li> <li> <a href="{% url "books" %}"> Books </a> </li> <li> <a href="{% url "authors" %}"> Authors </a> </li> {% if perms.catalog.can_see_borrowed_book %} <li> <a href="{% url "borrowed-book" %}"> Books borrowed </a> </li> {% … -
Jinja+Django. Uncaught SyntaxError: Unexpected token '{'
I'm loading js from another file, where i has a line this.data = {{ data.as_list | safe }};. When it is right in html tag, everything works fine. But when it's in another file, it throws an error "Uncaught SyntaxError: Unexpected token '{'". Appreciate any answers. <div class="recipe"> <div class="recipe-page-pointer" id="recipe-left-page-pointer"> <svg width="28.5" height="28.5" viewBox="0 0 28.5 28.5"> <path fill="#FFFFFF" d="M 28.5 0 L 0 14.25 L 28.5 28.5 Z"></path> </svg> </div> <div id="recipe-page-content"> <span></span> </div> <div class="recipe-page-pointer" id="recipe-right-page-pointer"> <svg width="28.5" height="28.5" viewBox="0 0 28.5 28.5"> <path fill="#FFFFFF" d="M 0 0 L 28.5 14.25 L 0 28.5 Z"></path> </svg> </div> <script src="{% static 'dishes/js/dish-details.js' %}"></script> </div> -
Dockerizing Django with Rabbitmq and Redis - Ports don't work
I'm dockerizing a Django project which uses Celery, Rabbitmq and Redis. Celery can't connect to Rabbitmq: consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. And Redis (used for cache) doesn't work either. Error while opening a cached url: Error 111 connecting to 127.0.0.1:6379. Connection refused. docker-compose.yml: services: rabbitmq: container_name: rabbitmq image: rabbitmq:latest networks: - main ports: - "5672:5672" restart: always environment: - RABBITMQ_DEFAULT_USER=guest - RABBITMQ_DEFAULT_PASS=guest celery_worker: container_name: celery_worker command: celery -A zwitter worker -l INFO build: . depends_on: - app - rabbitmq environment: - C_FORCE_ROOT=true networks: - main restart: always redis: container_name: redis image: redis:latest ports: - "6379:6379" volumes: - cache:/data command: redis-server --save 60 1 restart: always app: container_name: app build: . command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/src/ ports: - "8000:8000" networks: main: volumes: cache: Celery settings: # ... CELERY_BROKER_URL = "amqp://guest:guest@localhost:5672/" # ... Cache settings: CACHES = { "default": { "BACKEND": "django.core.cache.backends.redis.RedisCache", "LOCATION": "redis://127.0.0.1:6379", } } All containers are all up. -
Building a Django Q object for query
I am having an issue wrapping my head how to build a Q query in Django while setting it up as a dict. For example: I have a list of pks for properties and I am trying to filter and see if those pks are associated with either item = ['6', '21', '8', '13', '7', '11', '10', '15', '22'] I am trying to build a Q object that states: Q('accounts_payable_line_item__property__pk__in' = properties) | Q('journal_line_item__property__pk__in' = properties) while defining it in a dict I can pass to the queryset like so: If I define a filter dict and then create values it looks like this but it doesn't create the Q: filter_dict = {} filter_dict['accounts_payable_line_item__property__pk__in'] = properties filter_dict['journal_line_item__property__pk__in'] = properties queryset = queryset.select_related('accounts_payable_line_item', 'journal_line_item').filter(**filter_dict).order_by('-id')