Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django annotate with
How can i use average_ndvi and field_count variables into annotate, i need change 0.14 to F"average_ndvi", 5 to F"field_count". commune = ( Commune.objects.annotate( year=SearchVector("field__fieldattribute__date__year"), month=SearchVector(Cast("field__fieldattribute__date__month", CharField())), size=Sum(F("field__fieldattribute__planted_area")), average_ndvi=Avg(F("field__fieldattribute__ndvi")), field_count=Count("field"), standart_deviation=Sum( ((F("field__fieldattribute__ndvi") - 0.14) ** 2) / 5, output_field=FloatField(), ), ) .filter(year=year, month=str(month)) .only("id", "name") ) -
How to order a combined queryset by annotated field?
The weight for our objects is composed of 2 fields. One field is the weight unit (kilogram, tonne and pound) and the other field is the weight (number). I have tried making a queryset which annotates all the weights into one universal unit field. The problem is that once I order_by that annotated (unit) field, it still orders by largest number and not by largest weight. For example 100kg is less than 50t, but the ordering system just sorts by the largest number. This is the code inside the filters.py: ` class AircraftFilter(FilterSet): tail_number = CharFilter(field_name="tail_number", lookup_expr="startswith") by_weight = CharFilter(method="filter_by_weight") class Meta: model = Aircraft fields = ("tail_number", "by_weight") def filter_by_weight(self, qs: QuerySet, value, *args, **kwargs): if value != None: qs = ( qs.filter(max_takeoff_weight_unit=2).annotate( mtw_lb=F("max_takeoff_weight") * 2200 ) | qs.filter(max_takeoff_weight_unit=1).annotate( mtw_lb=F("max_takeoff_weight") * 2.2 ) | qs.filter(max_takeoff_weight_unit=3).annotate( mtw_lb=F("max_takeoff_weight") ) ) qs = qs.order_by("mtw_lb") return qs ` The query: `qs = (Aircraft.objects.all().filter(max_takeoff_weight_unit=2).annotate(mtw_lb=F("max_takeoff_weight")*2200) | Aircraft.objects.all().filter(max_takeoff_weight_unit=1).annotate(mtw_lb=F("max_takeoff_weight") * 2.2) | Aircraft.objects.all().filter(max_takeoff_weight_unit=3).annotate(mtw_lb=F("max_takeoff_weight"))).order_by("mtw_lb")` and the output: `<IsActiveModelQuerySet [ID: 5 | weight: 0.05 - (t) , ID: 4 | weight: 0.20 - (t) , ID: 8 | weight: 2.00 - (t) , ID: 7 | weight: 50.00 - (lbs) , ID: 6 | weight: 100.00 - (kg) ]>` -
i get an error while i use 'is none' in DJANGO [closed]
If there is no row in the Duyuru table registered to the database, I want the h5 tag to be displayed on the screen. But the h5 tag does not appear on the screen. This is my html file: (https://i.stack.imgur.com/K6Pte.png) and this is views: (https://i.stack.imgur.com/V7OWg.png) Can you help me? -
I try to be able to load an image in the django admin, but I can't see it when I click
I don't know how to solve it. It's really frustrating. If you managed to help, I would be very grateful. settings: ``` ``` STATIC_URL = '/static/' MEDIA_URL='Proyectoweb/media/' MEDIA_ROOT=BASE_DIR / 'Proyecto/media' ``` ``` url: ``` ``` from django.urls import path from ProyectoApp import views from django.conf import settings from django.conf.urls.static import static ``` ``` urlpatterns+=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ``` ``` models: ``` from django.db import models # Create your models here. class Servicio(models.Model): titulo=models.CharField(max_length=50) contenido=models.CharField(max_length=50) imagen=models.ImageField(upload_to='servicios') created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now_add=True) class Meta: verbose_name='servicio' verbose_name_plural='servicios' def __str__(self): return self.titulo ``` admin: ``` from django.contrib import admin from .models import Servicio # Register your models here. class ServicioAdmin(admin.ModelAdmin): readonly_fields=('created', 'updated') admin.site.register(Servicio, ServicioAdmin) ``` For some reason, this page asks me for more details, when I think I have already given enough. I try to be able to load an image in the django admin, but I can't see it when I click.... -
How can I set a variable width in my CSS or Tailwind class?
I am getting the width from my Django View, but I do not know if I can make it variable in CSS. I’ve been trying to set the Tailwind, but I imagine that it is not the right thing to do: {% for movie in movies %} <div id="bar" class="w-[{movie.score}]" style="transition: 1s"> {{movie.score}} </div> {% endfor %} However, I am also trying to do it directly in CSS, but the style does not accept a variable as: {% for movie in movies %} <div id="bar" style="transition: 1s; width: {{movie.score}}; "> {{movie.score}} </div> {% endfor %} I’ve also tried to change it using JavaScript, but I have to select multiple elements because there will be various bars. So, this just not worked. I receive messages that the movies were declared before if I use let, but using var nothing changes. def get_context_data(self, **kwargs): context = super(MoviesRatePage, self).get_context_data(**kwargs) context['movies'] = movies return context {% block javascript %} <script type="text/javascript"> var movies = "{{movies}}"; for (let i = 0; i < movies.length; i++) { document.querySelectorAll("#bar")[i].style.width = `${movies[i].score}%`; } </script> {% endblock javascript %} Thus, I want to make the bar width the same as the movie’s score. -
Is there a way to type the elements of the dictionary that is returned by a serializer?
I use the serializers that come from django-rest-framework to validate many of the request on my app end. I have found thhat is very useful to get the objects on the serializer, but the dictionary the serializer returns with the serializer.validated_data is not typed This is how I perform the validation: On views.py def post(self, request): body_serializer = ExampleSerializer(data=request.data) body_serializer.is_valid(raise_exception=True) body_data = body_serializer.validated_data # to get the object object_one = body_data['object_one'] On the serializers.py class ExampleSerializer(serializers.Serializer): field_one = serializers.CharField(required=True, help_text='field_one') field_two = serializers.CharField(required=True, help_text='field_two') field_three = serializers.CharField(required=True, help_text='field_three') def validate(self, attrs): object_one:ObjectOne = ObjectExample.objects.get(field=field_one) attrs['object_one'] = object_one return attrs Is there a way I can type the return dictionary? -
How to import my views from user in my urls.py file
I am using Pycharm for my Django Project. It says that it is a unresolved reference. In Startup/urls.py I have following code: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.contrib.auth import views as auth_views from users import views as user_views urlpatterns = [ path('admin/', admin.site.urls), path('vereinsapp/', include('vereinsapp.urls')), path('', include('vereinsapp.urls')), #Users path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), path('delete_user/', user_views.deleteuser, name='delete_user'), path('profile_confirm_delete/', user_views.profile_confirm_delete, name='profile_confirm_delete'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I also tried startup.users but then I get the error Message "no module named..": -
bootstrap alert-dismissable not working in django
here is my html code <div class="msg"> {% if messages %} {% for message in messages %} <div class="alert alert-dismissible alert-success"> <button type="button" class="close" data-dismiss="alert"> × </button> <strong>{{message}}</strong> </div> {% endfor %} {% endif %} </div> message is showing after form submission, but x button not working of collapse, how to resolve it, please help me. -
Django Model form is showing invalid with initialized values and file
I have a model like this: ` class Cohortpdfs(models.Model): id = models.AutoField(primary_key=True,editable=True) title= models.CharField(max_length=200,validators=[MaxLengthValidator(100)]) content=models.FileField() cohort_id=models.ForeignKey(Cohort,on_delete=models.CASCADE,default=0,db_constraint=False) ` I want to initialize and save data from views. views.py: ` if requests.method == 'POST': initialvalue={ 'cohort_id':id, 'title':requests.POST.get('title'), 'content':requests.FILES['content'], } if contentform.is_valid(): print("form valid") else: print("FORM ERROR") ` Forms.py class CohortpdfsForm(forms.ModelForm): class Meta: model = Cohortpdfs fields = [ "title","content","cohort_id", ] widgets={ 'title' : forms.TextInput(attrs={'class': 'form-control','max_length':20}), 'content': forms.FileInput(attrs={'class': 'form-control'}), 'cohort_id': forms.TextInput(attrs={'type': 'hidden'}), } ` This is showing my form is not valid. How can I initialize the form with uploaded file(PDF) and save it into the model database. This is showing my form is not valid. How can I initialize the form with uploaded file(PDF) and save it into the model database. -
What is the correct way to end a Watchdog observer without a sleep loop?
I am relatively new to python and programing in general. This is my first question on Stack Overflow so thank you for any responses in advance! My question is this. I have a Python web application that is using the django framework. A new feature of that web application requires the use of a locally installed command line tool on the server, that tool dumps an output file to a directory previously created. I want to watch that directory and when a file is created in it that ends in .json call a parsing function. Enter the Watchdog library. I have followed a number of tutorials/checked on here for how to correctly setup an observer. They all have the observer being started and then immediately going into a time.sleep(1) loop while waiting for something to happen. However since this is a django webapp I don't want to sit and wait while the watchdog observer is looking for the file to be created. Here is an example code from Geeks for Geeks: if __name__ == "__main__": # Set the format for logging info logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S') # Set format for displaying path path = sys.argv[1] if len(sys.argv) > … -
No module named 'manage_db.tools'; 'manage_db' is not a package
I have a Package that works with the Django Framework. I'm trying to import two packages that are outside the Django package, so that I can work with their Python files. In order for Django to recognize the packages, I added the following lines to the Django settings file: manage_db = os.path.join(BASE_DIR.parent.parent, "manage_db") g = os.path.join(BASE_DIR.parent.parent, "g") sys.path.append(manage_db) sys.path.append(g) And in the views.py file I wrote: from g.globals import Globals from manage_db.tools import Tools The error I got is: For the first package - No module named 'manage_db.tools'; 'manage_db' is not a package For the second package - No module named 'g' . I read from people who had similar problems that they changed the names of the directories, and it worked for them, I tried, and I change the name to "g", but it didn't work. Note: I created the packages, they are not packs that require pip install Thanks in advance to all the helpers. -
How to receive the value of an html attribute through the submitted form DJANGO
How can I get the value of the "data" attribute of this select's options? With request.POST.get() <select name="installments" id="installments"> <option value="1" data="239.8">239,80</option> <option value="2" data="125.31">125,31</option> <option value="3" data="84.76">84,76</option> <option value="4" data="64.5">64,50</option> <option value="5" data="52.35">52,35</option> <option value="6" data="44.25">44,25</option> </select> I tried this: installments = request.POST.get('installments.attrs=["data"]') -
create new objects from list only if its not in django database
I am having a list of python objects. suppose py_objs_list = [...data...] Model is Card I want to create a new object in django database only if database already dont have object My solution is to do objects.all() on my Card and run a for loop on py_objs_list and check if py_obj in objects.all(). If not present im taking that py_obj into seperate list. Finally creating objects using bulk_create py_objs_list = [...data...] cards = list(Card.objects.al()) <--- i know db hits here ---> emails = [card.email for card in cards] <--- does db hit here also everytime in a loop ---> empty_list = [] for py_obj in py_objs_list: if py_obj[some_data] not in emails: empty_list.append(py_obj) ---bulk_create--- Is this the best way to tackle this problem? pls tell me if not (want the best one). thnks:) Now my doubt is does db hit everytime in list comprehension as mentioned above my solution for this problem -
'Category' object is not subscriptable Django
I am learning Django. I wrote a simple model and some views method in Django rest framework so that I can modify some particular attributes when needed to all the records that need that. Here is the model: from django.db import models class Category(models.Model): name = models.CharField(max_length=255) isActive = models.BooleanField(default=True) def __str__(self): return self.name Then, I created this view to modify the isActive session when I call it: class CategoriesChangeActiveView(views.APIView): def post(self, request, format=None): try: categories = request.data.get('categories') for category in categories: category = Category.objects.get(id=category['id']) category.isActive = category['isActive'] category.save() except Exception as e: return Response({'error': 'Bad request'}, status=status.HTTP_400_BAD_REQUEST) return Response({'success': 'Active changed'}, status=status.HTTP_200_OK) Even when the format of my request is correct ( I debugged each line ) when it comes to the line category.isActive = category['isActive']it throws the error that'Category' object is not subscriptable`. I don't know why or how to fix it. I saw in the official documentation, on older StackOverflow questions that this is doable, but I don't understand why I can't. Can someone please suggest what I am doing wrong? Thank you -
How to improve search faster inside json file?
Here I have a sample JSON file with size more than 10MB(which will increase eventually). I have a python function which will try to match the entire json object from the json file and if matches it returns the next json object. This is my current implemention.It does the work but not sure it is the right way. I want some suggestions so that I can make this function much faster and scalable since this function is going to be used in several rest apis. { "all_checks": [ { "key":"value", "key2": { "key": "val" } }, { "key":"value", "key2": { "key": "val" } }, { "key":"value", "key2": { "key": "val" } }, ] } python func import os import json from django.conf import settings def get_value(value): with open(os.path.join(settings.BASE_DIR, "my_json.json")) as file: data = json.load(file) # for i,v in enumerate(data["all_checks"]): # if json.dumps(value) == json.dumps(v): # return data["all_checks"][i + 1] ls = [data["all_checks"][i + 1] for i, v in enumerate(data["all_checks"]) \ if json.dumps(value) == json.dumps(v)] return dict(ls[0]) This function will be used in several apis -
502 bad gateway error pointing django model.py to other database
i'v setup a wagtail website. I altered models.py from my home-page model. In this models.py i try to acces a database running on another external server. Before i altered models.py the website was running fine, but after altering models.py i get a 502 bad-gateway error. I'm using Nging and gunicorn to serve the website. I followed this tutorial to set it up: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-22-04 I noticed this error in gunicorn: Dec 05 22:36:50 ip-172-31-30-62 gunicorn[1853]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> Dec 05 22:36:50 ip-172-31-30-62 systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Dec 05 22:36:50 ip-172-31-30-62 systemd[1]: gunicorn.service: Start request repeated too quickly. Dec 05 22:36:50 ip-172-31-30-62 systemd[1]: gunicorn.service: Failed with result 'exit-code'. This is my models.py for accessing the external database. (With help of @Richard Allen) class CasPage(Page): .... @property def plot(self): try: conn = psycopg2.connect( database="xxxx", user="xxxx", password="xxxx", host="xxxxxxxxxxxxx", port=xxxxx, ) cursor = conn.cursor() strquery = (f'''SELECT t.datum, t.grwaarde - LAG(t.grwaarde,1) OVER (ORDER BY datum) AS gebruiktgas FROM XXX''') data = pd.read_sql(strquery, conn) fig1 = go.Figure( data = data, layout=go.Layout( title="Gas-verbruik", yaxis_title="aantal M3") ) return plotly.plot(fig1, output_type='div', include_plotlyjs=False) except Exception as e: print(f"{type(e).__name__} at line {e.__traceback__.tb_lineno} of {__file__}: {e}") return None I can acces the external database (no … -
how to call kedro pipline or nodes in Django framework
I have to call Kedro nodes or pipelines in Django API, and need to use Kedro pipelines or nodes output as input in Django API. Not getting any solution. Please suggest some solution for this. How to call Kedro pipeline or nodes in Django APIs? -
how to create a time limit object in django
In this project I create some objects and I want to filter only objects that are created 120 seconds ago . I tried this Line : Model.objects.filter(start_time__gte=Now() - timedelta(minutes=2) , user = request.user , code = data['code']) But It does not work for me . any other solution? (and django timezone is set on Asia/china) -
DJANGO - Unable to refresh my edit profile page
Good day, I am making a Django application, I want to call my data that the user signs up with and to display the information they submitted as: Name Email Then I want to be able to change that data and then I want to save it, and reload back into the dashboard, but when I am updating my 'update_profile.html' the info is not updating, I can; add form data and change it What am I doing wrong? My code below: views.py from django.shortcuts import render, redirect, HttpResponse from django.contrib import messages, auth from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from contacts.models import Contact def register(request): if request.method == 'POST': # Get form values first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] password2 = request.POST['password2'] # Check if passwords match if password == password2: # Check username if User.objects.filter(username=username).exists(): messages.error(request, 'That username is taken') return redirect('register') else: if User.objects.filter(email=email).exists(): messages.error(request, 'That email is being used') return redirect('register') else: # Looks good user = User.objects.create_user( username=username, password=password, email=email, first_name=first_name, last_name=last_name) # noqa # Login after register auth.login(request, user) messages.success(request, 'You are now logged in') return redirect('index') # user.save() # messages.success( # request, 'You … -
django : AttributeError: 'str' object has no attribute 'utcoffset'
template: <h2>Summary Details</h2> <table class="center"> <thead> <tr> <th>scrapper_id</th> <th>scrapper_jobs_log_id</th> <th>external_job_source_id</th> </tr> </thead> <tbody> {% for stud in scrappers %} {% csrf_token %} <tr> <td>{{stud.scrapper_id}}</td> <td>{{stud.scrapper_jobs_log_id}}</td> <td>{{stud.external_job_source_id}}</td> </tr> {% endfor %} views.py from django.db.models import Q from django.utils import timezone import pytz import warnings warnings.filterwarnings("ignore") get_records_by_date = "" def index(request): if request.method == "POST": from_date = request.POST.get("from_date") f_date = datetime.datetime.strptime(from_date,'%Y-%m-%d') print(f_date) to_date = request.POST.get("to_date") t_date = datetime.datetime.strptime(to_date, '%Y-%m-%d') print(t_date) new_records_check_box_status = request.POST.get("new_records", None) print(new_records_check_box_status) error_records_check_box_status = request.POST.get("error_records", None) print(error_records_check_box_status) drop_down_status = request.POST.get("field",None) print(drop_down_status) global get_records_by_date if new_records_check_box_status is None and error_records_check_box_status is None: get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)) get_records_by_date = check_drop_down_status(get_records_by_date,drop_down_status) elif new_records_check_box_status and error_records_check_box_status is None: get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)).filter(new_records__gt=0) get_records_by_date = check_drop_down_status(get_records_by_date, drop_down_status) elif error_records_check_box_status and new_records_check_box_status is None: get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)).filter(error_records__gt=0) get_records_by_date = check_drop_down_status(get_records_by_date, drop_down_status) else: get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)).filter(Q(new_records__gt=0)|Q(error_records__gt=0)) get_records_by_date = check_drop_down_status(get_records_by_date, drop_down_status) # print(get_records_by_date) else: roles = Scrapper.objects.all() return render(request, "home.html",{"scrappers": roles}) return render(request, "home.html", {"scrappers": get_records_by_date}) AttributeError: 'str' object has no attribute 'utcoffset'. It was running correctly when I run another project and change the url the error is showing. Is there any solution what is the reason for the error. Its showing error in view page and html page return render(request, "home.html",{"scrappers": roles}) . … -
How to refer to main database instead test one Django TestCase
I am using Django TestCase class to run some test in my project. Few of these test using selenium driver to test forms via browser. Creation of new instance of database table (Recipe for ex.) Point is. Since im using a browser and fill forms fields with Selenium driver, new recipe instance is creating for main database, not test one. I am trying to delete last added row from Recipe table with Recipe.objects.using('default').latest('id').delete() after successful test run. 'default' is single database connection. But this query is targeting test database, which us creating while tests run. How make query refer to main database instead? -
Django AUTO INCREMENT for PK
I have some models in my Django app and I saw the field 'auto_increment_id' (as PK) doesn't work as 'AUTO INCREMENT' (the DB is Postgres). I made 2 records with auto_increment_id 1 and 2, delete record 2 and make a new one with auto_increment_id=3 instead of auto_increment_id=2. models.py class Testme(models.Model): auto_increment_id = models.AutoField(primary_key=True) year = models.ForeignKey( Year, verbose_name="Year", blank=False, on_delete=models.CASCADE, ) def __str__(self): return str(self.auto_increment_id) How can I fix it? Thanks a lot! -
Django I can't pull data from database. DoesNotExist error in web
Admin can change the web title,keywords or description. But it's not working rn. When i entry website i have a error: DoesNotExist at / Setting matching query does not exist. This is my home/models.py from django.db import models class Setting(models.Model): title = models.CharField(max_length=150) keywords = models.CharField(max_length=255) description = models.CharField(max_length=255) company = models.CharField(max_length=50) address = models.CharField(blank=True, max_length=150) phone = models.CharField(blank=True, max_length=15) fax = models.CharField(blank=True, max_length=15) email = models.CharField(blank=True, max_length=50) smptpserver = models.CharField(blank=True, max_length=30) smptemail = models.CharField(blank=True, max_length=30) smptpassword = models.CharField(blank=True, max_length=150) smptport = models.CharField(blank=True, max_length=15) icon = models.ImageField(blank=True, upload_to='images/') facebook = models.CharField(blank=True, max_length=50) instagram = models.CharField(blank=True, max_length=50) twitter = models.CharField(blank=True, max_length=50) aboutus = models.CharField(max_length=50) contact = models.CharField(max_length=50) contact_map = models.CharField(max_length=50) references = models.CharField(max_length=50) status = models.CharField(max_length=10, choices=STATUS) create_at = models.DateTimeField(auto_now_add=True) uptade_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title This is my home/views.py from django.http import HttpResponse from django.shortcuts import render from home.models import Setting def index(request): setting=Setting.objects.get(pk=1) context={'setting':setting} return render(request,'index.html',context) This is my home/temp/index.html {% block title %} {{ setting.title }} {% endblock %} {% block keywords %} {{ setting.keywords }} {% endblock %} {% block description %} {{ setting.description }} {% endblock %} -
Django csrf ajax form not submitting data on server but working on local
I am working on a form submission process. Everything is working fine on my local server but when I am hosting the site on my server then the form submission doing nothing. Here is my template file : ` {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/> <meta name="description" content=""/> <meta name="author" content=""/> <link href="{% static 'css/bootstrap.css'%}" rel="stylesheet"/> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> <!-- <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script> --> <script src="{% static 'js/emp1.js'%}" type="text/javascript"></script> <link href="{% static 'css/style.css'%}" rel="stylesheet"/> <script type="text/javascript"> window.CSRF_TOKEN = "{{ csrf_token }}"; </script> <link rel="shortcut icon" href="{% static 'images/favicon.ico' %}"> <!-- <meta name="csrf_token" content="{{ csrf_token }}"> --> <title>Application Upload</title> </head> <body> <header> <section class="bg-white"> <div class="container"> <div class="row"> <nav class="bg-dark mt-1 navbar navbar-expand-lg navbar-light p-1 sticky-top"> <div class="bg-dark container-fluid "><a class="navbar-brand text-white" href="/">Nitin Mandhare <br/> Law Associates LLP</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="false" aria-label="Toggle navigation"><span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarColor01"> <ul class="mb-2 mb-lg-0 ms-auto navbar-nav "> <li class="nav-item"><a class="nav-link active" aria-current="page" href="/">Home</a> </li> <li class="nav-item"><a class="nav-link" href="#">Features</a> </li> <li class="nav-item"><a class="nav-link" href="#">Pricing</a> </li> <li class="nav-item"><a class="nav-link" href="#">About</a> </li> </ul> </div> </div> </nav> </div> </div> </section> </header> <main> <section> <div class="bg-secondary container mb-3 mt-3"> <div … -
PyCharm debugger can't connect to Django app inside docker
I try to debug a Django app inside Docker container, the app is launched under uWSGI. Unfortunately, PyCharm debugger can't connect to the container and stops by timeout. My run configuration: I've added up --build to run all containers in debug mode. docker-compose.yml: version: "2.4" services: rabbitmq: image: rabbitmq:3.10.7-management-alpine container_name: bo-rabbitmq rsyslog: build: context: . dockerfile: docker/rsyslog/Dockerfile image: bo/rsyslog:latest container_name: bo-rsyslog platform: linux/amd64 env_file: - .env volumes: - shared:/app/mnt api: build: context: . dockerfile: docker/api/Dockerfile image: bo/api:latest container_name: bo-api platform: linux/amd64 ports: - "8081:8081" - "8082:8082" env_file: - .env volumes: - shared:/app/mnt apigw: build: context: . dockerfile: docker/apigw/Dockerfile image: bo/apigw:latest container_name: bo-apigw platform: linux/amd64 ports: - "8080:8080" env_file: - .env volumes: - shared:/app/mnt depends_on: - api volumes: shared: Dockerfile (for api): FROM nexus.custom.ru/base/python27:2.7.17 # CentOS 7 with Python 2.7 # Environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV PYTHONPATH /app/ ENV PATH /app/:$PATH ENV PIP_DEFAULT_TIMEOUT=100 \ PIP_DISABLE_PIP_VERSION_CHECK=1 \ PIP_NO_CACHE_DIR=1 # Install required software RUN yum -y install enchant # Working directory WORKDIR /app # Install and configure Poetry RUN pip install --no-cache-dir poetry \ && poetry config virtualenvs.create false # Install project dependencies COPY pyproject.toml . COPY poetry.lock . RUN poetry install --no-root --no-interaction # Copy project files COPY …