Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't host my django website on shared hosting
I am trying to deploy my django project on shared hosting. I am trying from couple of hours but still now I can't host my django website and getting "Internal Server Error Error 500". this is my root passenger_wsgi.py from my_root_folder_name.wsgi import application #setting.py ALLOWED_HOSTS = ['mydomain.com','www.mydomain.com'] I also installed python app and django on my server. Now I am hopeless. I am trying from last five hours for host an website but still now I can't. Where I am doing mistake??? I am seeing those error from error log: File "/home/sellvqed/virtualenv/farhyn.com/3.8/lib/python3.8/site-packages/django/apps/registry.py", line 83, in populate raise RuntimeError("populate() isn't reentrant") RuntimeError: populate() isn't reentrant -
Why i get results of this ajax call instantly though I have async code?
I am studying async programming with Python and I cannot get why I get instant answer when I call route corresponding to this call (I call it as ajax call, platform is Django, this file is views.py file in Django app)? (When I click on button ajax calls buy method, it simulates buying some stock with sandbox and returns result, I want it to wait 5 secs and then return result, instead I get results of ajax call nearly immediately) async def buy(request): figi = request.GET.get('figi', 'missing') data = { 'result': 'success', 'figi': figi } SANDBOX_TOKEN = 'some_token' async def buy_stock(): try: async with TinkoffInvestmentsRESTClient( token=SANDBOX_TOKEN) as rest: order = await rest.orders.create_market_order( figi="BBG000BTR593", lots=1, operation=OperationType.BUY, ) await asyncio.sleep(5) result = await rest.orders.create_limit_order( figi="BBG000BTR593", lots=1, operation=OperationType.SELL, price=50.3, ) return 'result' except TinkoffInvestmentsError as e: print(e) result = await buy_stock() return JsonResponse({ 'result': 'success', 'message': result }, safe=False) In other words, seems call doesn't wait for async methods to finish and immediately sends JsonResponse -
How to upload a form image that comes in a request.FILES[] to an ImageField in my django db?
The problem here is that when I "upload" the image, it doesn't make any changes where it should It lets me make the upload with no errors but as I said, it doesn't update un db or anywhere. I need to write more to post this as I have too much code so dont read this part in parenthesis (Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pharetra augue sed pharetra lobortis. Mauris sit amet pellentesque felis. Integer in magna nec enim placerat imperdiet vitae et justo. Integer vel est ultricies, faucibus urna id, consequat eros. Integer venenatis ut nisi a aliquam. Morbi leo sem, dictum porttitor nibh id, condimentum pellentesque purus. Quisque pellentesque et nibh nec hendrerit. Suspendisse in nulla urna. Nam sit amet congue quam. Duis tellus enim, tincidunt ac est eget, lobortis accumsan orci. Mauris laoreet iaculis ornare. Maecenas eget urna malesuada dolor mollis efficitur. Nullam vehicula vel justo nec suscipit. Morbi fermentum libero urna, feugiat tincidunt felis pharetra ut. Vestibulum at erat sed massa sodales malesuada et eget justo. Fusce at iaculis quam, non elementum quam.) This is my model from django.db import models from django.utils.timezone import now from django.contrib.auth.models import User from ckeditor.fields import … -
Django url re_path failed to redirect to the correct view
Django re_path did not match and I don't know the reason why. urls.py urlpatterns = [ .. re_path(r'^localDeliveryPayment\?paymentId\=(?P<UUID>[0-9-a-z]{32})$', verifyMobilePayReceived.as_view()), re_path(r'^localDeliveryPayment$', Payment.as_view(), name = 'localDeliveryPayment'), .. ] If url www.example.com/localDeliveryPayment the user is directed to Payment view. If url www.example.com/localDeliveryPayment?paymentId=00340000610febab0891e9008816d3e9 the user should be directed to verifyMobilePayReceived view. The problem is that right now www.example.com/localDeliveryPayment?paymentId=00340000610febab0891e9008816d3e9 is still directed to Payment view. -
NoReverseMatch in Django but no clear issues
I've been reading other solutions to this but none of them apply to my project. It's a database of family pictures. The Problem On the list view, which works fine, there are two types of links - one at the top of the page to create a new record and one for each of the listed items to update the selected record. When clicking either, I get the following error. If I simply enter the URLs, I also get the same error. NoReverseMatch at /stories/l_memories_update_people/4 Reverse for 'memories_people' not found. 'memories_people' is not a valid view function or pattern name. . Models class memories_people(models.Model): fk_user = models.ForeignKey(User, default='1', on_delete=models.CASCADE) name = models.CharField(max_length=750, default='', blank=True, null=True) def __str__(self): return self.name class Meta: ordering = ('name', ) Views class v_memories_list_people(LoginRequiredMixin, ListView): model = memories_people template_name = 'storiesapp/t_memories_list_people.html' context_object_name = 'people' ordering = ['name'] class v_memories_update_people(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = memories_people fields = ['fk_user', 'name'] template_name = 'storiesapp/t_memories_update_people.html' def form_valid(self, form): form.instance.fk_user = self.request.user form.save() return HttpResponseRedirect(self.request.path_info) def test_func(self): post = self.get_object() if self.request.user == post.fk_user: return True return False URLs path('l_memories_list_people',v_memories_list_people.as_view(), name='r_memories_list_people'), path('l_memories_update_people/<int:pk>',v_memories_update_people.as_view(), name='r_memories_update_people'), Template (List) {% load static %} {% load crispy_forms_tags %} {% load render_table from django_tables2 %} {% load … -
Can 2 urls file in the same app have the same app name in Django?
The question is honestly completely self-explanatory. Can 2 urls.py files in the same app have the same app_name in Django? -
Django - import processes breaks if multiple S3 backends configured
I have a import process that should fetch multiple S3 backends for objects. Actually the process is working fine if I just have a single s3 backend configured. As soon as I have multiple S3 backends setup to fetch data from, my whole import process fails as no entries are written to my "Files" table. I have my import process packed as a celery task, please see below: @app.task(name="Fetch Descriptor JSON", base=Singleton) @transaction.atomic def fetch_descriptors(*args, **kwargs): keys = [] urls = [] for resource in S3Backend.objects.filter(backend_type=0): endpoint = resource.endpoint bucket = resource.bucket access_key = resource.access_key secret_key = resource.secret_key region = resource.region for obj in s3_get_resource(endpoint=endpoint, access_key=access_key, secret_key=secret_key, region=region).Bucket(bucket).objects.all(): keys.append(obj.key) for key in keys: descriptor = s3_get_client(endpoint=endpoint, access_key=access_key, secret_key=secret_key, region=region).generate_presigned_url( ClientMethod='get_object', Params={'Bucket': bucket, 'Key': key}, ExpiresIn=432000, ) new_file, create = Files.objects.get_or_create(descriptor=strip_descriptor_url_scheme(descriptor), file_path=key, file_name=Path(key).name, s3_backend=resource ) urls.append(descriptor) workflow_extract_descriptors = ( group([extract_descriptors.s(descriptor) for descriptor in urls]).apply_async() ) Are there maybe any problems with my for loop construct if S3Backend.objects.filter(backend_type=0) returns more than one entry? Thanks in advance -
Creating a blockchain game integrated on the web using python
Basically i need advice on which packages / frameworks to use in order to create this. My goal is to create a sort of cards/dice game (its called orlog) and im planning to use web3 to fetch a players data from the blockchain The game is in browser as well so i dont know what to use, whether its pygame + opengl django web framework etc etc Note: the game will be online 1 vs 1 -
How can I implement a database (ER) table where the values of a foreign key depend on another foreign key within the same table? (Django, e-commerce)
Please bare with me as I am a newbie to database design. I am trying to implement an e-commerce store in Django with product variations as shown in the attached image. For the ProductVariations model/table, I would like to have a foreign key for Options (which would represent something like size) and then based on that foreign key, I would like to have another foreign key for OptionValues (e.g. small). The possible values for the latter foreign key should be limited by the former foreign key. More specifically, I want don't want the drop-down in the admin site to display "small, red, blue, 32, 33, large" when the previous foreign key was "size". In that case, I would only want it to display "small, large". How do I go about doing this? I'd be grateful for any ideas either specific to Django or just database design in general. Image of my ER model. I might consider also adding the Product relationship to the Option which would mean now the option_value depends on the option which depends on the product. -
Django - creating super user
I created the model User And i added this two lines " is_superuser=models.BooleanField(default=False) is_staff=models.BooleanField(default=False)" just to by pass the probleme and create a super user by the model not the default one but this can't be the solution to my probleme i need to create a default django super uesr from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): first_name= models.CharField(max_length=30) last_name= models.CharField(max_length=30) cin = models.IntegerField() username= models.CharField(max_length=30,unique=True) password= models.CharField(max_length=30) codeQR = models.CharField(max_length=30) poste = models.CharField(max_length=30) image = models.CharField(max_length=30) email = models.EmailField() telephone= models.IntegerField() is_superuser=models.BooleanField(default=False) is_staff=models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] class pointage(models.Model): entre = models.CharField(max_length=30) sortie = models.CharField(max_length=30) retard = models.CharField(max_length=30) absance = models.CharField(max_length=30) user = models.ManyToManyField(User) class salaire(models.Model): mois = models.IntegerField() heurs_base= models.FloatField() heurs_sup = models.FloatField() primes = models.FloatField() total = models.FloatField() user = models.ManyToManyField(User) But i get the following error PS C:\py\pointage> py manage.py createsuperuser Username: a Password: Password (again): Error: Your passwords didn't match. Password: Password (again): The password is too similar to the username. This password is too short. It must contain at least 8 characters. This password is too common. Bypass password validation and create user anyway? [y/N]: y Traceback (most recent call last): File "C:\Users\moezm\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, … -
How to connect many to many relationaship if I save them via form.save() (django)?
This link https://docs.djangoproject.com/en/3.2/topics/db/examples/many_to_many/ explains that I need to make an object of the class to save the connection. Because I have many fields in my classes I used form.save() to save them, but that doesn't fill the connection ManyToMany in the class. How to fill that field? def create(response): if response.method == "POST": if "next" in response.POST: form = CreateNewPerson(response.POST) form.save() form2 = CreateNewDog() # form doesn't have filed many_to_many to Person, but class Dog does class CreateNewDog(forms.ModelForm): class Meta: model = Dog fields = ['name','years_old', 'sex', 'blood_type', 'image'] class Dog(models.Model): owner = models.ForeignKey(Person, on_delete=models.SET_NULL, null=True) user = models.ManyToManyField(User) -
Django save a change to Database
I'm trying to update the is_admin column of the model user_profile. I've written the following code in views.py but it's not updating in the DB. How can I save the change (user_object[0].is_admin = True) to the database? def post(self, request, format=None): users_provided = request.data.get('user_ids') for each_user in users_provided: user_object = UserProfile.objects.filter(user__is_active=True, user_id=each_user) if (user_object.exists()): user_object[0].is_admin = True user_object.update() -
reques.POST.get, always returns none
I'm trying to get the value of the template's select field, using request.POST.get. But even with the correct name the value that the view receives and always None, can someone help me how to solve this? Here are the codes: view: def efetuar_pagamento(request, id_pagamento): if request.POST: objPagamento = Pagamento.objects.select_related( "Matricula", "FormaPagamento").get(pk=id_pagamento) valorPago = request.POST.get("Valor_%s" % id_pagamento, None) formaPaga = request.POST.get("Forma_%s" % id_pagamento, None) print(formaPaga, valorPago) objFormaPG = FormaPagamento.objects.get(pk=formaPaga) objPagamento.ValorParcial = valorPago.replace(',', '.') objPagamento.FormaPagamento = objFormaPG objPagamento.save() if objPagamento.ValorParcial < objPagamento.Matricula.Plano.Valor and objPagamento.ValorParcial: objPagamento.Status = "PC" elif objPagamento.ValorParcial >= objPagamento.Matricula.Plano.Valor: objPagamento.Status = "PG" Template: <div class="body table-responsive"> <table class="table table-bordered table-striped table-hover js-basic-example dataTable"> <thead> <tr> <th>Data Vencimento</th> <th>Status Pagamento</th> <th>Valor Total</th> <th>Valor Pago</th> <th>Ações</th> </tr> </thead> <tbody> {% for objPagamento in listPagamentos %} <tr> <td>{{objPagamento.DataVencimento}}</td> <td>{{objPagamento.get_Status_display}}</td> <td>{{objMatricula.Plano.Valor}}</td> <td>{{objPagamento.ValorParcial|default_if_none:"0,00"}}</td> <td> {% if objMatricula.Plano.Valor >= objPagamento.ValorParcial %} <a type="button" class="btn btn-primary waves-effect" data-toggle="modal" data-target="#id_Status_{{objPagamento.id}}" data-toggle="tooltip" data-placement="top" title="Pagar!"><i class="material-icons" >attach_money</i></a> {% else %} <a type="button" class="btn btn-success waves-effect" data-toggle="tooltip" data-placement="top" title="Liquidado!"><i class="material-icons" >price_check</i></a> {% endif %} </td> </tr> <div class="modal fade" id="id_Status_{{objPagamento.id}}" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="defaultModalLabel"> <p>Efetuar Pagamento</p> </h4> </div> <form action="{% url 'efetuar_pagamento' objPagamento.id %}" id="id_form_{{objPagamento.id}}" method="POST"> {% csrf_token %} <div class="modal-body col-xs-12"> <h4>Valor … -
How to integrate Tron (TRX) crypto currency with python ? I am confused in their code can someone please help me to understand their code
import requests url = "https://api.trongrid.io/wallet/createtransaction" payload = "{\n \"to_address\": \"41e9d79cc47518930bc322d9bf7cddd260a0260a8d\",\n \"owner_address\": \"41D1E7A6BC354106CB410E65FF8B181C600FF14292\",\n \"amount\": 1000\n}" headers = { 'Content-Type': "application/json", 'TRON-PRO-API-KEY': "25f66928-0b70-48cd-9ac6-da6f5465447c663" } response = requests.request("POST", url, data=payload, headers=headers) print(response.text) I am creating a django based app where I will accept payments in Tron My Doubt is Do I have to keep "to_address"\ and "Owner Address"\ in code Where to pass Owners address and Clients address [as they have specified in the code Owner_address but to_address means we are paying "to" (someone) so I am not sure where to pass which address.] so where to pass owner's address as it is written in code but their is also to_address so I am confused with to_address and owner_address please help me to understand this, Thank you. -
Pre-populating Selected Values in Django Admin FilteredSelectmultiple Widget
I want to be able to set some default selected users on the right side of a Django Admin FilteredSelectMultiple widget. This is my model: class UserAdminForm(forms.ModelForm): users = forms.ModelMultipleChoiceField( queryset=User.objects.all(), widget=FilteredSelectMultiple("Users", is_stacked=False)) class Meta: model = User exclude = () Is there a way to do this with JavaScript so that I don't have to hand-select these defaults each time I create a new item? -
Not showing the Form in html
This is my model class showroom(models.Model): serialno=models.IntegerField(db_index=True,primary_key=True) carname=models.CharField(max_length=50) carmodel=models.CharField(max_length=50) price=models.IntegerField() rating=models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)]) This is my forms.py class RegisterForm(ModelForm): class Meta: model = showroom fields =("__all__") views.py class carform(CreateView): model = showroom form_class=RegisterForm template_name = "carbrand/carregister.html" context_object_name='registerform' html page {% block content %} {{registerform}} {% endblock content %} It's just showing a blank screen. I have imported all the necessary classes and views. It will make this too long for you so i removed it.can anyone please tell me if anything wrong in my view/form. -
How can i implement advanced search in django?
How can i implement advanced search like the below image in Django? I want the user can selects OR/AND operator. When I searched, I don't want the page to be refresh. What is the best technique for doing that? Ajax, rest framework, or other things...? -
How to remove the querysets '< [ <]>(code markers?)' for html (Django)
Am trying to just get a list of the made up gigs, (and hopefully make them links, to view them in a different html). Page result right now looks like this; <QuerySet [<Gig: Fulltime assistent needed from fall 2021!>, <Gig: Looking for event staff!>]> I don't know how to remove queryset 'code markers(or what are they called?)'. Just want the gig names listed. How can I fix that, to just show the gig titles? This is my code: Html: <div class="col"> {% if profile %} <div class="row justify-content-between"> <div class="col-9"> <p><b>My Gigs:</b></p> <p>{{profile.my_gigs}}</p> </div> <div class="col-3"> <p class="text-center"><b>No:</b></p> <p class="text-center"> {{profile.num_gigs}}</p> </div> <br> </div> {% endif %} </div> Views: def my_gigs(request): profile = Profileuser.objects.get(user=request.user) template = 'profileusers/my_gigs.html' context = { 'profile': profile, } return render(request, template, context) def create_gig(request): profile = Profileuser.objects.get(user=request.user) template = 'profileusers/create_gig.html' context = { 'profile': profile, } return render(request, template, context) Model: def my_gigs(self): return self.gig_set.all() @property def num_gigs(self): # pylint: disable=maybe-no-member return self.gig_set.all().count() -
django api for upload is very slow
My django api is soo slow when uploading files to a server, but very fast when using it on localhost. The api is supposed to receive files and save them to disk. I am expecting uploaded files to be between 70mb to about 600mb and save them in a storage. The files are binary files with a .svo extention created by stereolabs zed camera. Running this on localhost is very fast but when I deploy it to the server is becomes incredily slow. My internet speed is around 50mbps and the test file I am using is just 69mb. It takes over 24mins to upload the file, which is unacceptable. What could be the issue with why the uploading to the server is soo slow. This is my views.py to request and create a directory and save it import os import pathlib # external libraries from django.http import JsonResponse from rest_framework.views import APIView from django.core.files.storage import FileSystemStorage # environment variables from keys import USER_DIR # this is just a directory from .env class SaveRosBag(APIView): def post(self, request, *args, **kwargs): # integer_key & timestamp integer_key = self.kwargs['integer_key'] timestamp = self.kwargs['timestamp'] # required files if "zed_svo" in self.request.FILES: zed_svo = self.request.FILES["zed_svo"] else: … -
How to start Celery Beat with Supervisor
I am working on setting up Celery Beat with Supervisord. /etc/supervisor/conf.d/website.conf: [program:website-beat] command=bash /home/david/PycharmProjects/website/config/script.sh directory=/home/david/PycharmProjects/website user=www-data autostart=true autorestart=true stdout_logfile=/home/david/PycharmProjects/website/logs/celeryd.log [program:website] command=/home/david/PycharmProjects/website/venv/bin/celery -A config worker --loglevel=INFO -n worker1@%%h directory=/home/david/PycharmProjects/website user=www-data autostart=true autorestart=true stdout_logfile=/home/david/PycharmProjects/website/logs/celeryd.log redirect_stderr=true script.sh: #!/bin/bash cd /home/david/PycharmProjects/website/ source ../venv/bin/activate celery -A config beat -l info When I run sudo supervisorctl start all I get the output: website: started website-beat: ERROR (spawn error) When I run the script.sh file or celery -A config beat -l info manually, Celery Beat works. Thoughts on why this could be happening and how to fix it? -
Django how to use blocks in templates
Basicly my django project consists of the templates with html. I would like to fill the context of the site using blocks. My problem is that I would like to send the block to sidebar and the base part of the page from application's .html files. Templates: sidebar.html footer.html header.html base.html In my base.html I use: {% include 'partials/_sidebar.html' %} {% block content %}{% endblock %} in my sidebar.html I use {% block sidebar %}{% endblock %} and in my Application index.html i try to use: {% extends 'base.html' %} {% load static %} {% block content %} <h1>Home Page</h1> {% endblock %} {% block sidebar %} <div class="bg-white py-2 collapse-inner rounded"></div> <h6 class="collapse-header">Custom Components:</h6> <a class="collapse-item" href="{% url 'veggies' %}">veggies</a> <a class="collapse-item" href="{% url 'fruits' %}">fruits</a> </div> {% endblock %} But it is obviously not working. The starting page triggers app/index.html with a view. How to workaround such a problem? [i cant add post][1] [1]: https://i.stack.imgur.com/FV3Co.png -
I could not upload on wagtail admin when my project was deployed to Heroku
When I uploaded image files on wagtail, although it is going well to read image title but images itself was destroyed. so the titles is showed on the display of both admin and user side. I browsed through some blogs and websites on media and static, but this problem has not been resolved for almost three days. Development environment python==3.7.3 Django==3.2.6 gunicorn==20.1.0 psycopg2==2.9.1 wagtail==2.14 whitenoise==5.3.0 DB == postgres server == Heroku stack-18 my try and error ①added the follow code to urls.py python + static(settings.STATIC_URL, document_root=settings.STATICFILES_DIRS) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ②changed like follow application = get_wsgi_application() application = DjangoWhiteNoise(application) ↓ application = Cling(get_wsgi_application()) related code (those are possible to relate into this problem) #production.py from __future__ import absolute_import, unicode_literals import dj_database_url import os from .base import * #省略 STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' COMPRESS_OFFLINE = True COMPRESS_CSS_FILTERS = [ 'compressor.filters.css_default.CssAbsoluteFilter', 'compressor.filters.cssmin.CSSMinFilter', ] COMPRESS_CSS_HASHING_METHOD = 'content' #省略 #urls.py urlpatterns = [ path('django-admin/', admin.site.urls), path('admin/', include(wagtailadmin_urls)), ] + static(settings.STATIC_URL, document_root=settings.STATICFILES_DIRS) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #wsgi.py import os from dj_static import Cling from django.core.wsgi import get_wsgi_application application = Cling(get_wsgi_application()) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "squjap.settings.production") #base.py MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', ] STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(PROJECT_DIR, 'static')] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = … -
Django ModelAdmin get_urls not registering correctly
I'm trying to add a custom url and page to use to display certain data on the admin side of Django for a model of mine. Here is my code in admin.py class AdminUserEventHistory(admin.ModelAdmin): def get_urls(self): # get the default urls urls = super().get_urls() # define urls my_urls = [ path('userhistory/<int:pk>/>/', self.admin_site.admin_view(self.admin_user_event_view)) ] # make sure here you place the new url first then default urls return my_urls + urls def admin_user_event_view(self, request): context = {} context['history'] = None return HttpResponse('Success!') Then towards the bottom I register it with admin.site.register(EventAttendee, AdminUserEventHistory) The url should be /admin/events/eventattendee/userhistory/1/ if i'm not mistaken as I want it to take in the primary key of the user so I can pull info based on the user id. Sadly I am getting the following error. Event Attendee with ID “userhistory/1” doesn’t exist. Perhaps it was deleted? I do have two test records in that table and able to display them with the /admin/events/eventattendee/2/change. Did I miss something? This is all based on the Django documentation for 3.2 found here -
Django Circular Import Issue
so my django project was working completely fine and everything worked. I wanted to rename an app something else so I did and updated all the associated files in including the app.py config file. I also cleared the database and removed all migration files from each app. Ever since then I have never been able to finish makemigrations onto my apps. I even recreated the app I renamed, by doing django-admin startapp "appname" and then copied the contents of models.py admin.py, etc over to see if I somehow cause an internal issue but I just can't figure out what's going on?. I did manage to get all the makemigrations to success for all apps including the one I remade when I removed this (below) from another apps admin.py file # accounts/admin.py class SigBotSettingsInLine(admin.StackedInline): model = SigBotSettings @admin.register(Bot) class BotAdmin(admin.ModelAdmin,): ... inlines = [SigBotSettingsInLine] but in the end the python manage.py migrate, still Failed. If someone would help it would be highly appreciated. Here is the error-code: (dguacENV) PS C:\Users\Admin\Desktop\djangoProjects\dguac> python manage.py makemigrations accounts Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Admin\anaconda3\envs\dguacENV\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File … -
How to run periodic task using crontab inside docker container?
I'm building Django+Angular web application which is deployed on server using docker-compose. And I need to periodically run one django management command. I was searching SO a bit and tried following: docker-compose: version: '3.7' services: db: restart: always image: postgres:12-alpine environment: POSTGRES_DB: ${DB_NAME} POSTGRES_USER: ${DB_USER} POSTGRES_PASSWORD: ${DB_PASSWORD} ports: - "5432:5432" volumes: - ./db:/var/lib/postgresql/data api: restart: always image: registry.gitlab.com/*******/price_comparison_tool/backend:${CI_COMMIT_REF_NAME:-latest} build: ./backend ports: - "8000:8000" volumes: - ./backend:/code environment: - SUPERUSER_PASSWORD=******** - DB_HOST=db - DB_PORT=5432 - DB_NAME=price_tool - DB_USER=price_tool - DB_PASSWORD=********* depends_on: - db web: restart: always image: registry.gitlab.com/**********/price_comparison_tool/frontend:${CI_COMMIT_REF_NAME:-latest} build: context: ./frontend dockerfile: Dockerfile volumes: - .:/frontend ports: - "80:80" depends_on: - api volumes: backend: db: Dockerfile (backend): FROM python:3.8.3-alpine ENV PYTHONUNBUFFERED 1 RUN apk add postgresql-dev gcc python3-dev musl-dev && pip3 install psycopg2 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ ADD entrypoint.sh /entrypoint.sh ADD crontab_task /crontab_task ADD run_boto.sh /run_boto.sh RUN chmod a+x /entrypoint.sh RUN chmod a+x /run_boto.sh RUN /usr/bin/crontab /crontab_task RUN pip install -r requirements.txt ADD . /code/ RUN mkdir -p db RUN mkdir -p logs ENTRYPOINT ["/entrypoint.sh"] CMD ["gunicorn", "-w", "3", "--timeout", "300", "--bind", "0.0.0.0:8000", "--access-logfile", "-", "price_tool_project.wsgi> crontab_task: */1 * * * * /run_boto.sh > /proc/1/fd/1 2>/proc/1/fd/2 run_boto.sh: #!/bin/bash -e cd price_comparison_tool/backend/ python manage.py boto.py But when I …