Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do ı delete a row from database in django
I have remnants of old data ids in my database. So ı get an error in frontend. How do ı clear the empty rows? -
Cannot log in to django admin
Im currently a student and im building my project using gitpod. Ive been using this to create a django based project. For some reason, workspaces after 14 days get deleted on gitpod. I was able to get my code back as everything was saved on gitpod. All i had to do was download the apps again. The issue im having now is that my django accounts that i had created do not work anymore and trying to log in to Django Admin does not work either. Im thinking that all the accounts may got deleted. Is there anyway i could revert this. Im willing to provide any more detail if needed as i know i have not provided a lot. -
Django Annotate Worked with Postgres but now not working with Microsoft SQL Server
I was forced to switch databases from PgAdmin to Microsfot SQL Server. Now the following piece of code is not working and I can't figure what's wrong with it and why it doesn't work with Microsoft SQL Server. def total_queryset(item, selection): bill_amount = Labor.objects.values_list('item__name','selection__name') \ .filter(item__name=item, selection-_name=selection) I'm able to get the bill_amount but when I try to make the annotations it breaks. calculation= bill_amount.annotate(total_regular_amount=Round(Sum('total_bill_amount',filter=Q(paytype__id=1) | Q(paytype__id=2) | Q(paytype__id=5)))) print(calculation) File "D:\Users****\env\lib\site-packages\sql_server\pyodbc\base.py", line 553, in execute return self.cursor.execute(sql, params) pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near '::'. (102) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)") Why did my code work with pgAdmin and breaks with Microsoft SQL server? How can I make it work again? -
Django django-tables2 - Changing column ordering into descending
my goal is to reverse a column ordering from the default behavior. I would like to order table with the "number" column then reverse the order (newest->oldest). https://django-tables2.readthedocs.io/en/latest/pages/ordering.html After reading this documentation I tried using the below snippet in my tables.py class, nothing changed. name = tables.Column(order_by=("-number")) Main code. Snippet commented out. # models.py class Arrest(models.Model): number = models.IntegerField() charge = models.CharField(max_length=64) # views.py class ArrestListView(ExportMixin, tables.SingleTableView): table_class = ArrestTable model = Arrest template_name = 'data/view2.html' # tables.py class ArrestTable(tables.Table): # name = tables.Column(order_by=("-number")) export_formats = ['csv', 'xlsx'] class Meta: model = Arrest template_name = "django_tables2/bootstrap4.html" fields = ('number','charge',) -
Django - submitting form field dependant on permission
I'm looking for a way to control the users ability to submit a form field using permissions. We have 3 fields and the condition is that if any of the fields submitted are not in PERMISSION_KEY_MAP, we must return Permission denied. Note: User_1 has the permission to edit field_1 and field_2 only, via a group. I have tried this myself and i get my desired outcome. My question is should I be using PERMISSION_KEY_MAP to control the mapping of field and permission? Fields field_1 field_2 field_3 Views.py class SampleView(): def _get_permission_to_submit_field(self, field_keys): for field in field_keys: if not self.request.user.has_perm( settings.PERMISSION_KEY_MAP[field], ): return False return True def post(self, request, *args, **kwargs): field_keys = list(self.request.POST.keys()) if not self._get_permission_to_submit_field(field_keys): raise PermissionDenied return super().post(request, *args, **kwargs) PERMISSION_KEY_MAP PERMISSION_KEY_MAP = { 'field_1': 'app.edit_field_1', 'field_2': 'app.edit_field_2', } -
How can I storage data inputted on my localHost page (with Django) in .txt/.json files?
I tried this and Django still working, but the .json files don't appear on my rute. This is models.py (Django script) from django.db import models class Pizza(models.Model): """A pizza in a pizzeria""" text=models.CharField(max_length=250) date_added=models.DateTimeField(auto_now_add=True) filename='C:\\Users\\dayao\\OneDrive\\Escritorio\\PythonCrashCourse_Ex\\Pizzas\\pizzotas\\name.txt' def __str__(self): return self.text with open(filename,'w') as f: f.write(self.text) class Topping(models.Model): """Store n make a hook between Pizza an the toppings""" topic=models.ForeignKey(Pizza, on_delete=models.CASCADE) text=models.TextField() date_added=models.DateTimeField(auto_now_add=True) filename="C:\\Users\\dayao\\OneDrive\\Escritorio\\PythonCrashCourse_Ex\\Pizzas\\pizzotas\\pizza_toppings.txt" class Meta: verbose_name_plural ='Toppings' def __str__(self): if len(self.text)>=50: return f"{self.text[:50]}..." else: return self.text with open(filename,'w') as f: f.write(self.text) -
Best practice for looping python script in Django
So I have an app design question I'm hoping someone can help me with. I am building a network automation app for my company and currently have a python script which runs on a constant loop every 15 seconds to check on the health of a few hundred network devices across the company, essentially just pinging out. As an FYI, the app is in a docker container and being deployed to an azure web app. The goal is to build a django app that interfaces with all this information so there is a nice little web front end to view the state of the network and run commands from. The problem is, when trying to get the looping function to be called from 'views.py' for my python script it just takes over the server, so now the website goes down while it's looping. I can't seem to run the forever looping python script and keep the django web server running at the same time. Is there a better way to do this with Django and a constantly looping python script? Should I take this particular script out of the django app entirely and host it separate in azure some how … -
Django Rest Framework - How to serialize reverse relation field
I have a CustomerSerializer which uses a reverse foreign key field images to return all associated Image objects. class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = ('id', 'name', 'images') read_only_fields = ('id',) This is what I get from the response: [ { 'id': 1, 'name': 'John Doe', 'images': [ 1, 2, 3, 4, ... ] } ... ] Question: Instead of just showing images as a list of ids, how can I show a different property i.e. name? The desired result would be: [ { 'id': 1, 'name': 'John Doe', 'images': [ 'foo.jpg', 'bar.jpg', 'foobar.jpg', 'lorem.jpg', ... ] } ... ] My first attempt - I replaced the reverse foreign key images with image_names from the SerializerMethodField() in order to select the field name, but I get a null value. class CustomerSerializer(serializers.ModelSerializer): image_names = serializers.SerializerMethodField() def get_image_names(self, obj): return obj.images.name class Meta: model = Customer fields = ('id', 'name', 'image_names') read_only_fields = ('id',) Additional Info Example models: class Customer(models.Model): name = models.CharField() class Image(models.Model): name = models.CharField() customer = models.ForeignKey( Customer, related_name='images', on_delete=models.CASCADE) Please let me know if anything is unclear and I will update the question. Thank you. -
Im trying to get an id for a comment for update, delete, and to count Upvotes and downvotes
Im trying to get an id for a comment for update, delete, and to count Upvotes and downvotes, everything was working fine until I began using Django-mptt in order to have reply-able comments. Now Im trying to call the comments by node.id and it isn't working. Does anyone have any advice or know if this is every possible (without a ton of complex code). Here is my code urls.py path('<int:year>/<int:month>/<int:day>/<slug:post>/<node_id>/Upvote',views.Upvote_comment, name='Upvote_comment'), path('<int:year>/<int:month>/<int:day>/<slug:post>/<comment_id>/Downvote',views.Downvote_comment, name='Downvote_comment'), views.py def Upvote_comment(request, year, month, day, post, comment_id = None): post = get_object_or_404(Post , slug=post, status='cleared',publish__year=year,publish__month=month,publish__day=day) comments = post.comments.filter(active=True) comment = Comment.objects.get(id=comment_id) comment_form = CommentForm(data=request.POST) user = request.user if user in comment.Upvote.all(): comment.Upvote.remove(user) else: comment.Upvote.add(user) if user in comment.Downvote.all(): comment.Downvote.remove(user) comment.save(force_update=True) comment_form = CommentForm() messages.success(request, f'Comment has been Upvoted!') return HttpResponseRedirect( post.get_absolute_url() ) def Downvote_comment(request, year, month, day, post, comment_id = None ): post = get_object_or_404(Post , slug=post, status='cleared',publish__year=year,publish__month=month,publish__day=day) comments = post.comments.filter(active=True) comment = Comment.objects.get(id=comment_id) comment_form = CommentForm(data=request.POST) user = request.user if user in comment.Downvote.all(): comment.Downvote.remove(user) else: comment.Downvote.add(user) if user in comment.Upvote.all(): comment.Upvote.remove(user) comment.save(force_update=True) comment_form = CommentForm() messages.success(request, f'Comment has been Downvoted!') return HttpResponseRedirect( post.get_absolute_url() ) models.py class Comment(MPTTModel): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') parent = TreeForeignKey('self', on_delete=models.SET_NULL,null=True, blank=True, related_name='children') name = models.ForeignKey(User, on_delete=models.SET_NULL,null=True) body = models.TextField() … -
Do I need background tasks in django channels or can I just call functions inside the consumer?
I've just started learning how to use Django Channels - I've followed the tutorial on the docs and a read a bit online. My use case is fairly simple, I'm working with the Web MIDI API and I want to send MIDI to the server and have it represented in JSON, so that the client can query it later. I was doing this over HTTP, but the MIDI data was getting sent too fast and too often for HTTP to keep up. Once the data is received by the consumer, am I OK to just call a python function on it to store it in a dictionary directly inside the consumer, I've got functions already written that could do this. Is this an acceptable way to do it, or do I need to use these Worker or Background processes I've read about. The functions are quite simple, so I figured this method would be OK, but is there any reason why I should avoid this? -
Django code throws render to response error even though I'm not using it?
I get this error: ImportError: cannot import name 'render_to_response' from 'django.shortcuts' (C:\Python34\lib\site-packages\django\shortcuts.py) But my code looks like this: from django.shortcuts import render, redirect, render_to_response def proratesearch(request): context = { 'queryset': ers, 'ers2': ers2, } return render(request, 'conversion/query.html', context) What am I missing. Everything is like what people online say. -
How do I resolve a raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch error in Django 3.1 on Mac OS Catalina?
I'm currently going through "Python Crash Course" by Eric Matthes. I'm on Chapter 19 trying to add a page to a web app where users can enter data. If working correctly, the user can write an entry about a topic that he/she is learning about. I wrote the code exactly how the book told me. Sadly I keep getting the following error: File "/Users/jakeziegelbein/Desktop/crashCoursePython/learning_log/11_env/lib/python3.8/site-packages/django/urls/resolvers.py", line 685, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'learning_logs/new_entry' not found. 'learning_logs/new_entry' is not a valid view function or pattern name. Here are the files of code: views.py from django.shortcuts import render, redirect from .models import Topic, Entry from .forms import TopicForm, EntryForm def index(request): """The home page for Learning Log.""" return render(request, 'learning_logs/index.html') def topics(request): """Show all topics.""" topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) def topic(request, topic_id): """Show a single topic and all its entries.""" topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) def new_topic(request): """Add a new topic.""" if request.method != 'POST': # No data submitted; create a blank form. form = TopicForm() else: # POST data submitted; process data. form = TopicForm(data=request.POST) if form.is_valid(): form.save() return redirect('learning_logs:topics') # Display … -
Django MultiValueKeyDictError while saving data for a multistep form
class multi_form(View): model=Customer template_name='index.html' def get(self, request): return render(request, 'customer/index.html') def post(self,request): if(request.method!="POST"): return HttpResponseRedirect(reverse('')) else: first_name=request.POST.get("fname") last_name=request.POST.get("lname") personal_email=request.POST.get("Pid") official_email=request.POST.get("Oid") current_address=request.POST.get("Cadd") permanent_address=request.POST.get("Padd") pan_card_number=request.POST.get("Pan") aadhar_card_number=request.POST.get("Aadhar") loan_amount=request.POST.get("LAmount") request.session['fname']=first_name request.session['lname']=last_name request.session['Pid']=personal_email request.session['Oid']=official_email request.session['Cadd']=current_address request.session['Padd']=permanent_address request.session['Pan']=pan_card_number request.session['Aadhar']=aadhar_card_number request.session['Lamount']=loan_amount personal_photo=request.FILES['PhotoAttachment'] bank_statement=request.FILES['BankAttachment'] salary_slip=request.FILES['SalaryAttachment'] pan_card=request.FILES['PanAttachment'] aadhar_card=request.FILES['AadharAttachment'] try: CustomerForm1=CustomerInfo(first_name=first_name, last_name=last_name, personal_email= personal_email, official_email=official_email, current_address=current_address, permanent_address=permanent_address, pan_card_number=pan_card_number, aadhar_card_number=aadhar_card_number, loan_amount=loan_amount) CustomerForm2=Customer(first_name=first_name, last_name=last_name, personal_email= personal_email, official_email=official_email, current_address=current_address, permanent_address=permanent_address, pan_card_number=pan_card_number, aadhar_card_number=aadhar_card_number, loan_amount=loan_amount, personal_photo=personal_photo, bank_statement=bank_statement, salary_slip=salary_slip, pan_card=pan_card, aadhar_card=aadhar_card) CustomerForm1.save() CustomerForm2.save() messages.success(request, "Your Response has been recorded") return render(request, 'customer/index.html') except: return render(request, 'customer/index.html') So, I was trying to save fields of a multi-step form. Upon submission after only the first step and skipping the second step altogether I am displayed this error. MultiValueDictKeyError at / ('PhotoAttachment', None) How do I resolve this and save data of first of this form ie. CustomerForm1. I want to save data in form fields of both the forms although they contain duplicate fields Note: If I remove the submit button in first step and CustomerForm1 from views.py then I don't get this error implying forms works fine otherwise. -
How to hide/exclude certain fields of foreign key in graphene_django?
I have read about how to exclude (hide) certain fields in django and graphene_django in these Links: graphql-python repository Why does my excluded field still appear in this Django form? etc. Imagine that we have the following Post model which has foreign key to the User model. apps/posts/models.py from django.db import models from apps.users.models import User class Post(models.Model): author = models.ForeignKey( User, on_delete=models.CASCADE, null=False ) created_at = models.DateTimeField( auto_now_add=True, ) title = models.TextField( null=False, max_length=100, ) content = models.TextField( null=False, ) def __str__(self): return self.title apps/users/models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser, models.Model): phone_no = models.CharField( blank=True, null=True, default="", max_length=10, verbose_name="Phone Number", ) avatar = models.ImageField( null=True, upload_to='static', ) USERNAME_FIELD = "username" EMAIL_FIELD = "email" def __str__(self): return self.username I tried the following but it faced to an error: apps/posts/schema.py import graphene from graphene import Mutation, InputObjectType, ObjectType from graphene_django.types import DjangoObjectType from .models import Post class PostType(DjangoObjectType): class Meta: model = Post exclude_fields = [ 'created_at', #it worked 'author.password', #the way I tried to hide the foreign key field ] class Query(ObjectType): posts = graphene.List( PostType ) def resolve_posts(self, info): #TODO: pagination return Post.objects.all() How can I hide certain fields of it (like author's password … -
KeyError 'password' for Django User Serializer(was working, just transferred to Postgres and now not working?)
I am not sure why it's not POST-ing new Users, since it was working right before I transferred by DB to Postgres (also not sure if that could even affect this?). I originally had CharField in my Models, but it was throwing an error, regarding the Max_Character length(even though it was under 50). So, I currently have my models as Text_Field. Anything helps! Model: from django.contrib.auth.models import User, AbstractUser class User(AbstractUser): username=models.TextField(unique=True) email=models.TextField(unique=True) password=models.TextField def __str__(self): return self.username View: class UserView(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (permissions.AllowAny,) Serializer: from rest_framework import serializers from . import models from django.contrib.auth.hashers import make_password class UserSerializer(serializers.ModelSerializer): class Meta: model = models.User fields = ('id', 'username', 'email', 'password', 'favorites', 'reviews') depth = 2 def create(self, validated_data): user = models.User( email = validated_data['email'], username = validated_data['username'], password = make_password(validated_data['password']) ) user.save() return user -
can we apply django ordering on a field of SerializerMethodField
I have a field like matchCount= serializers.SerializerMethodField('get_match') def get_match(self, obj): likes = obj.post.count #here will be logic of almost 120 lines so cant use annotate* return likes / time if time > 0 else likes Now I want to order on basis of this filed matchCount. what can be best solution in this case ? until now I found other developers are using annotate etc but as this logic is dynamic and will count match on run time , what can I do to sort on basis of this field ? -
How to Login_required for Comments inside a view, Django
So i have this post_detail view, and i want to apply login_required but only for the comments, so people is able to enter the detail_post view and watch but not to Comment. I should login_required a part of the view or may be the Comment model? I tried to login_required the model but didn't work, i get an error. view: def post_detail(request, post_slug): post = get_object_or_404(Post, slug=post_slug, status='published',) # List of active comments for this post comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': # A comment was posted comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the comment to the database new_comment.save() else: comment_form = CommentForm() # List of similar posts post_tags_ids = post.tags.values_list('id', flat=True) similar_posts = Post.published.filter(tags__in=post_tags_ids)\ .exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags'))\ .order_by('-same_tags','-publish')[:4] Model: class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __str__(self): return f'Comment by {self.name} on {self.post}' -
Recurrent objects in Django
I need some help in order to manage adding a new feature on my website created in Django. I made a spendings tracker website where a user can add as many personalized spendings and budgets he/she likes but I have a problem. I want to make a user to have the possibility to create recurrent spendings and budgets. For example if a user creates a spending right now and he select to be recurrent the website should some how add in the next month the same spending at the same date. If I create now a new spending, next month on 20th September the website should add this automatically. Some help please. Spending object in models.py file: class Spending(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) category = models.CharField(max_length=100) amount = models.FloatField() date_created = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.user.username}\'s {self.name}' Function that create a spending in views.py file: @login_required def create_spending(request): Spending.objects.create(user=request.user, name=request.POST['spending_name'], category=request.POST['spending_category'], amount=request.POST['spending_amount']) return redirect('dashboard') I know that I need to add a new boolean row to table Spending and some if cases in this function but I don't have the exact idea and I need some help please. -
Django forcing logout on form submission
I have a Django application being used by multiple users. Users have told me that sometimes they will submit a form and it will redirect them to the login view (logs them out). When they log back in, the form was successfully submitted, but it is a strange and annoying bug. I have tried to duplicate this, but I can't seem to reproduce this behavior. Sorry for the lack of information here, but I am hoping someone has either seen this before, or can point me in the right direction for de-bugging an error like this. Thanks in advance! A little more info that may be useful: -I am using Django 3.1, and am running this on a local ubuntu Virtual machine within a corporate network. The VM is using postgres, NGINX, gunicorn to serve the application. -
Django Foreignkey in MongoDB's EmbeddedField
I am using Djongo engine for MongoDB in my Django project. I have two tables # app/models.py # My Main Table class Questions(models.Model): questionId = models.UUIDField(default=uuid.uuid4, editable=True, unique=True) question = models.TextField() answer = models.EmbeddedField( model_container=Answers ) date = models.DateTimeField(auto_now_add=True, blank=True) User = models.ForeignKey(UserDetailTable,on_delete=models.CASCADE,related_name='userinfo') and # app/models.py # This table needs to be Embedded in Questions Table class Answers(models.Model): answerId = models.UUIDField(default=uuid.uuid4, editable=True, unique=True) answer = models.TextField() date = models.DateTimeField(auto_now_add=True) User = models.ForeignKey(UserDetailTable,on_delete=models.CASCADE) class Meta: abstract = True I want to embed Answers in the Questions table. But I am getting this error django.core.exceptions.ValidationError: ['Field "App.Answers.User" of model container:"<class \'App.models.Answers\'>" cannot be of type "<class \'django.db.models.fields.related.ForeignKey\'>"'] I know this error is because I am using User = models.ForeignKey(UserDetailTable,on_delete=models.CASCADE) in Answers which is itself an EmbeddedField on Questions. How Can I solve this error? As there will be multiple answers from different users on the same question and with ForeignKey it will be simple to show the user's info along with his/her answer. I have also looked djongo's docs but couldn't find anything. Any help would be appreciated. -
How do i take care of these issue with django channels?
'''python manage.py runserver''' Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/abbracx/Documents/virtualenv/pycon/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/abbracx/Documents/virtualenv/pycon/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/abbracx/Documents/virtualenv/pycon/lib/python3.7/site-packages/django/core/management/__init__.py", line 244, in fetch_command klass = load_command_class(app_name, subcommand) File "/home/abbracx/Documents/virtualenv/pycon/lib/python3.7/site-packages/django/core/management/__init__.py", line 38, in load_command_class return module.Command() **AttributeError: module 'channels.management.commands.runserver' has no attribute 'Command'** Please these is the error i have been battling with when i include channels at the top of my install apps. when included bellow the install apps it is the django server that runs instead of Asgi channels server. Why? -
How to group by and count in a subquery with Django's ORM?
I have a table map(id, key, value) from where I would like to select the keys that have same value. In SQL I could do SELECT key FROM map WHERE value IN (SELECT value FROM map GROUP BY value HAVING COUNT(*) > 1); I tried to translate it into Django's ORM style from django.db.models import Count Map.objects.filter(value__in=Map.objects.values('value').annotate(count=Count('value')).filter(count__gt=1)).values('key') But it fails because the subquery in the __in filter returns two columns, the selected value column and a column for the count: SELECT "map"."key" FROM "map" WHERE "map"."value" IN (SELECT U0."value", COUNT(U0."value") AS "count" FROM "map" U0 GROUP BY U0."value" HAVING COUNT(U0."value") > 1) How can I remove the uneeded count column from that subquery? -
Unable to write Dynamic meta tag in django
Hello all i want to print dynamic meta tag values in django. i have _header.html as partial file which is common to all the pages. In that header file i want to add meta tags. The header file is included in base.html and base extends all the other pages i want different meta tags for different pages. the below code is for _header.html file {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> "here i want dynamic meta tags" <title>Random Blog</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link rel="stylesheet" href="{% static 'css/main.css' %}"> </head> -
django.db.utils.OperationalError: could not connect to server: Connection refused
I have 3 docker containers web(django) , nginx, db(postgresql) When I run the following command docker-compose -f docker-compose.prod.yml exec web python manage.py migrate --noinput The exact error is: django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Address not available Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? docker-compose.prod.yml version: '3.7' services: db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.envs/.db web: build: context: ./tubscout dockerfile: Dockerfile.prod command: gunicorn hello_django.wsgi:application --bind 0.0.0.0:8000 volumes: - .static_volume:/home/app/web/staticfiles expose: - 8000 env_file: - ./.envs/.prod depends_on: - db nginx: build: ./nginx volumes: - .static_volume:/home/app/web/staticfiles ports: - 1337:80 depends_on: - web volumes: postgres_data: static_volume: Dockerfile.prod ########### # BUILDER # ########### # pull official base image FROM python:3.8.3-alpine as builder # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip wheel --no-cache-dir --no-deps -w /usr/src/app/wheels -r requirements.txt ######### # FINAL # ######### # pull official base … -
How to disable VSCode's Explorer opening directory of opened file?
I'm using VSCode (1.47.3) on Ubuntu Bionic with the MS Python Extension Pack. I really want to disable the feature whereby Explorer decides to open the parent folder of the file I have just opened and allow me the control to open this folder manually (if I want to, which I rarely do). Scenario: I have some app-specific .py files open and Explorer shows my app's folder: "app" - all good. I navigate to a DJango dependency e.g. models.Manager when suddenly Explorer automatically shows the folder: site-packages/django/db/models - which I don't to happen. I didn't ask it to happen. In order to go back to the context of my top-level "app" folder, I have to scroll 100km back to where I was! I just want Explorer to stay in my "app" directory, regardless of what other files I may open. I only opened the DJango dependency for context/reference. I have no intention of editing that file (obviously) so I don't need any other DJango context. If I want to open a parent directory of a random file I've opened, I'll do that myself. How can I disable VSCode from doing this? Is there some JSON config I can modify?