Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
List of Users ordered by the rank of their Posts reviews
I want to make an API End Point so the user can get a list of the users in his city ordered by their post reviews I have defined a method in the post model to calculate the total review (up vote and down vote), all is needed to do is to groupBy user_fk in the post and orderBy sum(count_review()), but I don't know how to do it in django Post Model class Post(models.Model): title = models.TextField(max_length=255, default='Title') post_owner = models.ForeignKey(MyUser, on_delete=models.CASCADE) description = models.TextField(max_length=255) city = models.ForeignKey(City, related_name='location', on_delete=models.CASCADE) longitude = models.CharField(max_length=255) image = models.CharField(max_length=255, default='https://www.eltis.org/sites/default/files/styles/web_quality/public/default_images/photo_default_2.png') latitude = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) def count_reactions(self): likes_count = Reaction.objects.filter(post=self.id, is_like=True).count() dislikes_count = Reaction.objects.filter(post=self.id, is_like=False).count() return likes_count - dislikes_count def owner(self): return self.post_owner MyUser Model class MyUser(AbstractUser): phone_number = models.BigIntegerField(blank=False, unique=True) city = models.ForeignKey(City, related_name='city', on_delete=models.CASCADE) address = models.CharField(max_length=255) def owner(self): return self The expected result is to get the ordered list of the users by their posts reviews but only the users in the same city (city field in MyUser model) -
How to use select_related in save method of a model?
Lets say I have the following models: from django.db import models class X(models.Model): ... class Y(models.Model): ... x = models.ForeignKey(X, on_delete=models.CASCADE) class Z(models.Model): ... y = models.ForeignKey(Y, on_delete=models.CASCADE) Now, in a normal query, I could chain select_related() functions like so: z = Z.objects.select_related('y__x').get(pk=1) This would automatically get the related X and Y objects. Now, what if I wanted to use select_related() in the Z class's overridden save() method. How would I go about doing this? Thanks. -
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect when trying to run server in Django
I wanted to create a login page for users on my website, but I cannot run the server because of an error. It seems as if I have specified a filename in the wrong way, but I can't find it. I am following Python Crash Course, so I examined the code a few times and nothing seems wrong. urls.py from django.conf.urls import url from django.contrib.auth import views as auth_views from . import views urlpatterns = [ # Login page url('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login') ] base.html <p> <a href="{% url 'learning_logs:index' %}">Learning Log</a> - <a href="{% url 'learning_logs:topics' %}">Topics</a> - {% if user.is_authenticated %} Hello, {{ user.username }}. {% else %} <a href="{% url 'users:login' %}">log in</a> {% endif %} </p> {% block content %}{% endblock content %} login.html {% extends "learning_logs/base.html" %} {% block content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} <form method="post" action="{% url 'users:login' %}"> {% csrf_token %} {{ form.as_p }} <button name="submit">log in</button> <input type="hidden" name="next" value="{% url 'learning_logs:index' %}" /> </form> {% endblock content %} This is the traceback I get in terminal: OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect … -
How to install quasar framework on django-vue project?
I try to install quasar framework on django-vue project. And always have any issues. Can someone give me a guide-link or help with it? I'm newbie on it and can't understand what I need to do -
convert 'set' object to back to its querryset object
b = Blog.objects.all() c= Blog2.objects.all() a= set(b+c) now type(a) is 'set' object i want to convert back it into class 'django.db.models.query.QuerySet'. -
How to fix "Cant Update profile in Django"
I ran into such a problem. The account has the ability to change the plan from free to premium for a certain period. When a user selects a package and synchronizes it in a date base is not saved. What's my mistake? Here is the code # model.py CHOICES = [('Free', 'free'), ('Premium', 'premium')] class MemberShip(models.Model): title = models.CharField("Title", max_length=100) period = models.IntegerField("Period", default=30) price = models.IntegerField("Price", default=2, help_text="Price in dollars") def __str__(self): return f'Plan - {self.title}' class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) status = models.CharField("Status", max_length=20, choices=CHOICES, default='Free') end_date = models.DateTimeField("End Date", blank=True, null=True) membership = models.ForeignKey(MemberShip, on_delete=models.SET_NULL, null=True, default=None) def __str__(self): return self.user.username # def get_absolute_url(self): # return reverse('account:profile', args=['id', self.id]) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() # form.py class PremiumForm(forms.ModelForm): class Meta: model = Profile fields = ['membership'] # view.py class GetPremium(LoginRequiredMixin, UpdateView): model = Profile form_class = PremiumForm template_name = 'account/premium.html' success_url = reverse_lazy('account:dashboard') def get_object(self, **kwargs): return get_object_or_404(User, pk=self.request.user.id) -
If statement Could not parse the remainder: '|' from '|"
I'm trying to use a filter inside of an if statement and whenever I do, I get the error below. I have looked through for typos and wasn't able to catch anything. Details.html (the template) {% extends "dashboard/header.html" %} {% block content %} {% load custom_filts %} <h1>{{ result }} <span class="badge badge-pill badge-info" style="background-color: {{ colour | hexify }}">{{ result | get_model_name }}</span></h1> {% if result|get_model_name == "Fixture" %} {% block fixture_data %} {% endblock %} {% elif result | get_model_name == "Cable" %} {% block cable_data %} {% endblock %} {% elif result | get_model_name == "Adapter" %} {% block adapter_data %} {% endblock %} {% endif %} {% endblock %} My custom filters from django import template register = template.Library() @register.filter def get_model_name(value): return value.__class__.__name__ @register.filter def hexify(value): return "#" + value When this is used, I get this error: TemplateSyntaxError at /dashboard/detail/1 Could not parse the remainder: '|' from '|' -
How to access a Serializer field from the model's View?
I'm trying to access a custom defined variable in the model's Serializer class from the model's View. But, I haven't found the correct way to do that. So, any help would be appreciated. I've tried to take its value only by its name, but that wasn't successful. I have this model: class candidates(models.Model): id = models.IntegerField(primary_key=True, blank=True) name = models.CharField(max_length=255, blank=True, null=True) gender = models.CharField(max_length=10, blank=True, null=True) skill = models.TextField(blank=True, null=True) note = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'candidates' This is the serializer for the model: class CandidatesSerializer(serializers.ModelSerializer): experiences = CandidateExperienceSerializer(many=True) full_duration = serializers.SerializerMethodField('get_full_duration') def get_full_duration(self, candidate): sum = 0 for exp in candidate.experiences.all(): if exp.work_from is None: exp.work_from = now() if exp.work_to is None: exp.work_to = now() sum += int((exp.work_to - exp.work_from).days / 30) return sum class Meta: model = candidates fields = ['id', 'name', 'gender', 'skill', 'note', 'full_duration', 'experiences'] In the serializer, I have an additional custom field 'full_duration' where I store the full experience duration of the candidate (in months). Finally, here's the part of the view for the model, where I have the problem: if min != 'null': candidates_list = candidates_list.filter(full_duration__gte=min) if max != 'null': candidates_list = candidates_list.filter(full_duration__lte=max) I expect the output … -
Django rest framework serialization tutorial confused
I don't get what following code does.I don't get from where "item[1][0]" comes to line 8. It is not defined.I don't get what next line does also. btw I have a java background. I get the idea of comprehensions so I get the seventh line. from django.db import models from pygments.lexers import get_all_lexers from pygments.styles import get_all_styles LEXERS = [item for item in get_all_lexers() if item[1]] LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])` STYLE_CHOICES = sorted([(item, item) for item in get_all_styles()])` -
Exclude records from query set providing they are a part of subquery and meet condition
I need to exclude records from one query set if another contains records with same field values and under certain condition. This is rather hard to digest requirement so I’ll explain on real problem that I’m trying to solve: A restaurant has time slots when guests can book tables (1pm, 1:30pm, 2pm, etc.). Each time slot has availabilities. Availability is a table (table for 2, table for 4, etc.) and number of how many tables of this type are available for this time slot (3 tables for 2, 3 tables for 4, 2 tables for 8, etc.). When booking a table reservation does not keep relation to exact table or availability but just stores timestamp when reservation is going to happen and number of guests. Through time when reservations are created for time slots availabilities should be decreased but not by decreasing number of bookable tables but by counting reservations for each specific time slot. We arrived at the problem itself: At some point I need to list time slots available to book with given number of guests for given date but exclude time slots where table capacity was reached. In terms of query what needs to be done is … -
images not displayed in heroku website despite being visible from s3
the image from s3 haS an enscription, while after opening image from the website there is no enscription.am not sure if this is the problem.how can i solve this or how can i get rid of the enscription AWS_ACCESS_KEY_ID="xxxxxxxxxx" AWS_SECRET_ACCESS_KEY="rrrrrrrrr" AWS_STORAGE_BUCKET_NAME="ddddddddd" SECRET_KEY="44444" AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'mysite/media' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' -
Django. Sort objects in a chain
I set up sorting related to the object manager. I have views.py def Objects(request): Objects_1 = car_type_1.objects.filter(manager_id='1', is_published=True) Objects_2 = car_type_2.objects.filter(manager_id='1', is_published=True) Objects_3 = car_type_3.objects.filter(manager_id='1', is_published=True) queryset_list = list(chain(Objects_1, Objects_2, Objects_3)) paginator = Paginator(queryset_list, 6) page = request.GET.get('page') paged_listings = paginator.get_page(page) context = {'listings': paged_listings} return render(request, 'template.html', context) As a result, I get a page with objects. Responsible manager id 1 for all objects. Everything is sorted correctly on the page. Showing manager id 1 objects. But, they are shown, one by one. First all from the group car_type_1, then the group car_type_2 and car_type_3. Question. How to make objects sorted by price from all groups? Thank! -
How to display the data inputted through TinyMCE in text but not HTML format?
I'm having problem in displaying data inputted through TinyMCE in text format. Instead, data with HTML format is returned. Some of my toolbar also were not displayed Followed the django-tinymce docs but it doesn't show how to change the format custom.js: tinymce.init({ selector: 'textarea', height: 500, theme: 'advanced', plugins: [ 'advlist autolink lists link image charmap print preview anchor textcolor', 'searchreplace visualblocks code fullscreen', 'insertdatetime media table paste code help wordcount' ], toolbar: 'undo redo | formatselect | bold italic backcolor | fontselect | fontsizeselect | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | help', content_css: [ '//fonts.googleapis.com/css?family=Lato:300,300i,400,400i', '//www.tiny.cloud/css/codepen.min.css' ] }); models.py: container_description = HTMLField() forms.py: container_description = forms.CharField(required=False, widget=TinyMCEWidget(attrs={'placeholder': 'Enter description'})) I want to display the datas in text not with html tags and also display my missing toolbar icons -
Django limit to one choise in foreing key
Need somehow to limit in models ForeignKey to one from available choices. It's my models : class CustomCompany(models.Model): name = models.CharField(max_length=30, default=None, unique=True ) teams = ListCharField( base_field=models.CharField(max_length=15), size=15, max_length=(15*16), default=["Owners"], unique=True ) class CustomUser(AbstractUser): company = models.ForeignKey(CustomCompany, on_delete=models.CASCADE, default='None', to_field='name', related_name='company' ) team = models.ForeignKey(CustomCompany, on_delete=models.CASCADE, default='Owners', to_field='teams', related_name='team', ) And from this, I have issue with "team" model. Cause to team model assignment all choices, but I want to select only one from available. Someone had this issue? Is it possible to limit this ForeignKey to only one choose? Thx -
How to create class based pagination in django on custom array
I am new to python and I am using django class based pagination with below code: class Demo(LoginRequiredMixin, ListView): model = users template_name = 'users_list.html' context_object_name = 'users' filterset_class = users paginate_by = 10 def get_queryset(self): // Code goes here // Result array after custom array creation : {25474: {'address__is_active': 1, 'id': 1, 'updated_by': '', 'count': 1}, 25475: {'address__is_active': 1, 'id': 2, 'count': 1, updated_by': ''}} return qs def get_context_data(self, **kwargs): context = super(Demo, self).get_context_data(**kwargs) context['filter_form'] = UserFilterForm(self.request.GET) page_query = '' for key,value in self.request.GET.items(): if key != 'page': page_query+='&'+key+'='+value context['page_query'] = page_query return context I am able to see pagination UI in my list but pagination is not working properly because I have make custom array like below: {25474: {'address__is_active': 1, 'id': 1, 'updated_by': '', 'count': 1}, 25475: {'address__is_active': 1, 'id': 2, 'count': 1, updated_by': ''}} Could anyone please assist how I can use class based pagination on custom array. -
Show function call trace in django/python debug logs
I need to figure out which statement is causing a particular SQL query. I have a debug log like: DEBUG .../env/lib/python3.6/site-packages/django/db/backends/utils.py 111 (0.000) SELECT "django_migrations"."app", "django_migrations"."name" FROM "django_migrations"; args=() But I cannot figure out which part of my code is causing the above debug statement. format: %(pathname)s is quite useless because I get a framework file name. If I print the entire trace I can figure out which part of my code is calling it. The trace that is printed when an exception is raised. Also, I am using django rest framework and I couldn't get django debug toolbar working. Also, I would prefer a full trace anyway. Currently I have: LOGGING = { 'formatters': { 'simple': { 'format': '%(levelname)s %(message)s \n\n' } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'simple', }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False, }, }, 'version': 1, 'disable_existing_loggers': False, } -
how to show amount in html page?
I have saved some random numbers in database and I am trying to fetch to show it in html page. but it is not showing me. I want to show each user their amount of money after they login. It is like a wallet where the amount will be saved for every user. I have saved that amount in database. views.py from decimal import Decimal def payment(request): total_amount = Payment.objects.all()['total_amount'] or Decimal('0.00') for field in total_amount: field.amount context = { 'total_amount': total_amount.amount } return render(request, 'index.html', context) models.py class Payment(models.Model): amount = models.DecimalField(max_digits=12, decimal_places=2) owner = models.ForeignKey(User, on_delete=models.CASCADE) HTML PAGE <li style="float: right;">Your Balance: Rs. {{total_amount}}</li> Images of database which contains content https://ibb.co/481nzqv https://ibb.co/B4M1NTk -
Adding an attribute to a django model, which did not exist previously
I created Django model for my application. It had some attributes, such as title, description, etc. Then I wanted to add 'slug' of the title, so from My Project it shall be my-project. But my already created model instances do not have these attributes. I tried just basically adding the attribute as, but it created something like: djangodbmodelsfieldscharfield. I also tried doing it with saving, but it only created this attribute to the newly added model instances class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField() # create p1 class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField() slug = slugify(title) # create p2 # p1.slug, p2.slug -> 'djangodbmodelsfieldscharfield' class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField() def save(self, *args, **kwargs): if not self.id: # Only set the slug when the object is created. self.slug = slugify(self.title) super(Project, self).save(*args, **kwargs) # create p3 # p1.slug, p2.slug -> AttributeError # p3.slug -> my-title-in-desired-form So my goal would be to create this attribute to every instance in the database. Is it possible, or how should I approach this problem? -
Use variable as dict key in django templates
I have two dict with the same keys. I use one dict to build table but I don't know how to get access to other dict. Example {% for key1, item1 for dict1.items %} {% for key2, item2 for item1.items %} <p>{{ item2.value }}</p> <p>there should be value from dict2</p> {% endfor %} {% endfor %} In python I can use dict2[key1][key2]["value"] but how do this with template? -
How to display two not associated models on one page via admin interface?
I have two models, not connected by ForeignKey. I would to display them on one page in admin interface, in the way like inlines in Django. I can't associate PostFile with Post, because uploaded medias should be available to every Post which was and will be created in future. I have no idea what I can do if inlines are unavailable. class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published') ) title = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique_for_date='publish_date', blank=True) author = models.ForeignKey(User, related_name='blog_posts', on_delete=models.CASCADE, blank=True) content = MarkdownxField() publish_date = models.DateTimeField(default=timezone.now) creation_date = models.DateTimeField(auto_now_add=True) last_update_date = models.DateField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') tags = models.ManyToManyField(Tag) objects = models.Manager() class Meta: ordering = [ '-publish_date' ] def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('blog:post_detail', args=[ self.publish_date.strftime('%Y'), self.publish_date.strftime('%m'), self.publish_date.strftime('%d'), self.slug ]) #https://github.com/neutronX/django-markdownx/issues/83 def formatted_markdown(self): return markdownify(self.content) class PostFile(models.Model): file_name = models.CharField(max_length=200, blank=True) file_object = models.FileField(upload_to='post_files/') file_upload_date = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): if not self.file_name: self.file_name = self.file_object.name super(PostFile, self).save(*args, **kwargs) def file_url(self): return self.file_object.url def __str__(self): return self.file_name I would to receive in output a Post model admin page, where on the bottom I have listed all PostFile … -
Where is django TEMPLATES
I need to find Django TEMPLATES location to add in a line under 'context_processors' om 'OPTIONS' I researched and found this which looks to be my problem solver, however I am unable to find the location of the document where I am supposed to input the details specified: django.core.exceptions.ImproperlyConfigured: Enable 'django.contrib.auth.context_processors.auth' The project only relies on Django as a plugin so I am in no means experienced with setting up Django. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ "django.contrib.auth.context_processors.auth", ] } } ] I can not find the 'TEMPLATES' document. -
KeyError at admin/users/myuser/ Error during template rendering
I can not view or edit users in Admin because of getting the next error. Another links and models in Admin are working fine. Link /admin/users/myuser/ works before I switched the database from SQLite to MySQL. But I do not know if the problem is with this or something else. KeyError at /admin/users/myuser/ Request Method: GET Request URL: http://127.0.0.1:8000/admin/users/myuser/ Django Version: 2.2.4 Exception Type: KeyError Exception Value: '0' Exception Location: C:\my_project\venv\lib\site-packages\django\contrib\admin\templatetags\admin_list.py in _boolean_icon, line 195 Python Version: 3.7.0 Error during template rendering In template C:\my_project\venv\lib\site-packages\django\contrib\admin\templates\admin\base.html, error at line 62 52 {% endblock %} 53 </div> 54 {% endif %} 55 {% endblock %} 56 {% block nav-global %}{% endblock %} 57 </div> 58 <!-- END Header --> 59 {% block breadcrumbs %} 60 <div class="breadcrumbs"> 61 <a href="{% url 'admin:index' %}">{% trans 'Home' %}</a> 62 {% if title %} &rsaquo; {{ title }}{% endif %} 63 </div> 64 {% endblock %} 65 {% endif %} 66 67 {% block messages %} 68 {% if messages %} 69 <ul class="messagelist">{% for message in messages %} 70 <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message|capfirst }}</li> 71 {% endfor %}</ul> 72 {% endif %} I totally do not understand where … -
How to fix 'Imported file has a wrong encoding: 'charmap' codec can't decode byte 0x9d in position 21221: character maps to' error?
I'm trying to import a csv file to my django project. Until now, the previous times I did this i never had a problem. However, all of a sudden I keep getting this error that says "Imported file has a wrong encoding: 'charmap' codec can't decode byte 0x9d in position 21221: character maps to" when i try to import the csv file in. I don't understand why I am getting the error this is what i keep getting. I am trying to import my excel file like this: and this is what my csv file looks like: -
unable to install django==1.8 with *fab setup_all*
i am trying to install all the packages with fab like 'fab setup_all' in unix 16.x. Except one django==1.8.19 root@bridge-All-Series:/home/bridge/ticketing/docker# fab setup_all Installing worker requirements... pip_compile_and_sync worker /var/www/ticketflap/apps/worker/requirements.txt [localhost] local: docker run --rm --volume $(pwd)/../logs:/var/log/ticketflap/ --volume $(pwd)/../logs/celery:/var/log/celery/ --volume $(pwd)/..:/var/www/ticketflap --volume $(pwd)/worker/supervisord.conf:/etc/supervisor/conf.d/supervisord.conf:ro --volume ticketflap-worker-virtualenv:/virtualenv --env DONT_SWITCH_USER=1 --network=ticketflap-dev --network-alias=worker.dev.ticketflap.net --interactive --tty ticketflap-worker /var/www/ticketflap/docker/base/_run.sh pip-compile --output-file /var/www/ticketflap/apps/worker/requirements.txt.compiled /var/www/ticketflap/apps/worker/requirements.txt No handlers could be found for logger "pip._vendor.cachecontrol.controller" Could not find a version that matches django==1.8.19,>=1.11,>=1.2,>=1.3,>=1.4,>=1.4.2,>=1.6,>=1.7,>=1.8 Tried: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.5.12, 1.6, 1.6, 1.6.1, 1.6.1, 1.6.2, 1.6.2, 1.6.3, 1.6.3, 1.6.4, 1.6.4, 1.6.5, 1.6.5, 1.6.6, 1.6.6, 1.6.7, 1.6.7, 1.6.8, 1.6.8, 1.6.9, 1.6.9, 1.6.10, 1.6.10, 1.6.11, 1.6.11, 1.7, 1.7, 1.7.1, 1.7.1, 1.7.2, 1.7.2, 1.7.3, 1.7.3, 1.7.4, 1.7.4, 1.7.5, 1.7.5, 1.7.6, 1.7.6, 1.7.7, 1.7.7, 1.7.8, 1.7.8, 1.7.9, 1.7.9, 1.7.10, 1.7.10, 1.7.11, 1.7.11, 1.8a1, 1.8b1, 1.8b2, 1.8rc1, 1.8, 1.8, 1.8.1, 1.8.1, 1.8.2, 1.8.2, 1.8.3, 1.8.3, 1.8.4, 1.8.4, 1.8.5, 1.8.5, 1.8.6, 1.8.6, 1.8.7, 1.8.7, 1.8.8, 1.8.8, 1.8.9, … -
Celery can't connect to local PostgreSQL from within Docker container
I have a Django-Celery-PostgreSQL project that should partially run in Docker. Having Redis and PostgreSQL servers running locally on the machine and using virtual environment for the project everything runs smoothly. But when I try to setup Docker instance Celery seems unable to connect to the Postgres database while Django can. When running project in Docker I put only Django and Celery in it and set network_mode: "host". Redis and Postgres remains on the local machine. Django server itself works flawlessly reading and writing data into the Postgres database, but when I try to run Celery tasks - I get following exception (thrown by django_celery_results): [2019-08-13 11:26:24,815: ERROR/MainProcess] Pool callback raised exception: OperationalError('could not connect to server: No such file or directory\n\tIs the server running locally and accepting\n\tconnections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?\n',) Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.6/site-packages/psycopg2/__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? The above …