Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
File uploader is not showing in Swagger Django Rest-Framwork
I have created Rest API using Django rest-framework, when I am trying to test in with Swagger, it is not supporting FileField. in place of file uploader, it is showing text field. Here What I did - models.py class Document(models.Model): IS_DELETED = ( (True, True), (False, False), ) project = models.ForeignKey(Project, null=False, blank=False, on_delete=models.CASCADE) document_file = models.FileField(upload_to=PROJECT_DOC_PATH, null=False, blank=False) is_deleted = models.BooleanField(choices=IS_DELETED, default=False) created_by = models.CharField(max_length=500, null=True, blank=True) created_on = models.DateTimeField(null=False, blank=False, default=timezone.now) updated_by = models.CharField(max_length=500, null=True, blank=True) updated_on = models.DateTimeField(null=True, blank=True) serializers.py class DocumentSerializer(serializers.ModelSerializer): class Meta: model = DocumentTbl fields = ('project','document_file') views.py @method_decorator(csrf_exempt, name='dispatch') class Document(generics.CreateAPIView): renderer_classes = (JSONRenderer,) parser_classes = (FormParser, MultiPartParser,) permission_classes = (permissions.AllowAny, IsAuthenticated) serializer_class = DocumentSerializer def post(self, request): try: serializer = DocumentSerializer(data=request.data) if serializer.is_valid(): serializer.create(serializer.validated_data) return Response({ messages.RESULT: messages.SUCCESS, messages.MESSAGE: messages.SUCCESSFULLY_DATA_SAVE, }, status=status.HTTP_200_OK) else: return Response({ messages.RESULT: messages.FAIL, messages.RESPONSE_DATA: serializer.errors, messages.MESSAGE: messages.INVALID_DATA, }, status=status.HTTP_400_BAD_REQUEST) except Exception as ex: return Response({ messages.RESULT: messages.FAIL, messages.MESSAGE: messages.SERVER_ERROR + ', due to {}'.format(str(ex)), }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) urls.py urlpatterns = [ path('document/', Document.as_view(),name='document'), ] req.txt Python==3.x Django==2.2.5 django-cors-headers==3.1.0 django-rest-swagger==2.2.0 djangorestframework==3.10.3 djangorestframework-simplejwt==4.3.0 I have tried Django REST Framework + Django REST Swagger + ImageField but didn't solve my issue. Output -
Django: Is there a way to cancel an receiver triggering for a particular model signal?
I have a post_save signal receiver for a model in my domain. This receiver is triggered by many routines that run a save on that model (therefore I can't delete that receiver yet). I would like to cancel its triggering for a particular method that manipulates my model. Is that possible? I'm using Django 1.7 with Python 2.7 -
How to automatically update ForeignKeys to have ", on_delete=models.PROTECT"
I'm updating old code to the latest Django version. The ForeignKeys need ", on_delete=models.PROTECT". There are almost a hundred of them. How do I automatically add ", on_delete=models.PROTECT" to each one? -
How to change a value from in a django model while its foreign key?
Cart_Items , Cart , Order models .i want for my shopping website , that after a ordering a product , a value increased , but i cant access it . i tried to get it by pr=Products.objects.all() ci=Cart_Items.filter(product_id=pr) my models.py: order model: class Order(models.Model): user = models.ForeignKey(User,blank=True,null=True,on_delete=models.CASCADE) order_id = models.CharField( max_length=120,default="ABC",unique=True) cart = models.ForeignKey(Cart,on_delete=models.CASCADE) statu = models.CharField(max_length=120,choices=STATUS_CHOICES,default="Started") product model: class Products(models.Model): title = models.CharField(max_length=250) order_qty = models.IntegerField(default=0) Cart_Items model: class Cart_Items(models.Model): cart = models.ForeignKey('Cart',null=True,blank=True,on_delete=models.CASCADE) product_id = models.ForeignKey(Products,null=True,blank=True,on_delete=models.CASCADE) cart model : class Cart(models.Model): total = models.IntegerField(default=0) timestamp = models.DateTimeField(auto_now_add=True,auto_now=False) date = models.DateTimeField(auto_now_add=False,auto_now=True) isPaid = models.BooleanField(default=False) my views.py: def add(request): cart_items=Cart_Items.objects.all() for item in cart_items: print(item.product_id.order_qty) item.product_id.order_qty +=1 render(request,"home.html",{}) i want after ordering a product , order_qty , increased , how can i do that ? i must do it by Cart_items ? or there is another ways ? plz help. -
How to get related objects
I have 2 models : -products -review Every product have one or more revies/ Question : How i can get this related object's in view and pass him into template def product_detail(request, id, slug): product = get_object_or_404(Product, id=id, slug=slug, available=True) cart_product_form = CartAddProductForm() reviews = Review.objects.filter() template = 'shop/product/detail.html' return render_to_response(template, {'product': product, 'cart_product_form': cart_product_form, 'reviews': reviews}) class Review(models.Model): RATING_CHOICES = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), ) product = models.ForeignKey(Product, on_delete=models.CASCADE, default=None) user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) created = models.DateTimeField(auto_now_add=True, auto_now=False) text = models.TextField(max_length=500, blank=False) rating = models.IntegerField(choices=RATING_CHOICES, default=5) def __str__(self): return "%s" % self.user -
Is there a way to concatenate 2 model field names in the "list display" to display as one column in Django Admin?
In the Django Admin area, rather than have two separate columns for "first_name" and "last_name" to display, I'd like to concatenate those to create one column. I want to avoid creating a separate model field to get this done. One solution could be to return self, but that seems to not work either. The code below gets me "This site cannot be reached." admin.py from django.contrib import admin from .models import Agent class RealtorAdmin(admin.ModelAdmin): list_display = ('MLS_number', 'first_name' + 'last_name', 'email', 'phone', 'hire_Date') -
Exporting a field from another model, using foreign key
I've just set up the whole import-export thing and I just can't make it export a field from another model, using the foreign key. models.py from django.db import models from django.contrib.auth.models import User from datetime import date from .validators import validate_file_size # Create your models here. class CORMeserii(models.Model): CodCOR = models.CharField(max_length=25, primary_key=True, unique=True) MeserieCor = models.CharField(max_length=50, unique=True) def __str__(self): return str(self.CodCOR + " - " + self.MeserieCor) class Meta: verbose_name_plural = "CORuri" class Oferta(models.Model): solicitant = models.ForeignKey(User, on_delete=models.CASCADE) cor = models.ForeignKey(CORMeserii, on_delete=models.CASCADE) dataSolicitare = models.DateField(default=date.today) locuri = models.IntegerField() agentEconomic = models.CharField(max_length=50) adresa = models.CharField(max_length=150) dataExpirare = models.DateField() experientaSolicitata = models.CharField(max_length=200) studiiSolicitate = models.CharField(max_length=200) judet = models.CharField(max_length=20) localitate = models.CharField(max_length=25) telefon = models.CharField(max_length=12) emailContact = models.EmailField(max_length=40) rezolvata = models.BooleanField(default=False) def __str__(self): return str(self.cor) admin.py from django.contrib import admin from .models import Oferta, CORMeserii from import_export import resources from import_export.admin import ImportExportMixin, ImportExportModelAdmin import tablib # Register your models here. class CorImEx(resources.ModelResource): class Meta: model = CORMeserii class CorAdmin(ImportExportMixin, admin.ModelAdmin): list_display = ('CodCOR', 'MeserieCor') resource_class = CorImEx class CorImExAdmin(ImportExportModelAdmin): resource_class = CorImEx class OferteImEx(resources.ModelResource): class Meta: model = Oferta fields = ('id', 'solicitant', 'cor', 'oferta.cor.MeserieCor') class OfertaAdmin(ImportExportMixin, admin.ModelAdmin): list_display = ('id', 'solicitant', 'dataExpirare', 'dataSolicitare') resource_class = OferteImEx class OferteImExAdmin(ImportExportModelAdmin): resource_class = OferteImEx … -
Bootstrap Tabs preventing django model from saving
When I have the exact same code outside of a bootstrap tab, the model will save correctly, when I put the code into a tab, it stops saving the model. the post.request is showing all of the correct information in the correct format and when I loop through the request, I see all of the correct information. But it will not save the model's information to the database. I have tried only having one tab (with just the card information in it) and that doesn't work. I've tried having two tabs (and the first one, with different information, saves correctly) but the card information won't save. I've tried putting them in the same tag, and different ones, I've tried putting them all in the same form, and not in the same form. in the app/views.py settleCard = SettlementCard.objects.create( owner = client, cardNumber = request.POST.get('cardNumber'), nameOnCard = request.POST.get('cardName'), cardCvv = request.POST.get('cardCvv'), cardExpDate = request.POST.get('cardExpDate'), address1 = request.POST.get('address1'), address2 = request.POST.get('address2'), city = request.POST.get('city'), state = request.POST.get('state'), zipCode = request.POST.get('zipCode'), country = request.POST.get('country'), ) sellCardCount = SettlementCard.objects.filter(owner__pk=request.session.get('authId')) if sellCardCount == 0: settleCard.isPrimary = True settleCard.save() Not working HTML <div class="jumbotron"> <div class="container log-in" align="center"> <div class="tab" align="center"> <button class="tablinks" onclick="openTab(event, 'Card')">{% trans … -
How to delete existing image while uploading new image in django
Let say I have a model which has a profile pic image field.As a user I uploaded a profile pic.When I upload a new profile pic, old profile has to get deleted. How to handle this scenario in development and production stage -
How to check that Django model instance have preselected related data
Before Django 2.X I use this function for checking that ForeignKey and OneToOneField were prefetched to the Django model instance. def ensure_related(obj, field): field_obj = obj._meta.get_field(field) if hasattr(obj, field_obj.get_cache_name()): return True return False So for example In [1]: permission = Permission.objects.last() SELECT "auth_permission"."id", "auth_permission"."name", "auth_permission"."content_type_id", "auth_permission"."codename" FROM "auth_permission" INNER JOIN "django_content_type" ON ("auth_permission"."content_type_id" = "django_content_type"."id") ORDER BY "django_content_type"."app_label" DESC, "django_content_type"."model" DESC, "auth_permission"."codename" DESC LIMIT 1 In [2]: ensure_related(permission, 'content_type') Out[2]: False In [3]: permission = Permission.objects.prefetch_related('content_type').last() SELECT "auth_permission"."id", "auth_permission"."name", "auth_permission"."content_type_id", "auth_permission"."codename" FROM "auth_permission" INNER JOIN "django_content_type" ON ("auth_permission"."content_type_id" = "django_content_type"."id") ORDER BY "django_content_type"."app_label" DESC, "django_content_type"."model" DESC, "auth_permission"."codename" DESC LIMIT 1 SELECT "django_content_type"."id", "django_content_type"."app_label", "django_content_type"."model" FROM "django_content_type" WHERE "django_content_type"."id" IN (1) In [3]: ensure_related(permission, 'content_type') Out[4]: True But since Django 2.X this method always return True. My questions is: how since Django 2.X implement this check? -
How to retrieve a list of all available schedulers (django celery)?
Hi i want to create tasks from a fontend application. I want to retrieve a list of possible schedulers. By the celery documentation: schedule The frequency of execution. This can be the number of seconds as an integer, a timedelta, or a crontab. You can also define your own custom schedule types, by extending the interface of schedule. So i want a list of the default schedules (integer, timedelta, crontab) plus the user created ones that extends the schedule interfase. -
How to send an error message from the server to the client using django and print it to the console?
I have a server request that is supposed to find a file, if it doesn't find that file, in need to print in the js console a custom message saying "I couldn't find file x". I have tried raising exceptions, raising Http errors, sending custom requests.... But I have no idea how to send both an error (e.g 400, 404...) and a custom message associated with that error. The purpose of this is, when the XMLHttpRequest() object gets a response, if the status isn't 200, that;s when the error ought to be printed. I have no interest as to whether this is good practice or not, I just need to be able to do it somehow. -
Upload Multiple Images: Can't upload multiple images
I have been trying to code a Multi Upload for Images, my code only uploads 1 image even though more than 1 is selected, I don´t understand why request.FILES.getlist('picture') doesn´t work. I basically trying to use the code that appear in the Django documentation. models.py class Images(models.Model): session = models.CharField(max_length=50, blank=True) picture = models.ImageField(upload_to='photoadmin/pictures') created_date = models.DateTimeField(default=timezone.now) forms.py class UploadImages(forms.ModelForm): class Meta: model = Images fields = ('picture',) widgets = {'picture': forms.ClearableFileInput( attrs={'multiple': True})} views.py class Upload(FormView): form_class = UploadImages template_name = 'photoadmin/upload.html' success_url = 'photoadmin/' def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('picture') if form.is_valid(): for f in files: form.save() return render(request, 'photoadmin/index.html') else: return self.form_invalid(form) html {% extends 'base.html' %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> <p><a href="{% url 'index' %}">Return to home</a></p> {% endblock %} This code only uploads one image. thanks for your help. -
how to install satchmo project in django?
I'm having a problem with satchmo project in django. I want to know how do I install it properly to see it working. So far what I have tried is that I have created a directory store and installed satchmo in that. But from the Satchmo documentation it's not very clear what do I have to do after that. -
django mptt change selected value of TreeNodeChoiceField
I'm trying to use Django MPTT to display a list of nested categories in a select form using TreeNodeChoiceField forms.py class CategoryForm(forms.ModelForm): class Meta: model = Category fields = [] category = TreeNodeChoiceField(queryset=Category.objects.all(), label='') When I render the form in the template, I get the following select As you can see the selected option contains dashes and I haven't figured out how to change it. It would be nice if I can change it to a more meaningful name like "Category" -
Create sub-folders inside app Templates in Django
I've created a sub-folder name Housekeeping inside Properties in my templates folder as can be seen in the picture below. I've done it to better organize things. Problem The situation here is that my UpdateView looks for the template inside the app folder Properties and not inside Housekeeping. This ends up showing me this error: TemplateDoesNotExist at /properties/1/housekeeping/housekeeper/edit properties/propertyhousekeeper_update_form.html Which in fact makes sense.. If I move the file to inside the properties folder it works fine. For reference: #views.py class HousekeeperUpdateView(UpdateView): # login_url = '/login/' redirect_field_name = 'properties/housekeeping/housekeeping.html' template_name_suffix = '_update_form' form_class = HousekeeperAddForm model = PropertyHousekeeper Is there a way to do this? Or can it be done? -
Page not found (404) URLconf
when i run the server this show up Page not found (404) Using the URLconf defined in notes.urls, Django tried these URL patterns, in this order: admin/ notes/ The empty path didn't match any of these notes urls.py from django.contrib import admin from django.urls import include , path urlpatterns = [ path('admin/',admin.site.urls), path('notes/', include('notes_app.urls')) ] notes_app urls.py from django.contrib import admin from django.urls import include , path urlpatterns = [ path('admin/',admin.site.urls), path('notes/', include('notes_app.urls')) ] view from django.shortcuts import render from django.http import HttpResponse from .models import Note # Create your views here. ## show all notes def all_notes(request): # return HttpResponse('<h1> Welcome in Django Abdulrahman </h1>' , {}) all_notes = Note.objects.all() context = { 'all_notes' : all_notes } return HttpResponse (request , 'all_notes.html' , context) ## show one note def detail(request , id): note - Note.objects.get(id=id) context = { 'note' : Note } return render(request,'note_detail.html' , context) image -
GET http://localhost:8000/project:slug
Running localhost:8000/random-string returns "page not found" I believe my code is all running smoothly because if it wasn't I don't think when I run manage.py runserver it will load my local host successfully. There's another post which I believe the issue is similar and pointed to something in the codes environment not being set up correctly. I've tried to follow the answer from other issue but that didn't quite work for me. To provide more context this is how the error message looks like in my CMD: financio>manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). September 12, 2019 - 17:37:26 Django version 2.2.5, using settings 'financio.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: /random-string [12/Sep/2019 17:37:30] "GET /random-string HTTP/1.1" 404 2327 Within my budget folder which is nested in the parent folder I have my urls.py: from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.project_list, name='list'), path('<slug:project:slug>', views.project_detail, name='detail') ] When I run localhost:8000/random-string it is meant to load the following page project-detail.html: {% extends 'budget/base.html' %} {% block content %} <div class="container"> <section class="section section-stats"> <div … -
add to wishlist function didn't work properly as i wanted
This add_to_wishlist return two messages and eventually get_or_create act like this. But i want if an item added first time it shows "added" and next time "already added" but it return both when i click to the button. How i checked or make a query that it return me it added firstime. i used get_or_create method. As far as i know when there is no existence of an item it will create one and if already exits it will get or override the item. I have try it in add_to_cart and it worked perfectly. here is the model class Wishlist(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) wished_item = models.ForeignKey(Item,on_delete=models.CASCADE) slug = models.CharField(max_length=30,null=True,blank=True) added_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.wished_item.title here is the function @login_required def add_to_wishlist(request,slug): item = get_object_or_404(Item,slug=slug) wished_item,created = Wishlist.objects.get_or_create(wished_item=item, slug = item.slug, user = request.user, ) messages.info(request,'The item was added to your wishlist') wish_list_qs = Wishlist.objects.filter(user = request.user, slug=item.slug) if wish_list_qs.exists(): messages.info(request,'The item was already in your wishlist') return redirect('core:product_detail',slug=slug) it shows both messages .... but I want one according to the action either added the first time or added again The item was added to your wishlist The item was already in your wishlist -
how to save data of form wizard data in database in django
i want make add profile page in multiple steps and of that page when user submits their form and then this data is saved to database of django admin ## forms.py ## class FormStepOne(forms.Form): firstname = forms.CharField(max_length=100) lastname = forms.CharField(max_length=100) phone = forms. CharField(max_length=100) email = forms.EmailField() class Meta: model = FormStepOne fields = ['firstname', 'lastname', 'phone', 'email'] class FormStepTwo(forms.Form): skills = forms.CharField(max_length=100) salary = forms.CharField(max_length=100) job_description = forms.CharField(widget=forms.Textarea) class Meta: model = FormStepTwo fields= ['skills','salary','job_description'] ## views.py ## class FormWizardView(SessionWizardView): # # def done(self,request, form_list, **kwargs): # return render(self.request, 'accounts/online/profile.html', { # 'form_data': [form.cleaned_data for form in form_list], # }) # # if request.method == 'POST': # form = FormStepOne(request.POST) # if form.is_valid(): # form.save() # firstname = form.cleaned_data.get('firstname') # lastname=form.cleaned_data.get('last_name') # # messages.success(request, f'You successfully registered!') # return redirect('online_dashboard') # context={'form:from'} # else: # form = () # return render(request, 'accounts/online/firststep.html', {'form': form, 'title': ' Sign Up'}) this is my first time on stackoverflow so help me out of this problem and thanks in advance -
How to to forbid access my site from ip address+port using nginx?
I have a django app with gunicorn running on port 2333.In nginx.conf I set server { listen 80; server_name mydomain.com; location / { proxy_cache my_cache; proxy_set_header REMOTE-HOST $remote_addr; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://127.0.0.1:2333; expires 30d; } now I can view my django app on address http://ipaddress:2333 and mydomain.com but I don't want users to view my site by http://ipaddress:2333 .How to allow nginx only use mydomain.com to access my site. I have tried to use "server default".It not worked. server { listen 2333 default; server_name _; return 500; } -
R Reverse for 'results' not found. 'results' is not a valid view function or pattern name
I am learning django framework and i am getting an error " Reverse for 'results' not found. 'results' is not a valid view function or pattern name." I am including my code here. "results.py" {% extends "polls/base.html" %} {% block main_content %} <h1>{{question.question_text}}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{choice.choice_text}} -- {{choice.votes}} vote{{choice.votes|pluralize}}</li> {% endfor %} </ul> <a href="{% url 'polls:details' question.id }">Vote again</a> {% endblock%} "views.py" from django.shortcuts import render,get_object_or_404 from django.http import HttpResponse,HttpResponseRedirect # from django.core.urlresolvers import reverse from .models import Question from django.urls import reverse def results(request,question_id): question=get_object_or_404(Question,pk=question_id) return render(request,"polls/results.html",{"question":question}) def vote(request,question_id): question=get_object_or_404(Question,pk=question_id) try: selected_choice=question.choice_set.get(pk=request.POST['choice']) except: return render(request,"polls/details.html",{'question':question,"error_message":"Please select a choice"}) else: selected_choice.votes+=1 selected_choice.save() return HttpResponseRedirect(reverse("polls:results",args=(question.id,))) -
Only last form in the inlineformset_factory is saved
I am getting only the last form using inlineformset_factory. Here is is codes. I have tried with different answers but couldn't find my own bug. Is it something with js script or anything else? Please help me to find it. model.py from django.db import models # Create your models here. class DAILY_REPORT(models.Model): report_date = models.DateField() # AutoNow = True sets the time when the object created district = models.CharField(max_length=100) def __str__(self): return f"{self.district}" class GURUTTOPUNNO_NIYOMITO_MAMLA(models.Model): daily_report = models.ForeignKey(DAILY_REPORT, on_delete=models.CASCADE) mamlar_number = models.DecimalField(max_digits=10, decimal_places=2, null=True) # ejaharer_description = models.TextField() # ejaharer_ashami_number = models.DecimalField(max_digits=10, decimal_places=2) # greptarer_number_ejahar = models.DecimalField(max_digits=10, decimal_places=2) # greptarer_number_shondhigdho = models.DecimalField(max_digits=10, decimal_places=2) # uddhar = models.DecimalField(max_digits=10, decimal_places=2) # comment = models.DecimalField(max_digits=10, decimal_places=2) class DOINIK_GREPTAR(models.Model): daily_report = models.ForeignKey(DAILY_REPORT, on_delete=models.CASCADE) da_b_dhara_290 = models.DecimalField(max_digits=10, decimal_places=2) forms.py from django import forms from django.forms import modelformset_factory, ModelForm, inlineformset_factory from .models import DAILY_REPORT, DOINIK_GREPTAR, GURUTTOPUNNO_NIYOMITO_MAMLA class DAILY_REPORT_FORM(ModelForm): district = forms.CharField(label='জেলার নাম') #widget=forms.Textarea(attrs={"placeholder":"জেলার নাম"})) report_date = forms.DateField() class Meta: model = DAILY_REPORT fields = [ 'district', 'report_date' ] class DOINIK_GREPTAR_FORM(ModelForm): class Meta: model = DOINIK_GREPTAR fields = '__all__' class GURUTTOPUNNO_NIYOMITO_MAMLA_FORM(ModelForm): class Meta: model = GURUTTOPUNNO_NIYOMITO_MAMLA exclude = ('daily_report',) GURUTTOPUNNO_MAMLA_FORMSET = modelformset_factory(GURUTTOPUNNO_NIYOMITO_MAMLA, form=GURUTTOPUNNO_NIYOMITO_MAMLA_FORM, exclude=('daily_report',),extra=1) # class WeeklyProgressReportForm(forms.ModelForm): # class Meta: # model = WeeklyProgressReport # fields = … -
Use a For loop to save fields from a database into a numpy array
I have a database that is filled with values from a numpy array that gets its data from the face_recognition image. The fields in my database are as follows: f1: (double) f2: (double) ... f128: (double) i want to retrive this points and save them into a numpy array, to fill this numpy array im using a for loop: for x in range(0, 129): result = face.f1 known_image = np.append(known_image, result) What i need is to be able to change that face.f1 for face.f2 in the second loop and so on. Note that f1,f2... are values already stored in the database. -
How to achieve below objective.?
I am using celery with Django. Redis is my broker. I am serving my Django app via Apache and WSGI. I am running celery in supervisor mode. I am starting up a celery task named run_forever from wsgi.py file of my Django project. My intention was to start a celery task when Django starts up and run it forever in the background (I don't know if it is the right way to achieve the same. I searched it but couldn't find appropriate implementation. If you have any better idea, kindly share). It is working as expected. Now due to certain issue, I have added maximum-requests-250 parameter in the virtual host of apache. By doing so when it gets 250 requests it restarts the WSGI process. So when every time it restarts a celery task 'run_forever' is created and run in the background. Eventually, when the server gets 1000 requests WSGI process would have restarted 4 times and I end in having 4 copies of 'run_forever' task. I only want to have one copy of the task to run at any point in time. So I would like to kill all the currently running 'run_forever' task every time the Django starts. …