Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter view based on the users Group
I am trying to filter the query further to only show records where the Groups matches the logged in users group. I am new to Python and not sure how to add an additional filter into the below view. View @login_required(login_url='login') def home(request): q= request.GET.get('q') if request.GET.get('q') != None else '' infs= Infringement.objects.filter(Q(name__icontains=q) | Q(infringer__name__icontains=q) ) Model class Infringement (models.Model): name = models.CharField(max_length=200) link = models.CharField(null=True, blank=True, max_length=200) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) infringer = models.ForeignKey(Infringer, on_delete=models.SET_NULL,null=True) player = models.ForeignKey(Player, on_delete=models.SET_NULL,null=True) customer = models.ForeignKey(Customer, on_delete=models.SET_NULL,null=True) status = models.ForeignKey(Status, on_delete=models.SET_NULL,null=True) groups = models.ForeignKey(Group, on_delete=models.CASCADE,default=1) class Meta: ordering = ['-updated', '-created']` I tried adding the below but it doesn't work. infs= Infringement.objects.filter(Q(name__icontains=q) | Q(infringer__name__icontains=q|) (groups=request.user.groups) ) -
django.core.exceptions.ImproperlyConfigured: PASSWORD_RESET_TIMEOUT_DAYS/PASSWORD_RESET_TIMEOUT are mutually exclusive
I'm upgrading a django code and I faced this error when I runserver, I tryied already to ALLOWED_HOSTS = ["*"] and it doesn't work -
Edit data in the database that was recorded without a form
In my project, there is a form and a table with checkboxes, based on the data entered in the form and the checkboxes, I fill 2 databases and redirect the user to a page where information from one table is displayed, it all worked very well until I got to editing the records, I decided I do it with UpdateView, passing in template_name the same template as before adding records: here is the add function and the edit class: class CampaignEditor(UpdateView): model = Campaigns template_name = 'mailsinfo/add_campaign.html' form_class = CampaignsForm def add_campaign(request): if request.method == 'POST': addCampaignDataToDB(request.POST) data = list(Emails.objects.values()) data = MailsTableWithoutPass(data) form = CampaignsForm() data_ = { 'form': form, 'data': data } return render(request, 'mailsinfo/add_campaign.html', data_) But when calling the url to change my data table is empty and there are no selected checkboxes there, all processing of the form works fine Here is the template I use, and the function that writes the data into the tables: <div> <div class="container-campaign"> <div class="campaign-form"> <form method="post" id="newCampaign"> {% csrf_token %} {{ form.name }}<br> {{ form.subject }}<br> {{ form.body }}<br> {{ form.user_guid }}<br> </form> </div> <div class="campaign-table"> <table id="table" data-height="480" class="table table-dark"> <thead> <tr name="mails-info"> <th data-field="state" data-checkbox="true"></th> <th data-field="id">ID</th> … -
How to properly config a django application on cpanel
Before now, the main domain was serving a WordPress website but I needed to replace that with a new django application. I was able to successfully deploy the Django application to cPanel, and the application was served on a subdomain without any problems. But when I edit the application url to point to the main domain, the homepage renders without the static files. Initially, I thought it was a static file issue until I tried to access other pages, but all I keep getting is a 404 page that is being served by the old WordPress. Somehow the old wordpress website is conflicting with the django app. I'm not sure why the old wordpress is still trying to serve the new django pages except the homepage, even though static files are also missing on the homepage. -
How to handle Response when the I'm a expecting a url to download a file?
So I'm using a third party API to make my own, I'm expecting a download url back. But here the response is what I don't know how to handle. Any Help ? class ListUserSearchView(ListAPIView): queryset = UserSearch.objects.all() serializer_class = UserSearchSerializer permission_classes = [IsAdminUser] def get(self, request, data=None, *args, **kwargs): url = "base_url" querystring = {"track_url": request.data.get('track_url')} headers = { "X-RapidAPI-Key": "API key", "X-RapidAPI-Host": "API host" } response = requests.request("GET", url, headers=headers, params=querystring) Response(response.text) -
Django two different URLs map to same view function
New to Django! I want to move some of my URLs to new ones but keep serving old ones for a while. Is there a standard practice in Django for this? I have referred to older posts (How to map two urls to one view?) that have /<person> /<name> mapped to same function. Can I use the same approach for /<person> /company/<company-id>/<person>? Is it just better to add this into query parameter and version bump the API? I like versioning API when new parameters are added into target object, for instance, person having a new field but not for this. Reason: all the new URLs coming after this are guaranteed to have /company// I am still exploring ways. -
Getting error json.decoder.JSONDecodeError
Here's the full traceback of the error I am getting: ERROR 2022-11-08 13:29:54,926: Internal Server Error: /voice_chat/rooms Traceback (most recent call last): File "C:\Users\15512\anaconda3\lib\site-packages\asgiref\sync.py", line 451, in thread_handler raise exc_info[1] File "C:\Users\15512\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 38, in inner response = await get_response(request) File "C:\Users\15512\anaconda3\lib\site-packages\django\core\handlers\base.py", line 233, in _get_response_async response = await wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\15512\anaconda3\lib\site-packages\asgiref\sync.py", line 414, in __call__ ret = await asyncio.wait_for(future, timeout=None) File "C:\Users\15512\anaconda3\lib\asyncio\tasks.py", line 455, in wait_for return await fut File "C:\Users\15512\anaconda3\lib\concurrent\futures\thread.py", line 57, in run result = self.fn(*self.args, **self.kwargs) File "C:\Users\15512\anaconda3\lib\site-packages\asgiref\sync.py", line 455, in thread_handler return func(*args, **kwargs) File "C:\Users\15512\anaconda3\lib\site-packages\django\views\generic\base.py", line 69, in view return self.dispatch(request, *args, **kwargs) request_body = json.loads(decode_request) File "C:\Users\15512\anaconda3\lib\json\__init__.py", line 357, in loads return _default_decoder.decode(s) File "C:\Users\15512\anaconda3\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\15512\anaconda3\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) ERROR 2022-11-08 13:29:54,959: HTTP POST /voice_chat/rooms 500 [0.32, 127.0.0.1:54258] This is my code: def post(self, request, *args, **kwargs): decode_request = request.body.decode("utf-8") print('decoded request body', decode_request) request_body = json.loads(decode_request) # print('request body', request_body) room_name = request_body.get("roomName") participant_label = request_body["participantLabel"] # print('username', curr_username) response = VoiceResponse() dial = Dial() dial.conference( name=room_name, participant_label=participant_label, start_conference_on_enter=True, ) response.append(dial) return … -
How to add 3 or more Model attributes sitting in one ManytoManyField in Django Models ? Need to display a certain total in frontend
Problem Statement: I want to add up the Activity.models attribute net_cost from within Trip.models i.e. connected via ManytoManyField. I have 3 or more choices per instance, so add: from the template language is inadequate (https://docs.djangoproject.com/en/4.1/ref/templates/builtins/#add) More Context: Activity is connected to Trip via ManytoManyField. Accessing and adding up via save method in models.py is causing id needs to be assigned first error, I believe since ManytoMany can only be assigned once an instance of the model is saved. Even if I access them all in the views.py before rendering, the context passed even after iterating over each object in list, can onlt render a singular grand total for all entries rendered in the template, making it redundant. Models: Activity -> class Activity(models.Model): activity_location = [ ... ] acitivity_duration = [ ... ] activity_title = models.CharField(max_length=20, unique=True) ... net_cost = models.PositiveIntegerField(validators=[MaxValueValidator(100000), MinValueValidator(0)], default=0) class Meta: ordering = ['-margin'] def __repr__(self): return f"{self.activity_title} - {self.activity_location} - {self.net_cost}" def __str__(self): return f"Activity {self.activity_title}, Location {self.activity_location}, Duration {self.acitivity_duration}, Cost {self.net_cost}" def get_absolute_url(self): return reverse('activitys-list') Trip -> class Trip(models.Model): transfer_choices = [ ... ] transfers = models.CharField(max_length=11, choices=transfer_choices, blank=True, null=True) activity = models.ManyToManyField(Activity, related_name="activities", blank=True, verbose_name='Activities', help_text='select multiple, note location tags') .... class Meta: ordering … -
Unable to get (user) as mysite.com/user in right way
I'm using twitter API for authentication process and it works fine. But I want something like mysite.com/user where (user: twitter user name). And I'm able to get this too but the only when I hit the logout button why so? I mean my twitter_callback function running when I hit twitter_logout. As it should be running at the login time! urls.py urlpatterns = [ path('', views.index, name='index'), path('twitter_login/', views.twitter_login, name='twitter_login'), path('twitter_callback/', views.twitter_callback, name='twitter_callback'), path('twitter_logout/', views.twitter_logout, name='twitter_logout'), path('<str:username>/', views.user_profile, name='user_profile'), ] views.py from django.contrib import messages from django.contrib.auth import login, logout from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect from .decorators import twitter_login_required from .models import TwitterAuthToken, TwitterUser from .authorization import create_update_user_from_twitter, check_token_still_valid from twitter_api.twitter_api import TwitterAPI from django.contrib.auth import logout # Create your views here. def twitter_login(request): twitter_api = TwitterAPI() url, oauth_token, oauth_token_secret = twitter_api.twitter_login() if url is None or url == '': messages.add_message(request, messages.ERROR, 'Unable to login. Please try again.') return render(request, 'authorization/error_page.html') else: twitter_auth_token = TwitterAuthToken.objects.filter(oauth_token=oauth_token).first() if twitter_auth_token is None: twitter_auth_token = TwitterAuthToken(oauth_token=oauth_token, oauth_token_secret=oauth_token_secret) twitter_auth_token.save() else: twitter_auth_token.oauth_token_secret = oauth_token_secret twitter_auth_token.save() return redirect(url) def twitter_callback(request): print("Running twitter_callback") if 'denied' in request.GET: messages.add_message(request, messages.ERROR, 'Unable to login or login canceled. Please try again.') return render(request, 'authorization/error_page.html') twitter_api = TwitterAPI() oauth_verifier … -
How to use the same database on two separate machines (copies)?
I have a web application project that I would like to create with a friend of mine. We are planning to have a simple frontend with JavaScript, a backend with Django, and a PostgreSQL database. We're planning to use apache for the web server. The application would be a simple website showing statistical data from the data in our database. The data in the database would be loaded from CSV files which are stored locally (would not be uploaded through the website, but rather by us). We don't need "live" data, so it would be ok to create the whole database with tables and everything on one machine and then copy that to the other machine. - only problem is that we don't really know how one could do that Now the question I have is: How should we set up our environments so that we can use the same database and the same code? We would use git for code versioning of course, but I am not sure how one would do versioning with a database. I have found online that docker would be a good option, but I have unfortunately very little experience with it so would really … -
Django, How to queue tasks to control the flow of queries?
I'm working on a Django middleware to store all requests/responses in my main database (Postgres / SQLite). But it's not hard to guess that the overhead will be crazy, so I'm thinking to use Redis to queue the requests for an amount of time and then send them slowly to my database. e.g. receiving 100 requests, storing them in database, waiting to receive another 100 requests and doing the same, or something like this. My questions are "is it a good approach? and how we can implement it? do you have any example that does such a thing?" And the other question is that "is there any better solution"? -
Django : Recalculating mean value in the database after creating a new instance
I have informations about companies presented in a table. One of the field of this table is the mean value of each note the company received ('note_moyenne' in models.FicheIdentification). By clicking on a button, people are able to submit a new note for the company ('note' in models.EvaluationGenerale). I want the mean value of the notes to update in the database each time someone submit a new note. Here is my models.py : class FicheIdentification(models.Model): entreprise=models.ForeignKey(Entreprise, on_delete=models.CASCADE) note_moyenne=models.IntegerField() def __str__(self): return self.entreprise.nom_entreprise class EvaluationGenerale(models.Model): entreprise=models.ForeignKey(Entreprise, on_delete=models.CASCADE) note=models.IntegerField() commentaires=models.CharField(max_length=1000) date_evaluation=models.DateField(auto_now_add=True) def __str__(self): return self.commentaires views.py : class CreerEvaluationGenerale(CreateView): form_class = FormulaireEvaluationGenerale model = EvaluationGenerale def form_valid(self, form): form.instance.entreprise=Entreprise.objects.filter(siret=self.kwargs['siret']).first() return super(CreerEvaluationGenerale, self).form_valid(form) def get_success_url(self): return reverse('details-evaluations') Currently I just display the mean value in my table using this def render_evaluation(self, record): return (EvaluationGenerale.objects.filter(entreprise=record.entreprise.siret).aggregate(Avg('note'))['note__avg']) but I really don't like this solution as I want the value to be stored in the database, in FicheIdentification.note_moyenne. I thought about creating a UpdateView class but couldn't manage to link it with my CreateView. Any help or documentation would be really appreciated, I'm a bit lost right know... -
Async await call request.user in Django 4.1 causes SynchronousOnlyOperation
I'm using this async code to check user is is_authenticated: async def offers(request, currency_id): user = await User.objects.aget(pk=request.user.pk) currency = await sync_to_async(get_object_or_404)(Currency, pk=currency_id) offers_to_sell = [ item async for item in Offer.objects.filter( currency_to_sell_id=currency_id ).prefetch_related("currency_to_sell", "currency_to_buy") ] context = {"currency": currency, "offers_to_sell": offers_to_sell, "user": user} return render(request, template_name="offers.html", context=context) But it throws me an error: SynchronousOnlyOperation You cannot call this from an async context - use a thread or sync_to_async. Traceback (most recent call last): File "\venv\lib\site-packages\django\contrib\sessions\backends\base.py", line 187, in _get_session return self._session_cache Also I tried this code, but with no luck: user = await sync_to_async(User.objects.get)(pk=request.user.pk) And from template without using code in view: {% if request.user.is_authenticated %} But result is the same. It looks that there is something I missed about async call. What is the problem? -
Django Model Multi Select form not rendering properly
I am trying to display all the categories to appear as a list that I can click and select from, just an exact replica of what I have in my admin panel, but it still display's as a list that isn't clickable. forms.py class ProfileEditForm(forms.ModelForm): """ Form for updating Profile data """ class Meta: model = Profile fields = [ "first_name", "last_name", "about_me", "profile_image", "username", "email", "categories", ] first_name = forms.CharField(label="First Name", max_length=63, required=False) last_name = forms.CharField(label="Last Name", max_length=63, required=False) about_me = forms.CharField(label="About Me", max_length=511, required=False) email = forms.EmailField(label="Email", disabled=True) username = forms.CharField(label="Username", disabled=True) profile_image = forms.ImageField(required=False) categories = forms.ModelMultipleChoiceField( queryset=Category.objects.all(), required=False, widget=forms.CheckboxSelectMultiple(), ) settings.html <div class='row'> <div class="col s12 m6"> {{form.categories.errors}} {{form.categories.label_tag}} {{form.categories}} </div> </div> Output -
image 404 in django template
I am making a catalog of film directors for an introduction to django exercise and im trying to load the images from my database to my template but is not working. All my steps: I added an imagefield to the directors model class, which I have then filled in from the admin version. Then in my view I have made a request to collect a list of all directors like so: directors = Directors.objects.all() and then I have returned it with render. In the template I have done this {%for director in directors%} <img src="{{director.director_image.url}}" alt="{{director.first_name}}"> {% endfor %} And everything is fine except that the images are not loaded, the alt with the names of the directors are ok :D (an advance). I get the feeling that somehow I have to define the url of the images??? because from the browser console it get the url of the images properly but it gives a 404. im really on my first days using django so I guess im missing something with how the media urls works. hope someone can help me. tysm <3 What I tried? I haven't tried anything else since I'm very new to django. I have searched … -
How to change the label in display_list of a field in the model in django admin
I have a model with some fields with a verbose_name. This verbose name is suitable for the admin edit page, but definitively too long for the list page. How to set the label to be used in the list_display admin page ? -
passing url parameters using custom url converter in django
I am getting this error when I use my custom url converter Reverse for 'user-update' with keyword arguments '{'pk': 'Rwdr4l3D'}' not found. 1 pattern(s) tried: ['users/(?P<pk>[a-zA-Z0-9](8,))/update/\\Z'] Question: why isn't the pk matching the regex whats wrong details given below urls.py from utils.url import HashIdConverter register_converter(HashIdConverter, "hashid") app_name = "users" urlpatterns = [ path("<hashid:pk>/update/", views.UserUpdateView.as_view(), name="user-update"), ******* utils/url.py class HashIdConverter: regex = f'[a-zA-Z0-9]{8,}' def to_python(self, value): return h_decode(value) def to_url(self, value): return h_encode(value) template I've tried using <a href="{% url 'users:user-update' pk=user.hashed_id %}" also, <a href="{% url 'users:user-update' user.hashed_id %}" where hashed_id is as below def hashed_id(self): return h_encode(self.id) neither of them is working -
choice modify in foreignkey Django or add default 'other' in foregin key
Department Name is a foreignkey in django, And I wanted to add new choice 'other' . Do know how to achieve that either by forms or ? -
NetSuite Script AWS SP API STS request
I am trying to connect to Amazon SP API through NetSuite scripts but unable to establish the connection, i am able to get the access token but when i try to create the authorization i keep getting the error that signature does not match. Need help to get the STS connection setup. Below is part of the STS request that i am trying. const amzDate = getAmzDate(); const datestamp = amzDate.split("T")[0]; var host = "sts.amazonaws.com"; //https://sts.amazonaws.com/?Version=2011-06-15&Action=AssumeRole&RoleSessionName=Test&RoleArn=myactualARN&DurationSeconds=3600 const canonicalUri = '/'; const canonicalQuerystring = "?Version=2011-06-15&Action=AssumeRole&RoleSessionName=Test&RoleArn=mayactualARNe&DurationSeconds=3600"; const canonicalHeaders = 'host:' + host + '\n' + 'x-amz-date:' + amzDate + '\n'; const signedHeaders = 'host'; const payloadHash = crypto.createHash({ algorithm: crypto.HashAlg.SHA256 }); const canonicalRequest = 'GET\n' +canonicalUri + '\n' +canonicalQuerystring + '\n' +canonicalHeaders + '\n' +signedHeaders + '\n' +payloadHash.digest().toLowerCase(); log.debug("canonicalRequest",canonicalRequest); const credentialScope = datestamp + '/' + REGION + '/' + SERVICE_NAME_STS + '/' + 'aws4_request'; const canonicalHash = crypto.createHash({ algorithm: crypto.HashAlg.SHA256 }); canonicalHash.update({ input: canonicalRequest }); const stringToSign = ALGORITHM + '\n' +amzDate + '\n' +credentialScope + '\n' +canonicalHash.digest().toLowerCase(); log.debug("stringToSign",stringToSign); const signingKey = getSignatureKey(amamzonConnectionKeysArray.secretkey, datestamp, REGION, SERVICE_NAME_STS); const signature = CryptoJS.HmacSHA256(stringToSign, signingKey); const authorizationHeader = ALGORITHM + ' ' + 'Credential=' + amamzonConnectionKeysArray.accesskey + '/' + credentialScope + ', ' + 'SignedHeaders=' … -
mod_wsgi.py no module namesd django Centos7
I have a django project which works fine in the development envirnonment. I seem to have set something wrong in my httpd .conf file. When I attempt to use production mode and to go to the page - I get an 500 Internal Server Error. My wsgi.py Module complains that it cannot find django. Error is: File "/var/www/trackx_proj/trackx_root/trackx/wsgi.py", line 17, in <module> [Tue Nov 08 11:54:17.140508 2022] [wsgi:error] [pid 2969] [remote xxx.xxx.95.97:56342] from django.core.wsgi import get_wsgi_application [Tue Nov 08 11:54:17.140549 2022] [wsgi:error] [pid 2969] [remote xxx.xxx.95.97:56342] ModuleNotFoundError: No module named 'django' In my configuration file I have: WSGIDaemonProcess trackx_proj python-home=/home/bakert/.local/share/virtualenvs/trackx_proj-2E2CC07X WSGIProcessGroup trackx_proj WSGIScriptAlias / /var/www/trackx_proj/trackx_root/trackx/wsgi.py I pointed this at the virtual environment for the user that I used when I created this app. It's all owned by apache.. If I change it to the www directory i.e.: WSGIDaemonProcess trackx_proj python-home=/var/www/trackx_proj/trackx_root WSGIProcessGroup trackx_proj WSGIScriptAlias / /var/www/trackx_proj/trackx_root/trackx/wsgi.py Then I get a recurring error in the log file: Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' Not sure why it cannot seem to find the right environment. Maybe I need to set up the virtual environment for the application under www ?? Any ideas about this … -
Django RadioSelect choices with "Other" Text Field - [Form not saving]
I'm trying to add a radioselet button and an 'other' option that includes a freeform text. How do I create this is in Django. I've gotten my form to have this input type and capture the information. However, my form refuses to save and validate the field. Here's my models.py file. Here's my forms.py file. Can you help me? Thank you! -
Django rest api create email login along with password
Hi. I've created the employee management system using django rest api. I've created the models, views and serializers like shown below. What i need is I've created employee details like his personal details as a register view, but when he login i want to use email and password field as a field to sign with jwt token. How to implement this. Models.py Class Employee (models.Model): Fname = models.charfield() Lname = models.charfield() Personal _email=models.Emailfield() Department= models.choicefield() Designation= models.charfield() Serializer.py Class Employeeserializer(models.Modelserializer): class Meta: model = Employee fields = '__all__ Views.py Registeremployeeview(createAPIview): serializer_class = Employeecreateserializer def post(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response({ "user": serializer.data, "message": "User Created Successfully..!", }) Now i want to create login view. How to i make email and password login view and serializers without I haven't included that in my models. Alos i want to login and set authentication with jwt authentication. Please somebody help -
django csrf / how it works?
we have good page But if we add csrf token in the top of html template All head's content will move in body and head will be empty How it works? I think csrf does input and all info after input teleport in body :/ but why -
Plotly Dash - Change number abbreviations format
I have lots of tables and plots shown about transactions on my web app, with the frontend based on Dash. The issue is that Plotly uses d3 format to format all numbers, and d3 format doesn't include "Million" & "Billion". Therefore, I'm getting the abbreviations "G" & "T", that are used for example in "gigabytes" or "terabytes". Do you know any way of changing those ? I haven't found anything relevant online... Here are some examples: For the table, here is the corresponding code: format_number = Format().precision(2).scheme("s") format_amount = Format().precision(2).scheme("s").symbol(Symbol.yes).symbol_suffix(" €") table = DataTable( columns=[ { "name": ["Transactions", "Total number"], "id": "nb_operation", "type": "numeric", "format": format_number, }, { "name": ["Transactions", "Total amount"], "id": "amount_euro", "type": "numeric", "format": format_amount, }, ], [...] -
Django + Celery + Nginx
I try to run my django application in docker with Celery and Nginx. Docker-compose version: '3' services: helpdesk_web: build: context: ./ dockerfile: Dockerfile container_name: helpdesk_web volumes: - ./static:/usr/src/app/static - media:/usr/src/app/media ports: - "8000:8000" - "5678:5678" env_file: - ./.env restart: always depends_on: - helpdesk_db - helpdesk_redis helpdesk_db: image: postgres container_name: helpdesk_db volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env ports: - "5432:5432" environment: POSTGRES_DB: helpdesk_db POSTGRES_PASSWORD: itds POSTGRES_USER: itds nginx: build: context: ./docker/nginx dockerfile: Dockerfile container_name: helpdesk_nginx restart: on-failure depends_on: - helpdesk_web - helpdesk_db ports: - "80:80" volumes: - ./static:/usr/src/app/static - media:/usr/src/app/media helpdesk_redis: image: redis ports: - "6379:6379" helpdesk_celery: build: context: . dockerfile: Dockerfile command: celery -A helpdesk worker -l INFO --pool=solo depends_on: - helpdesk_web - helpdesk_redis helpdesk_celery-beat: build: context: . dockerfile: Dockerfile command: celery -A helpdesk beat -l INFO --scheduler django_celery_beat.schedulers:DatabaseScheduler depends_on: - helpdesk_web - helpdesk_redis volumes: postgres_data: media: Dockerfile FROM python:3.10 WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip COPY requirements.txt . RUN pip install -r requirements.txt COPY . . RUN chmod +x entrypoint.sh ENTRYPOINT ["/usr/src/app/entrypoint.sh"] entrypoint.sh #! /bin/sh if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." while ! nc -z $SQL_HOST $SQL_PORT; do sleep 0.1 done echo "PostgreSQL started" fi python manage.py …