Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django insert record
I am selecting a mark for every student and every core value then sending all data back to the database my main problem here is , i didnt get the right mark for every student and core value this is my html <form method="post" id="DogForm" action="/studentbehavior/" class="myform" style="width: 100%" enctype="multipart/form-data">{% csrf_token %} <table class="tblcore"> <input type="hidden" value="{{teacher}}" name="teacher"> <tr> <td rowspan="2" colspan="2">Core Values</td> {% for core in corevalues %} <td colspan="8"><input type="hidden" value="{{core.id}}" name="core">{{core.Description}}</td> {% endfor %} </tr> <tr> {% for corevalues in corevaluesperiod %} <td colspan="4" style="font-size: 12px"><input type="hidden" value="{{corevalues.id}}" name="coredescription">{{corevalues.Description}}</td> {% endfor %} </tr> <tr> <td colspan="2">Student's Name</td> {% for corevalues in period %} <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> {% endfor %} </tr> {% for students in student %} <tr> <td colspan="2" class="names"><input type="hidden" value="{{students.id}}" name="student">{{students.Students_Enrollment_Records.Students_Enrollment_Records.Students_Enrollment_Records.Student_Users}}</td> <td colspan="4"> <select name="marking"> <option>--------</option> {% for m in marking %} <option value="{{m.id}}" >{{m.Marking}}</option> {% endfor %} </select> </td> <td colspan="4"> … -
Can I run scripts at the click of a button in Django?
I want to run a script with a button click in Django. If you have any reference, please share it. -
In graphene-django, How can I use middleware to specific resolver
I want to set cookie by a resolver input value like: @decorator_from_middleware_with_args(TestMiddleare) def resolve_is_user_canary(self, info, user_token): return True Unfortunately, I can't get_response without middleware, what should I do to set a cookie without a global middleware? -
how to fill histroy chage reason in django simple history?
class ModelA(models.Model): name = models.CharField("Name", max_length=128) history = HistoricalRecords( history_change_reason_field=models.TextField(null=True)) I made a serializer : class ModelAHistorySerializer(serializers.Serializer): name = serializers.CharField() history_change_reason = serializers.CharField() history_date = serializers.DateTimeField() history_user = serializers.CharField() history_type = serializers.CharField() views : @action(methods=["GET"], detail=True) def history(self, request, *args, **kwargs): a = self.get_object() result = ModelA(a.history.all(), many=True).data return Response(data=result) this works at the point as it provides me name , history_user and history date but null value in change reason and type. Result: [ { "name": "john", "history_change_reason": null, "history_date": "2020-03-06T06:48:36.065985Z", "history_user": "admin", "history_type": "~" }, how to fill up override the change reason and type field??? -
vscode don't close all django(python) processes when I click stop button
VSCode Version: 1.42.1 OS Version: Ubuntu 18.04 Steps to Reproduce: Press Ctrl + F5 to run the django process. Click "stop" button to stop all django process. But there is still a process that has not been closed. -
How to send the image to API from modal window in Django?
I'm using Fengyuan Chen Image Cropper in Django. Here you can see more about it After cropping the Image, I want to send the image to API and get the response in JSON. This is how my views.py file looks like.. import json import urllib.request from .models import Photo from .forms import PhotoForm def photo_list(request): photos = Photo.objects.all() if request.method == 'POST': form = PhotoForm(request.POST, request.FILES) if form.is_valid(): if form.save(): data = get_json("http://127.0.0.1:5000/") return render(request, 'album/photo_list.html', {'form': form, 'photos': photos, 'data': data}) else: form = PhotoForm() return render(request, 'album/photo_list.html', {'form': form, 'photos': photos}) def get_json(url): html = urllib.request.urlopen(url) raw_json = html.read().decode('utf-8') forex_json = json.loads(raw_json) return forex_json And here is how my photo_list.html form code looks like.. <form method="post" enctype="multipart/form-data" id="formUpload" name="file"> {% csrf_token %} {{ form }} </form> Where "file" is the name of the key. I'm facing an issue where sending file using this form. ERROR :: raise exceptions.BadRequestKeyError(key) werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. KeyError: 'file' May be it's because it can't perform two tasks simultaneously. I'm new to Django. Any help will be really appreciable. Thanks -
csrf_exempt Decorator does not work in Dajngo function based views
I am using React with Django, most of the client server interaction is being done through the API using Django Rest Framework. I created a standard app called mail, it has a standard view which accepts a POST request with csrf_exempt and login_required decorators on it. However whenever making an ajax call through Axios it always gives me a 400 Invalid CSRF Token error - CSRF Cookie not specified. views.py from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt @login_required @csrf_exempt def testmail(request): if request.method=="POST": EmailQueue.objects.create(subject='TEST EMAIL BROTHER', body=render_to_string('nordalmail/testmail.html'), to_email=request.user.email, from_email=settings.FROM_EMAIL, send_now=True) return HttpResponse("CHECK ADMIN") if request.method == "GET": return render(request, "nordalmail/test-mail.html") React Component import axios from 'axios'; import {createMessage, returnErrors} from './messages.js'; import {tokenConfig} from './auth.js'; // Tokenconfig simply gets the Authorization Token and sends it as a Header value export const sendTestMail = () => (loggedUserEmail, getState) => { axios .post('http://alice:55403/nordalmail/', tokenConfig(getState)) .then(res => { createMessage("A test email has been sent to your registered email address!", "Email Sent"); }) .catch(err => { returnErrors("Something went wrong while sending your email, website administrator has been notified of this incidence!", "Error"); }); } Here's the Request I send Request URL: http://alice:55403/nordalmail/ Request Method: POST Status Code: 403 Forbidden Remote Address: 127.0.0.1:55403 Referrer … -
How to serve image from bucket in gcloud to opencv detect face method in view?
i have two methods one which sends the path of the newly uploaded image file by user from frontend to the other method which reads the image path by pre-appending the my storage path to detect the face from it. But in my case the cv.imread function is not considering the path to be an image but actually it is image path only because when i get the image when i directly write the path on browser url. OPEN CV IMAGE READ AND FACE DETECT def detect_im(request, pathname): rootpath = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) haar_file = rootpath + '\\face_detector\\haarcascade_frontalface_default.xml' datasets = 'datasets\\' myid = random.randint(1111, 9999) path = f"https://storage.googleapis.com/agevent269406.appspot.com/srv/face_detector/static/face_detector/datasets/{str(myid)}" face_cascade = cv2.CascadeClassifier(haar_file) newpath = f"https://storage.googleapis.com/agevent-269406.appspot.com/{str(pathname)}" //JOINING THE OBTAINED PATH WITH MY BUCKET PATH count = 1 while count < 30: im = cv2.imread(newpath, 1) gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) ... GET UPLOADED IMAGE PATH FROM USER AND SEND TO ABOVE METHOD def add_image(request): form = PicUpForm() if request.method == "POST": form = PicUpForm(data=request.POST, files=request.FILES) if form.is_valid(): picup = form.save() pathname = picup.picture item = detect_im(request, pathname) #SENDING THE IMAGE PATH FROM HERE TO ABOVE METHOD return item else: return render(request, "add_dataset.html", {"picform": form}) BUT I AM GETTING THIS ERROR Exception Type: error Exception Value: … -
Django Rest Auth: Customer Register Serializer not saving extra fields
NOT A DUPLICATE I am building a simple Todo app with Django & ReactJs, and i have ran into a problem with django-rest-auth. the problem is that my custom UserRegisterSerializer only saves a fragment of the request.dataand ignore the rest. and i have no idea why. Here's my code: User Model: class User(AbstractUser): id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False, db_index=True) first_name = models.CharField(max_length=100, blank=False) last_name = models.CharField(max_length=100, blank=False) email = models.EmailField(max_length=247, blank=False, unique=True, error_messages={ 'unique': _('A user with this email already exists.'), 'invalid': _('Invalid e-mail address detected.'), 'blank': _('this field may not be blank.') }) phone = models.CharField(max_length=20, blank=True, null=True, unique=True, error_messages={ 'unique': _('A user with this phone number already exists.'), }) gender = models.CharField(max_length=5, choices=GENDERS, default=NOOP) birthday = models.DateField(blank=True, null=True) @property def user_id(self): return self.id RegisterSerializer(Custom): class UserRegisterSerializer(RegisterSerializer): first_name = serializers.CharField( write_only=True, required=True, max_length=100) last_name = serializers.CharField( write_only=True, required=True, max_length=100) birthday = serializers.DateField(required=True, write_only=True) phone = serializers.CharField(max_length=20, write_only=True, validators=[ UniqueValidator( User.objects.all(), message=_('A user with this phone number already exists.') ) ]) gender = serializers.ChoiceField( write_only=True, choices=[ ('NO-OP', 'Rather not tell'), ('M', 'Male'), ('F', 'Female'), ], default='NO-OP' ) def get_cleaned_data(self): cleaned_data = super().get_cleaned_data() cleaned_data['first_name'] = self.validated_data.get('first_name', '') cleaned_data['last_name'] = self.validated_data.get('last_name', '') cleaned_data['phone'] = self.validated_data.get('phone', '') cleaned_data['birthday'] = self.validated_data.get('birthday', '') cleaned_data['gender'] … -
How to allow django view in nginx with PWA at /
I'm trying to setting up nginx to my PWA app with django backend. My django backend has some views to pdf reports on /export route. My PWA app (Vue) runs on /. I'm getting a blank page when access to /export. The blank page is trying to response from PWA, but when I reload with Shift (⇧) it loads the pdf report. Here is my nginx server config: server { server_name awesome.app; root /home/awesomeapp/pwa; location /api/ { include proxy_params; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://unix:/home/awesomeapp/awesome-backend/awesome.sock; } location /export/ { include proxy_params; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://unix:/home/awesomeapp/awesome-backend/awesome.sock; } location / { index index.html; } } Any idea how to setting up nginx to allow the access to the pdf report generated by django? Secondly, django backend also has a dashboard app (no pwa) but nginx does not allows to access it (only with shift(⇧)). -
Data from react axios post is not sending data to django
I am trying to send post data from react to django, however, the data is not attached to the post object. My react code looks something like this: class Homepage extends React.Component { createProject() { axios({ url: "localhost:8000/createProject/, headers: { "Content-Type": "application/json" }, data: { name: "projectname" }, }) } render() { return <div onClick={this.createProject}></div> } urls.py urlpatterns = [ path( "createProject/", views.createProject ), ] views.py def createProject( requests ): print( requests.POST ) return JsonResponse({"this returns": "just fine"}) output from print( requests.POST ) in views.py: <QueryDict: {}> If it matters, I'm using csrf_exempt on my django functions as there are no plans of deploying. Thanks! -
delendent dropdown in django(DJango,Python)
I want to make four drop down button(like country state city and location)each field we want to make it based on the selection like when country select its state related to country we get and when state is s selected then city related to these state gets populated when city get slelected then its loctation related to these city we get -
please give me advice with django admin
I'm new with python and Django. I know a lot about the Codeigniter framework and there if you want to create a project like an eCommerce you must create an admin panel with template and function for the backend. when I was creating backend I was adding functions for the admin panel where all functions were for adding some informations in the database. so when I start with Django I saw that there was an integrated admin panel which can be modified but I have a question can I create app for Django which will be admin panel of my project -
How do I make a user-specific database in Django?
so what I'm trying to do is make a user-specific dataset and show the data only to the user. You can think of social media. The layout is all the same, but what is shows is very much personalized to the user. I'm trying to do this with Django and PostgreSQL, but I have no idea on how to do this. Btw I'm a beginner, I've only took a few Django classes. So if there is any further knowledge that I have to learn, please let me know. I would very much appreciate your help or advice. :) -
ManagementForm data is missing or has been tampered with' while using Nested Django Formsets
I have been trying to use django forms in nested way. I have succesfully made the forms.py and models.py for the purpose but I have been struggling to Implement its html java script part. Now while saving the form I am getting an error "ManagementForm data is missing or has been tampered with'". I am not able to figure whether its views.py bug or my html/java script. I am a starter in django. Kindly help me to debug my code. models.py ``` from django.db import models # Create your models here. from django.contrib.contenttypes.models import ContentType # Create your models here. class courses(models.Model): name = models.CharField(max_length = 50) enter code here class topics(models.Model): name = models.CharField(max_length = 50) course = models.ForeignKey(courses,on_delete = models.CASCADE,null = True) class sub_topics(models.Model): name = models.CharField(max_length = 50) topic = models.ForeignKey(topics,on_delete = models.CASCADE,null = True) class course_to_topics(models.Model): serial_no = models.IntegerField() course = models.ForeignKey(courses ,related_name="course", on_delete = models.CASCADE,null = True) topic = models.ForeignKey(topics ,related_name="topics", on_delete = models.CASCADE,null = True) class topics_to_subtopics(models.Model): serial_no = models.IntegerField() topic = models.ForeignKey(topics ,related_name="topic", on_delete = models.CASCADE,null = True) subtopic = models.ForeignKey(sub_topics ,related_name="subtopics", on_delete = models.CASCADE,null = True) forms.py from django.forms import ModelForm from django.forms import formset_factory, inlineformset_factory,modelformset_factory from .models import courses, topics, sub_topics, … -
Clear the cache for django rest framework
I set the cache with this @method_decorator class IssueViewSet(viewsets.ModelViewSet): queryset = Issue.objects.all() serializer_class = IssueSerializer @method_decorator(cache_page(60*60*2)) @method_decorator(vary_on_cookie) def list(self,request,*args,**kwargs): api/issue returns the cached objects correctly, But now I want to off the cache sometimes. I notices just api/issue?something off the cache though, I want to off the cache for api/issue. Is there any way to solve this?? -
Jinja2 set block not recognized in Django
I searched for 2 days before posting this, so I really hope its not a duplicate question. I am building my first Django site and after getting into it I realized I'd rather have the power of jinja2. I installed jinja2 to my virtual environment and made the necessary changes to django (see below). However, django appears to be rendering the template with the standard django template engine instead of jinja2. All of my code works as expected when using {% block content %} template content {% endblock content %} Instead of block, I am trying to use {% set %} template content {% endset %} so that I can duplicate a template in base.html. but I get this error: django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 7: 'set'. Did you forget to register or load this tag? [05/Mar/2020 22:27:37] "GET /bge/ HTTP/1.1" 500 161659 I made the following changes to my project to try and make jinja2 work: Settings: TEMPLATES = [ { 'BACKEND': 'django.template.backends.jinja2.Jinja2' , 'DIRS': [os.path.join(BASE_DIR, 'templates/jinja2')], 'APP_DIRS': True, 'OPTIONS': { 'environment': 'bge_app.jinja2.environment' }, }, { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [(os.path.join(BASE_DIR, 'templates')),], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] jinja2.py added to … -
How do i create a table using JSON in my views.py?
This is my views.py marking = StudentBehaviorMarking.objects.all() corevaluesdescription = CoreValuesDescription.objects.values('id', 'Description').distinct( 'Description').order_by('Description') period = gradingPeriod.objects.filter(id=coreperiod).order_by('Display_Sequence') studentcorevalues = StudentsCoreValuesDescription.objects.filter(Teacher=teacher).filter( GradeLevel=gradelevel.values_list('Description')) \ .values('Students_Enrollment_Records').distinct('Students_Enrollment_Records').order_by( 'Students_Enrollment_Records') student = StudentPeriodSummary.objects.filter(Teacher=teacher).filter( GradeLevel__in=gradelevel.values_list('id')) How do i create a table using this query that correspond each other? this is i want a result This is my models class CoreValues(models.Model): Description = models.CharField(max_length=500, null=True, blank=True) Display_Sequence = models.IntegerField(null=True, blank=True) . class CoreValuesDescription(models.Model): Core_Values = models.ForeignKey(CoreValues,on_delete=models.CASCADE, null=True) Description = models.TextField(max_length=500, null=True, blank=True) grading_Period = models.ForeignKey(gradingPeriod, on_delete=models.CASCADE) Display_Sequence = models.IntegerField(null=True, blank=True) class StudentBehaviorMarking(models.Model): Marking = models.CharField(max_length=500, null=True, blank=True) Non_numerical_Rating = models.CharField(max_length=500, null=True, blank=True) class StudentPeriodSummary(models.Model): Teacher = models.ForeignKey(EmployeeUser, on_delete=models.CASCADE,null=True, blank=True) Students_Enrollment_Records = models.ForeignKey(StudentSubjectGrade,on_delete=models.CASCADE) -
Error while creating a view and displays some errors which goes like explicit label and isn't inside the INSTALLED APPS
the Entire error message is: Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x000001967F417820> Traceback (most recent call last): File "C:\Users\ALEX GEORGE\Dev\cfehome\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\ALEX GEORGE\Dev\cfehome\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "C:\Users\ALEX GEORGE\Dev\cfehome\lib\site-packages\django\core\management\base.py", line 356, in check all_issues = self._run_checks( File "C:\Users\ALEX GEORGE\Dev\cfehome\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\ALEX GEORGE\Dev\cfehome\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\ALEX GEORGE\Dev\cfehome\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Users\ALEX GEORGE\Dev\cfehome\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Users\ALEX GEORGE\Dev\cfehome\lib\site-packages\django\urls\resolvers.py", line 254, in check for pattern in self.url_patterns: File "C:\Users\ALEX GEORGE\Dev\cfehome\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\ALEX GEORGE\Dev\cfehome\lib\site-packages\django\urls\resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\ALEX GEORGE\Dev\cfehome\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\ALEX GEORGE\Dev\cfehome\lib\site-packages\django\urls\resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "c:\python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\ALEX GEORGE\Dev\cfehome\src\trydjango\urls.py", line 19, in <module> from … -
why i cant save m2m relationships in Django 3
recently i have upgrade and app to django 3, and i'm using a many to many relationship to define the people i want to send and email, in this way: class Contact(Master): name = models.CharField(max_length=100, blank=True, null=True, verbose_name=_('name')) email = models.EmailField(verbose_name=_("Email"), max_length=70, db_index=True, unique=True) class Meta: verbose_name = _("contact") verbose_name_plural = _("contacts") def __str__(self): return "{} - {}".format(self.name, self.email) class Newsletter(Master): template = models.CharField(verbose_name="template",max_length=100,null=True,blank=True) subject = models.CharField(max_length=100,null=False) text_content = models.TextField(blank=True,null=True) send = models.BooleanField(db_index=True,default=True) contacts = models.ManyToManyField('contacts.Contact', blank=True, related_name="contacts", verbose_name=_('contacts')) i make all the migrations and everything looks normal, but when i try to add contacts to the newsletter, via "admin" or "shell" it shows this error: ProgrammingError at /es/admin/contacts/newsletter/4/change/ syntax error at or near "ON" LINE 1: ... ("newsletter_id", "contact_id") VALUES (4, 1861) ON CONFLIC... the complete traceback error shows this Traceback (most recent call last): File "/home/beren5000/lib/python3.8/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.SyntaxError: syntax error at or near "ON" LINE 1: ... ("newsletter_id", "contact_id") VALUES (4, 1861) ON CONFLIC... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/beren5000/lib/python3.8/django/db/models/fields/related_descriptors.py", line 944, in add self._add_items( File "/home/beren5000/lib/python3.8/django/db/models/fields/related_descriptors.py", line 1123, in _add_items self.through._default_manager.using(db).bulk_create([ File … -
How To get Values of One View Function into Another View Function In django
def index_view(request): emp_data2 = {'eno':101,'ename':'john','esal':3000,'eadd':'uk'} return render(request,'TestApp/index.html',{'emp_data2':emp_data2}) trying to add above emp_Data2 to below view but its returning None def some_view(request): data = request.GET.get('emp_data2') render(request,'TestApp/some.html',{'data':data}) -
Last index value in Python Django View html
How to retrieve the last value of any array/dict/tuple? arr = [1,6,7,9,22] arr[-1] = 22 In Django view arr.0 gives the value 1 but cannot do arr.-1 or arr[-1] django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '-1.start' from 'vmd.-1.dstart' django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '[-1].start' from 'vmd[-1].dstart' I am looking to get the last value. -
Django SuspiciousFileOpretation at /admin/
I know many people asked this question. I have two laptops, one uses python 3.7 another one uses python 3.6. The code is the same, the second laptop raises this error. here is my file in admin: admin.site.register(File) in models class File(models.Model): files = models.FileField() settings BASE_DIR = os.path.dirname(os.path.abspath(__file__)) MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') any idea why I get this error when using python 3.6? -
Celery what happen to running tasks when using app.control.purge()?
Currently i have a celery batch running with django like so: Celery.py: from __future__ import absolute_import, unicode_literals import os import celery from celery import Celery from celery.schedules import crontab import django load_dotenv(os.path.join(os.path.dirname(os.path.dirname(__file__)), '.env')) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'base.settings') django.setup() app = Celery('base') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): app.control.purge() sender.add_periodic_task(30.0, check_loop.s()) recursion_function.delay() print("setup_periodic_tasks") My aim is whenever the celery file get edited then it would restart all the task -remove queued task that not yet execute(i'm doing this because recursion_function will run itself again if it finished it's job of checking each record of a table in my database so i'm not worry about it stopping mid way). The check_loop function will call to an api that has paging to return a list of objects and i will compare it to by record in a table , if match then create a new custom record of another model My question is when i purge all messages, will the current running task get stop midway or it gonna keep running ? because if the check_loop function stop midway looping through the api list then it will run the loop again and i will create new duplicate record which i don't want -
Running python manage.py test results in "Unittest.loader.__FailedTest"
I am trying to run test cases in my Django project using python manage.py test and I am getting Unittest.loader.__FailedTest. Here is project structure:- myproject/ myprojectservice/ __init__.py manage.py myprojectservice/ __init__.py tests/ __init__.py testmyproject.py None of the init files have anything in it. Is it because of same package and sub-package name? How do I resolve this?