Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Upload image from swagger_auto_schema
How to upload image from swagger UI? I am using DRF and drf-yasg Swagger. I want to upload image from request body. my current view.py: @api_view(['POST']) def image(request): profile_img = request.FILES.get('profile_img', '') cover_img = request.FILES.get('cover_img', '') ... pass Is it possible to upload image by: @swagger_auto_schema(method='post', request_body=openapi.Schema(type=openapi.TYPE_OBJECT, parameters={ 'profile_img': openapi.Schema(type=openapi.TYPE_FILE, description='Profile picture.'), 'cover_img': openapi.Schema(type=openapi.TYPE_FILE, description='Cover Photo.') }) ) @api_view(['POST']) def image(request): profile_img = request.FILES.get('profile_img', '') cover_img = request.FILES.get('cover_img', '') ... pass -
Django filter out on related field
I have three models, two of them linked to the third by a foreign key, as follows: class A(models.Model): sku = models.ForeignKey("SKU", on_delete=models.PROTECT) production_start = models.DateField(blank=True, null=True) production_end = models.DateField(blank=True, null=True) class B(models.Model): date = models.DateField() sku = models.ForeignKey("SKU", on_delete=models.PROTECT) quantity = models.PositiveIntegerField() last_modified = models.DateTimeField(auto_now=True) class SKU(models.Model): product = models.CharField(max_length=64) design = models.CharField(max_length=64) I would like to filter the foreign keys that can be returned in the A response in an efficient way, such that by defining a date range filter on the endpoint parameters (e.g., /A/?from_date=2021-01-01&to_date=2021-01-02), for all elements of A whose production dates fall within the range, I want it to return the object A containing the elements of B for the same SKU whose date matches the specific dates. Example: "data"=[ { "sku": 7, "production_start": "2021-01-01", "production_end": "2021-01-07", "b": [ { "date": "2021-01-01", "quantity": 100 }, { "date": "2021-01-02", "quantity": 200 } ] }, ... ] So far I've tried adding a filter from django-filters to my views.py. class AViewSet(viewsets.ReadOnlyModelViewSet): class AFilterSet(filters.FilterSet): from_date = filters.DateFilter(field_name="sku__b__date", lookup_expr="gte") to_date = filters.DateFilter(field_name="sku__b__date", lookup_expr="lte") class Meta: model = models.A fields = [] queryset = models.A.objects.all() serializer_class = serializers.ASerializer filterset_class = AFilterSet And my serializers.py: class BSerializer(serializers.Serializer): date = serializers.DateField() quantity … -
Python Permission Denied with ffprobe on NamedTemporaryFile
I'm trying to validate certain parameters of a media file before the file gets saved in Django. So I validate the file using ffprobe (from the ffmpeg pip package). with NamedTemporaryFile(suffix=f'.{self.audio.name.split(".")[-1]}') as fp: fp.write(self.audio.read()) try: # Get duration with ffprobe info = probe(fp.name) self.duration = info['format']['duration'] fp.close() except ffmpeg.Error as e: print('stderr:', e.stderr.decode('utf8')) raise NotAudioFile except: traceback.print_exc() raise NotAudioFile This is the snippet that validates the file. self.audio is a Django FileField. It creates a named temporary file, writes the file from the django file, and then validates it using ffprobe. However, when it runs, ffprobe gives me a Permission Denied error, which is weird, since I checked the file and I have full permission to write that directory/file. stderr: ffprobe version 4.3.2-2021-02-20-essentials_build-www.gyan.dev Copyright (c) 2007-2021 the FFmpeg developers built with gcc 10.2.0 (Rev6, Built by MSYS2 project) configuration: --enable-gpl --enable-version3 --enable-static --disable-w32threads --disable-autodetect --enable-fontconfig --enable-iconv --enable-gnutls --enable-libxml2 --enable-gmp --enable-lzma --enable-zlib --enable-libsr t --enable-libssh --enable-libzmq --enable-avisynth --enable-sdl2 --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxvid --enable-libaom --enable-libopenjpeg --enable-libvpx --enable-libass --enable-libfreetype --ena ble-libfribidi --enable-libvidstab --enable-libvmaf --enable-libzimg --enable-amf --enable-cuda-llvm --enable-cuvid --enable-ffnvcodec --enable-nvdec --enable-nvenc --enable-d3d11va --enable-dxva2 --enable-libmfx --enable-libgme --enable-libopenmpt --enable-libopencore-amrwb --enable-libmp3lame --enable-libtheora --enable-libvo-amrwbenc --enable-libgsm --enable-libopencore-amrnb --enable-libopus --enable-libspeex --enable-libvorbis --enable-librubberband libavutil 56. 51.100 / 56. 51.100 libavcodec 58. … -
Load data from models into HTML file by clicking button
I am trying to load data from my database into the same fields when a user clicks on load for a certain bla number. I am saving the data just fine and I can see it on the console but how do I get it to show up in the fields of the form? here is what I have: model: class Overview(models.Model): application_path = models.CharField(max_length=100) review_decision = models.CharField(max_length=100) bla_number = models.CharField(primary_key=True, max_length=100) applicant_name = models.CharField(max_length=200) prop_name = models.CharField(max_length=200) non_prop_name = models.CharField(max_length=500) obp_name = models.CharField(max_length=500) dosage_form = models.CharField(max_length=500) strength_potency = models.CharField(max_length=500) route_administration = models.CharField(max_length=500) primary_assessor = models.CharField(max_length=500) secondary_assessor = models.CharField(max_length=500) review_iteration = models.CharField(max_length=500) review = models.CharField(max_length=500) designation = models.CharField(max_length=500) def __str__(self): return self.applicant_name class Meta: db_table = 'kasaapp_overview' Form that is being saved is coming from this file: <form name="overviewForm" method="POST" action="overview#" id="overviewForm" onsubmit="return false"> {% csrf_token %} <!-- NDA Basic Information--> <div class="p-3"></div> <div class="container"> <div class="row"> <div class="col-lg-3"> <div> <label>Application path:</label> </div> </div> <div class="col-lg-9"> <select class="form-control form-control-sm" name="application_path" id="application_path"> <option selected disabled>Select option</option> <option>BLA under 351(a)</option> <option>BLA under 351(k)</option> <option>NDA under 505(b)(1)</option> </select> </div> </div> </div> <div class="p-3"></div> <div class="container review"> <div class="row"> <div class="col-lg-6 custom-control custom-radio"> <input type="radio" name="review" id="radio1" class="custom-control-input review" value="Priority Review"> <label class="custom-control-label" for="radio1">Priority … -
Django: Getting the currently logged-in user in Dash app
I am using Django-Dash-Plotly module and I am trying to grab the currently logged in user in the Dash app. I have a quick example below: import dash import io import spacy import base64 from dash.dependencies import Input, Output, State import dash_table import dash_core_components as dcc import dash_html_components as html import pandas as pd import time from django_plotly_dash import DjangoDash from sqlalchemy import create_engine import psycopg2 import datetime from django.contrib.auth import get_user_model User = get_user_model() users = list(User.objects.all()) print(users) Regarding the last 4 rows - users = list(User.objects.all()) gives me all available users. Is there any way to manipulate the code such that it only returns the currently logged in user and not every user that exists? Thanks -
Reference before assignment in Django
I am trying to display an error message if a request was not successful. I set a duplicate variable to False, and if an exception is thrown then the duplicate variable should be set to True. However, when the exception is triggered, duplicate will still return False. What am I missing? views.py def generate_hardware_milestone(request): get_request = request.POST.get('form') # creating a formset insert_formset = formset_factory(Forms, extra=0) formset = insert_formset(request.POST or None) duplicate = False try: if request.method == 'POST': if get_request: try: # Execute insertion except Exception as e: duplicate = True except Exception: # some code context = {'formset': formset, 'duplicate_error': duplicate} return render(request, 'example.html', context) -
Heroku - App not compatible with buildpack https://github.com/heroku/heroku-buildpack-python.git when uploading a Django-App
I'm new with Heroku and when I try to push my project to Github, I just get the error message: App not compatible with buildpack: https://github.com/heroku/heroku-buildpack-python.git Complete output: remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpack: https://github.com/heroku/heroku-buildpack-python.git remote: -----> App not compatible with buildpack: https://github.com/heroku/heroku-buildpack-python.git remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected remote: To https://git.heroku.com/appname.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/appname.git' I have a Procfile in my root: web:gunicorn Food_Blog.wsgi --log-file - Also I have a requirements.txt and runtime.txt file runtime.txt: python-3.8.1 Anyone an idea how to fix this issue? -
Export in csv a custom admin function
Here is my admin class : from django.contrib import admin from Engine.actions import export_as_csv_action # Register your models here. from .models import Bathroom # Register your models here. class Bathroom_Admin(admin.ModelAdmin): list_display = ("uuid", "nicole_user","modified","getcountproduct") search_fields = ("uuid","nicole_user__firebase_id","modified","getcountproduct") actions = [ export_as_csv_action( "CSV Export", fields=["uuid", "mireille_user","modified","getcountproduct"] ) ] def getcountproduct(self, obj): return obj.products.all().count() admin.site.register(Bathroom, Bathroom_Admin) Here is my action : import csv from django.http import HttpResponse from django.contrib import admin def export_as_csv_action( description="Export selected objects as CSV file", fields=None, exclude=None, header=True, ): """ This function returns an export csv action 'fields' and 'exclude' work like in django ModelForm 'header' is whether or not to output the column names as the first row """ def export_as_csv(modeladmin :admin.ModelAdmin, request, queryset): """ Generic csv export admin action. based on http://djangosnippets.org/snippets/1697/ """ opts = modeladmin.model._meta field_names = set([field.name for field in opts.fields]) many_names =set([field.name for field in opts.many_to_many]) print(many_names) print("opts") print(modeladmin) if fields: fieldset = set(fields) field_names = field_names & fieldset many_names = many_names & fieldset elif exclude: excludeset = set(exclude) field_names = field_names - excludeset many_names = many_names - excludeset print(many_names) response = HttpResponse(content_type="text/csv") response["Content-Disposition"] = "attachment; filename=%s.csv" % str( opts ).replace(".", "_") writer = csv.writer(response, delimiter=";") if header: list_all = list(field_names) + list(many_names) … -
How to fix special characters with python?
I have this problem with the special characters "ANTÔNIO GONÇALVES". How can I fix? I've tried using 'coding utf-8' but it didn't work. -
Django list_display highest value ManyToMany Field
I want to know how I can display the "highest value" from my ManyToMany Field in the admin. This is my models.py file: class Personal(models.Model): lastname = models.CharField(max_length = 100) firstname = models.CharField(max_length = 100) degree = models.ManyToManyField('Degree') def __str__(self): return self.lastname class Degree(models.Model): name_degree = models.CharField(verbose_name = 'Degree', max_length = 200, blank = False) rank = models.PositiveIntegerField(default = 0) def __str__(self): return self.name_degree In my backend, I have created different types of Degree's, all with a "ranking". In my case, the highest degree you can have is "Doctoral Degree", with a rank of "6". So if a User is creating himself in "Personal" he will have the option to select all the Degree's he has achieved. But for my Personal list, I just to want to see the highest one, e.g. if the User selects "Bachelor's Degree" and "Master's Degree", the Personal list should only contain "Master's Degree", because 5 > 4. Someone with an idea on how my admin.py file should look like? class PersonalAdmin(admin.ModelAdmin): list_display = ('lastname', 'firstname', ) # 'degree' Big thanks in advance! -
django-tz-detect save timezone to user model
I want to automatically save a user's timezone to their profile after it has been detected by the django-tz-detect package. Use case: I have a simple app that allows users to sign up and reserve time slots. Features: As little overhead as possible for users. Simply sign up with a name and email address, then click a button to reserve a time slot. Admin user can send email reminders to users when their time slots are approaching. Problem: The email sent to users is not formatted by their local time zone, as django-tz-detect is only concerned with the current timezone of that session. How can I format times in the user's local timezone in the reminder email? -
How can I add a bank transfer service to my django app
I am working on a stock trading app in django. I need to be able to give users the ability to transfer money from their current account into their brokerage account. What is the conventional way of doing this? For example, how does a platform like Robinhood transfer money from user's current account to their trading account? I am aware of payment services such as stripe, but this seems more tailored for ecommerce. -
failed to solve with frontend dockerfile.V0
I am pretty new to Docker and trying to build docker image with plain python django but i have this error message [+] Building 3.0s (3/3) FINISHED => [internal] load build definition from Dockerfile 0.7s => => transferring dockerfile: 224B 0.0s => [internal] load .dockerignore 0.9s => => transferring context: 2B 0.0s => ERROR [internal] load metadata for docker.io/library/python:3.9 1.7s ------ > [internal] load metadata for docker.io/library/python:3.9: ------ failed to solve with frontend dockerfile.v0: failed to create LLB definition: unexpected status code [manifests 3.9]: 403 Forbidden Dockerfile FROM python:3.9 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system COPY . /code/ -
Django images not uploading
I am working on a blog project where I am able to upload profile picture for each logged in user. Those uploaded profile photos are saving my django files. But for uploading a blog with images its not loading or saving, keeps warning "This field is required". Views.py class CreateBlog(LoginRequiredMixin, CreateView): model = Blog template_name = 'App_Blog/create_blog.html' fields = ('blog_title', 'blog_content', 'blog_image',) def form_valid(self, form): blog_obj = form.save(commit=False) blog_obj.author = self.request.user title = blog_obj.blog_title blog_obj.slug = title.replace(" ", "-") + "-" + str(uuid.uuid4()) blog_obj.save() return HttpResponseRedirect(reverse('index')) Models.py class Blog(models.Model): author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='post_author') blog_title = models.CharField(max_length=264, verbose_name="Put a Title") slug = models.SlugField(max_length=264, unique=True) blog_content = models.TextField(verbose_name="What is on your mind?") blog_image = models.ImageField( upload_to='blog_images', verbose_name="Image") publish_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) def __str__(self): return self.blog_title Settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_DIR = os.path.join(BASE_DIR, 'media') # MEDIA MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' Create_blog.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block title_block %} Write a Blog {% endblock title_block %} {% block body_block %} <h2>Start Writing:</h2> <form method="POST"> {{ form | crispy }} {% csrf_token %} <br> <button type="submit" class="btn btn-success btn-sm">Publish</button> </form> {% endblock body_block %} -
[Django Rest Framework]: How to additional phone_number field on Registration page?
I successfully created apis which can generate token on user login and register, also have a api page where i can display all the registered users (admin privileges required). But im not able to add a additional field like phone number on my register page. I need a phone number field as well on the registration page. Currently it has firstName, lastName, email and password. Models.py from django.db import models from django.contrib.auth.models import User from phonenumber_field.modelfields import PhoneNumberField class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_profile') phone_number = PhoneNumberField(blank=True, null=True) def __str__(self): return str(self.user) Serializers.py from rest_framework import serializers from django.contrib.auth.models import User from rest_framework_simplejwt.tokens import RefreshToken from .models import Profile class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' class UserSerializer(serializers.ModelSerializer): firstName = serializers.SerializerMethodField(read_only=True) lastName = serializers.SerializerMethodField(read_only=True) class Meta: model = User fields = ['id', 'username', 'email', 'firstName', 'lastName'] def get_firstName(self, obj): firstName = obj.first_name return firstName def get_lastName(self, obj): lastName = obj.last_name return lastName class UserSerializerWithToken(UserSerializer): token = serializers.SerializerMethodField(read_only=True) class Meta: model = User fields = ['id', 'username', 'email', 'firstName', 'lastName', 'token'] def get_token(self, obj): token = RefreshToken.for_user(obj) return str(token.access_token) Views.py from django.shortcuts import render from django.contrib.auth.models import User from .models import Profile from rest_framework.decorators import api_view, permission_classes … -
Dynamic Templates in Django Views
I am wondering whether it is possible to insert template names dynamically into Django views from urls.py. That is, suppose I have an app whose entire purpose is to serve as a container for various static landing pages. The plan is to create this app and have various entries in its urls.py correspond to paths to various landing pages. Each page would have a separate .html correspond to it. The question is whether one could get away with writing only one (class-based or other) view for all of these templates or would there need to be a view for each page? Django version 2.1-2.2 P.S. If there is an alternative, laconic way of accomplishing something similar, I am all ears. -
How to count clicks of a link and store in database(Django)?
How do I edit this code to count the times the "Link" was clicked and add this to the database model "T_shirt" in a new column? HTML <ul class="products"> {% for v in owner_obj %} <div class="container"> <a href={{ v.Link }} target="_blank" rel="noopener noreferrer"> <img src={{ v.Images }} width="150" height="150"> </a> <figcaption> {{ v.Titles }} </figcaption> <figcaption> <b>{{ v.Prices }} </b></figcaption> </div> {% endfor %} </ul> Models.py class T_shirt(models.Model): Images = models.ImageField() Titles = models.CharField(max_length=250, primary_key=True) Prices = models.CharField(max_length=250) Link = models.CharField(max_length=250) -
DRF + React.js Best Security Practise
Hello everyone i'm building a web-app with Django rest framework and react js. Back-end and front end are completely decoupled its pretty basic.React project created with npm create-react-app and DRF API is pretty standard i will use it to provide the info that front-end needs .So its both my resource and auth(which holds the users info and issues tokens etc.)server what is the best practice in 2021. bonus question I'm trying to implement Authorization code with PKCE and OIDC with django-oauth-toolkit.A high level of steps to do would be nice . for example i register an application on the admin interface and to get code http://127.0.0.1:8000/o/authorize/?response_type=code&client_id=<client_id>&redirect_uri=<redirect_uri> and i get an url with the grant code but only i'm logged in as admin user. (what good is that? I think i'm missing something here.) Also any help or information regarding the subject is much appreciated -
Setting a default value for an instance in django views
I am tracking histories on my models using simple history and this works fine.Problem is , some changes made to the models are done by the application and so do not have a history_user, thus return null. The result I get form the api in this case is as below. I am trying return the id of the history_user for those that have one and set the ones that are null to a specific id, say 1.But am struggling a bit. I have added a function get_history_user to return 1 in case the value is null .But the code just runs and returns the initial result with no errors.Can this work as it is? What am I doing wrong? { "invoice_history": [ { "history_id": 452, "history_user": 8, "history_type": "+", "history_date": "2021-04-28T13:22:16.045294+03:00", "id": 919 }, { "history_id": 451, "history_user": null, "history_type": "+", "history_date": "2021-04-28T13:22:15.572174+03:00", "id": 918 }, { "history_id": 450, "history_user": null, "history_type": "+", "history_date": "2021-04-28T13:22:13.477117+03:00", "id": 917 } ]} Views.py class AllHistoryView(APIView): def get(self, request, format=None): all_invhist = Invoice.history.all() serializers = InvoiceHistorySerializer(all_invhist, many=True) try: result = {} res = serializers.data result = res invoice_history = result[0:3] def get_history_user(invoice_history): history_user = invoice_history["history_user"] if isinstance(history_user, (float, int)): return history_user return 1 # … -
How to solve Django forms inline radio button bullet point problem
I'm try to use Django forms with radio buttons but if I like to use it as inline class I have bullet points in the row. How could I hide them? This is the result: models.py class Attitud(models.Model): def __str__(self): return str(self.user_name) class question(models.IntegerChoices): Nem_jellemző = 0 Néha_jellemző = 1 Nagyon_jellemző = 2 user_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1) att_v001 = models.IntegerField(verbose_name="Kérdés 1", default='', null=True, blank=False, choices=question.choices) forms.py class AttitudForm(forms.ModelForm): class Meta: model = Attitud fields = ['att_v001'] widgets = { 'att_v001': forms.RadioSelect(attrs={'class': 'form-check-inline ml-5'}) } html {% extends 'stressz/base.html' %} {% block body%} <div class="container w-75"> <div class="display-4">Helló {{ user.get_short_name}}! </div> <p class="text-justify">Kérlek, hogy az alábbi kérdések esetében válaszd ki, hogy melyek a rád leginkább jellemző kijelentések. </p> </div> <form method = "POST"> <div class="container w-75 bg-light rounded-3 pt-3"> <div class="form-group"> {% csrf_token %} {{ form.as_p }}<br> </div> <button class="btn btn-large btn-primary" type="submit">Mentés</button> {% comment %} {{ form.att_v001|crispy }} {% endcomment %} {% endblock %} -
Prevent Authenticated Users from accessing the inbuilt login form in djagno
I'm using Django's default login form from within a custom template.However,once a user logs in using this form,they can still go back to the login form.Now,I'm aware of a method to prevent something like this from happening: decorators. However,these decorators wont work on the way I'm rendering the login view.Have a look at the urls.py : from django.urls import path from . import views from django.contrib.auth import views as auth_views urlpatterns=[ path('',auth_views.LoginView.as_view(template_name='main/login.html')), path('home',views.home,name='home') ] Normally,decorators are imported within views.py and called right above the view function.This can't be done here. I dont know whether it will help,but here's the form part of 'main/login.html': <form method="POST" class=""> {% csrf_token %} <div class="form-group"> {{ form.username.label }}: {{ form.username }} </div> <div class="form-group"> {{ form.password.label }}: {{ form.password }} </div> <div class="form-group"> <input type="submit" class="login-input btn btn-warning" value="Login!" /> </div> </form> Thank you very much! -
Django FormViews displays dropdown menu instead of char- and textfield
I'm new to Django and I'm trying to use the FormViews but when I display the view it looks fine except the fields with a ForeignKey (companyAddress and companyContactInformation). Instead of creating a Char- and Textfields for each variable it just makes a dropdown field. I've looked into formsets, inline_formsets and model_formsets but can't seem to figure it out. from django.db import models from django.forms import ModelForm class address(models.Model): streetName = models.CharField(max_length = 45) houseNumber = models.CharField(max_length = 25) postalCode = models.CharField(max_length = 4) region = models.CharField(max_length = 45) def __str__(self): return '{} {} {} {}'.format(self.streetName, self.houseNumber, self.postalCode, self.region) class contactInformation(models.Model): phoneNumber = models.CharField(max_length = 11) email = models.CharField(max_length = 100) mainContact = models.CharField(max_length = 50) def __str__(self): return '{} {} {}'.format(self.phoneNumber, self.email, self.mainContact) class company(models.Model): companyName = models.CharField(max_length = 145) companyAddress = models.ForeignKey(address, on_delete = models.CASCADE) description = models.TextField() companyContactInformation = models.ForeignKey(contactInformation, on_delete = models.CASCADE) websiteURL = models.CharField(max_length = 100) relationToDjango = models.TextField() def __str__(self): return '{} {} {} {} {} {}'.format(self.companyName, self.companyAddress, self.description, self.companyContactInformation, self.websiteURL, self.relationToDjango) class addressForm(ModelForm): class Meta: model = address fields = '__all__' class contactInformationForm(ModelForm): class Meta: model = contactInformation fields = '__all__' class companyForm(ModelForm): class Meta: model = company fields = ['companyName', 'companyAddress', 'description', … -
can anybody help me to run this django github project in window?
I used these steps to run this projects: downloaded and extracted and opened with vscode created virtual env using virtualenv test after django installation pip install -r requirements.txt 4)after successfully installation of requirements showing not found two modules celery and dotenv The link of Github-project is given below: https://github.com/MicroPyramid/opensource-job-portal -
Celery Beat sending tasks on startup (before the scheduled time)
I have a celery beat schedule: CELERY_BEAT_SCHEDULE = { "test-task": { "task": "myapp.tasks.test_task", "schedule": crontab(hour=20), # Should execute at 8pm UTC! } } And when I execute the beat instance, with celery --app myapp beat --loglevel DEBUG The celery beat instance automatically sends the task to the broker: [2021-05-03 14:12:04,022: INFO/MainProcess] Scheduler: Sending due task test-task (myapp.tasks.test_task) Is there a way to prevent it? The task should only be executed at 8pm and never before that time. -
Critical Section across multiple EC 2 Instances
I have a code hosted on two different EC2 servers, and it might happen that the given code can be executed simultaneously on two different machines for certain set of variables. It will be ok for me if if they execute one by one. For .e.g my current sequence at two machines(A, B) runs like this, where CS gets executed simultaneously on both machines, depending on two conditions (say condition1, condition2) if condition1 and condition2 A1 B1 A2 B2 "CS" "CS" A3 B3 But what I am trying to do is something like: if condition1 and condition2 A1 B1 A2 B2 "CS" A3 "CS" B3 My code is hosted on Django. What can I do to prevent simultaneous execution.