Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django Admin site wrong foreign key values
I have 2 models listing and profile defined as below. Owner and location both are supposed to be taken from Profile. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, blank=True, null=True) location = models.CharField(max_length=200, blank=True, null=True, unique=True) class Listing(models.Model): owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.CASCADE) location = models.ForeignKey(Profile, blank=True, null=True, on_delete=models.CASCADE, related_name='rel_location') However, Whenever I am trying to create a new listing record, the location field only displays values from Owner column. How do I efficiently reference both columns add listing -
BrowsableAPI not working with functional views
How do I make BrowsableAPI work with functional views? For example, let's say I have @api_view(['GET', 'POST']) @csrf_exempt def snippet_list(request): """ List all code snippets, or create a new snippet. """ if request.method == 'GET': snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = SnippetSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) When I register in the url and acces it, the browser gives me the raw json, not the browsableapi version of it. How can I make it work? I looked up the documentation and posts but couldnt find anything, everyone is either using classes based or generics. I know this way of making views is not ideal, but I still want to know how to make a functional view "Browsable". -
Django: Set many-to-many value to a model
I am trying to test my Models Project, Category and Tag. I'm running into an issue when trying to add tags to my project model. It won't allow me to do it in the Project model itself for eg. self.project = Project.objects.create( ... tags=Tag.objects.create("HTML5"), ) Django docs suggest the I do it as below. However I can't "add" the Tag without saving the model and I can't save the model without adding the Tag Tests class ProjectTests(TestCase): def setUp(self): self.tag = Tag.objects.create(name="HTML5") self.project = Project( title="Oaks on Main Shopping Center", url="www.oaksonmain.co.za", image=SimpleUploadedFile( name="test-image.jpg", content=open( "static\\images\\test_images\\florian-olivo-4hbJ-eymZ1o-unsplash (1).jpg", "rb" ).read(), content_type="image/jpeg", ), description="Beautiful website created for Oaks on Main Shopping Center in Knysna!", category=Category.objects.create(name="Website"), ) self.project.save() <- Problem here self.project.tags.add(self.tag) <- Problem here def test_project_model(self): self.assertEqual(f"{self.project.title}", "Oaks on Main Shopping Center") self.assertEqual(f"{self.project.url}", "www.oaksonmain.co.za") self.assertEqual( f"{self.project.description}", "Beautiful website created for Oaks on Main Shopping Center in Knysna!", ) self.assertEqual(self.tags.count(), 3) self.assertEqual(self.category.count(), 1) self.assertEqual(self.image.count(), 1) def test_project_listview(self): resp = self.client.get(reverse("index")) self.assertEqual(resp.status_code, 200) self.assertContains(resp, self.project.title) self.assertTemplateUsed(resp, "page/index.html") Models class Project(models.Model): class Meta: ordering = ["-id"] # Always show latest projects first verbose_name_plural = "Projects" title = models.CharField(max_length=50) url = models.URLField() image = models.ImageField(upload_to=f"{title}/") description = models.TextField() category = models.ForeignKey("Category", on_delete=models.PROTECT, related_name="categories") tags = models.ManyToManyField("Tag", verbose_name="tags") … -
Why queryset.only() is ignored when using serializers?
Could you give me a hand with this issue please? I am using Django and REST Framework for my app. I want to retrieve distinct values of 1 column in a django model, for that I use a queryset with chained filters and a serializer with the option many=True. Here is my code: Specified queryset: queryset = CollectedCompaniesInfo.objects.all() queryset = queryset.only('branch').distinct('branch') Expected result: [{ "id": 16, "branch": "McDonald's" }, { "id": 80, "branch": "Wendy's" }] I am getting: [ { "id": 16, "branch": "McDonald's", "latitude": "35.94905003", "longitude": "-81.18771815", "state": "North Carolina", "address": "561 W Main Ave Taylorsville NC 28681 United States", "open_hours": "Mon-Sun 5 am - 11pm", "coordinate_x": 35.94905003, "coordinate_y": -81.18771815 }, { "id": 88, "branch": "Wendy's", "latitude": "35.24987478", "longitude": "-80.95769756", "state": "North Carolina", "address": "5501 Birmingham Pkwy Concourse A Charlotte NC 28208 United States", "open_hours": "Sun - Thu 6:30am -2am/Fri-Sat 6:30am -3am", "coordinate_x": 35.249874778495084, "coordinate_y": -80.95769756353488 }] Serializer code: serializer = CollectedCompaniesInfoModelSerializer(queryset, many=True) return Response(serializer.data, status=status.HTTP_200_OK) -
radio buttons with simple input
dear stackoverflow! Professionals, please help. i need to implement a form like this in Django: If a user enters something in the "another amount" field, the radio buttons become disabled. I really have no idea. my html: <div class="payment__amount"> <div class="payment__amount__1"> <div class="form-check payment__amount__check"> {{ form.amount_select.0 }} </div> <div class="form-check payment__amount__check"> {{ form.amount_select.1 }} </div> </div> <div class="payment__amount__2"> <div class="form-check payment__amount__check"> {{ form.amount_select.2 }} </div> <div class="form-check payment__amount__check"> {{ form.amount_select.3 }} </div> </div> </div> {{ form.amount_input }} my forms.py CHOISES = [ ('50', '50'), ('100', '100'), ('200', '200'), ('500', '500') ] class CheckoutForm(forms.Form): amount_select = forms.IntegerField(widget=forms.RadioSelect(choices=CHOISES)) amount_input = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': "another amount"})) Thank you very much! -
read from database and display as dictionary, not list
I've got a simple database with this table structure: ---------------- | A1 | A2 | A3 | |--------------| | B1 | B2 | B3 | | C1 | C2 | C3 | ---------------- Using this function and djangorestframwork: @api_view(['GET']) def read(request, source): if source not in sources: return Response({'error': f'{source} not found', 'allowed sources': sources, 'help': address}) with connect(f'{source}/news.db') as conn: cmd = '''SELECT * FROM newstable''' cur = conn.execute(cmd) results = cur.fetchall() rand_id = randrange(len(results)) return Response(results[rand_id]) the contant is displayed in json like this: [ 'B1', 'B2', 'B3 ] However, I want to get this: { 'A1': 'B1', 'A2': 'B2', 'A3': 'B3 } -
Store file if user confirms it
I am quite new to Django. Here is the issue I am having now. User will upload some data and file in a django form. But the data including file will not be uploaded unless user confirms it. Here is the flow: user enters some data and selects a file for upload the file will be viewed (the content of the file) to the user if user wills to upload that file only then the file will be uploaded else it will not upload to database. I hope that I can get some suggestions/ways of doing it. Having a tough time with it. Thank you for understanding -
Django rest API student mentor app where student can send question and mentor can view and answer
The task is to Implement API endpoints to post questions to Mentor. As a part of this code assessment, the following APIs are to be implemented to enable the corresponding actions Register User User Login Send Query to Mentor. Message includes document attachment also Respond to User Query (Mentor must be able to respond to all the queries received to him) Application shall have two roles: User and Mentor. (Mentor will be created by the System Admin) Please ensure you code is implemented using the following features Use customized user model and make email as username Use Django password validator. (Password should contain minimum 8 letters, 2 numbers and 2 special chars) Use JWT Authentication to protect the endpoints. Use DRF Exception Hander and return generic error response. Use Serializers to validate the user request Use multiple roles (e.g. USER, MENTOR,..) and the endpoints can be accessed based on the roles. Use SMTP email background(Gmail) and signals for notification (Optional) Log every endpoint access (Optional) Use Swagger for API documentation (Optional) -
My view object 'has no attribute' {my attribute} in Django
Background I'm trying to load a custom url (e.g. www.mysite.com/order-2523432) that will show a user details about their order. Problem I am trying to use the method order_id in my models.py in order to get the correct url. The problem is that I am getting the error: 'OrderDetailView' object has no attribute 'order_id' Does anyone know what I can do to get order_id to work? My views.py: class OrderDetailView(DetailView): model = Orders template_name = "customer/orders.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) try: context["orders"] = get_orders(self) except RequestException as e: logger.exception(e) return context My utils.py: def get_orders(orders): url = f"mysite.com/customer/{orders.order_id}" method = "GET" content_type = "application/json" header = Sender( credentials etc ).request_header response = requests.request( headers etc ) response.raise_for_status() return response.json() My models.py: class Orders(CustomModel): table_name = models.CharField(max_length=256, unique=True) @property def order_id(self): return f"order-{self.table_name}" def get_absolute_url(self): return reverse("order:edit", args=(self.id,)) -
Django ORM multiple inner join in query
I want to be able to do queries involving multiple inner joins using Django ORM, here's my model (showing only relevant fields) class Students(models.Model): class Status(models.IntegerChoices): preRegistered = 0 #No ha aceptado terminos y condiciones Enabled = 1 Disabled = 2 Suspended = 3 Test = 4 id = models.AutoField(primary_key=True) user = models.ForeignKey(Users, on_delete=models.CASCADE) trainingPath = models.ForeignKey(trainingPaths, on_delete=models.CASCADE) status = models.IntegerField(choices=Status.choices, default=0) creationDate = models.DateTimeField(auto_now_add=True) modificationDate = models.DateTimeField(auto_now=True) class Meta(): db_table = 'Students' class trainingPaths(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=70, blank=False, null=False) shortName = models.CharField(max_length=10, blank=True) creationDate = models.DateTimeField(auto_now_add=True) modificationDate = models.DateTimeField(auto_now=True) class Meta(): db_table = 'Training_Path' class Courses(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=70, blank=False, null=False) path = models.URLField(max_length=500, blank=True, null=True) shortName = models.CharField(max_length=6, blank=True) creationDate = models.DateTimeField(auto_now_add=True) modificationDate = models.DateTimeField(auto_now=True) course_image = models.URLField(max_length=200, blank=True) class Meta(): db_table = 'Courses' class CoursesXTrainingP(models.Model): id = models.AutoField(primary_key=True) trainingPath = models.ForeignKey(trainingPaths, on_delete=models.CASCADE) course = models.ForeignKey(Courses, on_delete=models.CASCADE) alternativeName = models.CharField(max_length=70, blank=True) order = models.PositiveIntegerField(blank=False) creationDate = models.DateTimeField(auto_now_add=True) modificationDate = models.DateTimeField(auto_now=True) class Meta(): db_table = 'Courses_X_Training_Paths' I want to get the information of the courses that a student has according to the value of the "trainingPath". this is my SQL query select courses.id, courses.`name`, courses.course_image from students join courses_x_training_paths on students.trainingPath_id = courses_x_training_paths.trainingPath_id … -
DRF Update Insert in ManytoMany, ForeignKey Relationship Models
I have six models, they are below: class Certificate(DateTimeLog): name = models.TextField(max_length=255) class Vacancy(DateTimeLog): name = models.CharField(max_length=255) parent_position = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name='sub_positions') class Region(DateTimeLog): name = models.CharField(max_length=255) class MaritalStatus(DateTimeLog): name = models.CharField(max_length=255) class Candidate(DateTimeLog): pin = models.CharField(max_length=16, unique=True) first_name = models.CharField(max_length=64, blank=True, null=True) last_name = models.CharField(max_length=64, blank=True, null=True) marital_status = models.ForeignKey(MaritalStatus, on_delete=models.SET_NULL, null=True, blank=True) certificate = models.ManyToManyField(Certificate, blank=True) class Candidacy(DateTimeLog): candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE) vacancy = models.ForeignKey(Vacancy, on_delete=models.CASCADE) work_region = models.ForeignKey(Region, on_delete=models.SET_NULL, null=True, blank=True) Now I want to handle, if candidate record exists(I am checking it with pin), then check and update Candidate related data. If a candidate does not exist create it. After the candidate is created or updated assign it to the candidacy. My Serializer looks like below: class CandidateSerializer(serializers.ModelSerializer): marital_status = MaritalStatusSerializer(required=False) certificate = CertificateSerializer(many=True, required=False) def create(self, validated_data): marital_status_data = validated_data.pop("marital_status") certificate_data = validated_data.pop("certificate") candidate = Candidate.objects.create(**validated_data) ms_o = MaritalStatus.objects.get(name=marital_status_data["name"]) candidate.marital_status = ms_o for certificate in certificate_data: certificate_o = Certificate.objects.create(**certificate) candidate.certificate.add(certificate_o) candidate.save() return candidate class Meta: model = Candidate fields = '__all__' depth = 1 class CandidacySerializer(serializers.ModelSerializer): candidate = CandidateSerializer() vacancy = VacancySerializer() work_region = RegionSerializer() def create(self, validated_data): candidate_s = CandidateSerializer() candidate_data = validated_data.pop('candidate') vacancy_data = validated_data.pop('vacancy') work_region_data = validated_data.pop('work_region') vac_o = Vacancy.objects.get(name=vacancy_data['name']) … -
When Displaying Django Variables, 'Could not parse the remainder' error
I have a Django app that is meant to display the records of certain people. Rather than making a template for each person's records, I wanted to create one view and one template that can display the records of different people dynamically by taking the person's name from a variable passed through the url. All of the rest of my code seems to run fine, but when I render the template the variables containing the person's information I get this error: Could not parse the remainder: '('first_name', flat=True)[0]' from 'modelname.objects.values_list('first_name', flat=True)[0]' I have stored information about the people in several different models which are contained in the records variable as a list. Firstname is the variable containing the name entered into the url by the user. Sorry if my code is ugly. Thank you for your time. views.py def records(response, firstname): #firstname is a variable containing the name entered into the url by the user #the function will check if a record model with that first name is in records #records is a list containing all record models foundmodel = False for i in range(len(records)): firstname = firstname[0].upper() + firstname[1:] #Makes first letter uppercase if firstname == records[i].objects.values_list('first_name', flat=True)[0]: modelname … -
I'm having an issue with my code @ Python django blog Getting this error : AttributeError: module 'django.contrib.auth.admin' has no attribute 'site'
I'm having an issue with my code @ Python django blog Getting this error : AttributeError: module 'django.contrib.auth.admin' has no attribute 'site' Errror as below File "/usr/lib/python3.8/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 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/martin/My-blog/mysite/urls.py", line 6, in <module> path(r'^admin/', admin.site.urls), AttributeError: module 'django.contrib.auth.admin' has no attribute 'site' My urls.py is as below from django.urls import include, path from django.contrib.auth import login from django.contrib.auth import admin urlpatterns =[ path(r'^admin/', admin.site.urls), path(r'^accounts/login/$', 'django.contrib.auth.views.login'), path(r'^accounts/logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}), path(r'', 'blog.urls'), ] -
Any Possibility to put condition on Password Required in Django Custom Auth?
I want the registered user to log in with the Email or PhoneNumber and the Password first. If the user forgot the Password then there should be the possibility to log in with OTP bypassing the Password which would be provided via SMS on the User Phone Number. So Is there any possibility to achieve that? Here are official docs where the password field is always required. https://docs.djangoproject.com/en/4.0/topics/auth/customizing/#a-full-example I know we can change the username to the email or for a phone number if we want but how do we put the condition to login with Password/Random OTP. So how we can achieve that? a suggestion would be appreciated. Thanks -
Can I access the users data on django admin while using django-allauth?
I am new, first question.. I have configured django-allauth on a django project. It is working fine front end. When I access the Django-admin interface with the superuser, I can access all sorts of things that django-allauth as added like : -accounts -social accounts :... -sites I cannot access to the normal user data, the one which is in a table called 'campfire-users' in the db (campfire being the name of the application). Normally it appears in a group called 'authentication and authorisation" where you find 'groups' and 'users'. I have also noticed that the name of the top level app which normally appears in the top left is not appearing 'application_name ADMIN' becomes ADMIN. Any clue ? -
Custom number of input in django admin
I'm just working on the Django admin page. It is just to collect data, so I'm using a simple model and Django admin to collect data. I've made a model using this code: Adjoining_land_cover_1 = models.CharField('Adjoining land cover 1', max_length=100) Adjoining_land_cover_2 = models.CharField('Adjoining land cover 2', max_length=100) Adjoining_land_cover_3 = models.CharField('Adjoining land cover 3', max_length=100) Adjoining_land_cover_4 = models.CharField('Adjoining land cover 4', max_length=100) My output is: My question is: I want it to be dynamic. Is it possible to first make one "Adjoining land cover" and have an add button that will create another field and add as many as possible? I don't mind saving each value using a comma. I appreciate any help you can provide. -
my pagination seems not to be working - DRF problem
I am trying to create an endpoint that returns a list of posts. I want lets say 2 posts per page (for testing only! I know its not that big of a number to cause problem!). here is my views.py class blogsViewSet(ModelViewSet): queryset = Posts.objects.all() serializer_class = PostSerializer pagination_class = pagination.CustomPagination def list(self, request): data = request.data uid = data['uid'] context = {"user": uid} blogs = Posts.objects.all() serializer = PostSerializer(blogs, many= True, context= context) return Response(serializer.data) here is my serializers.py class PostSerializer(ModelSerializer): isLiked = serializers.SerializerMethodField(method_name='check_react') totalLikes = serializers.SerializerMethodField(method_name='get_likes') totalComments = serializers.SerializerMethodField(method_name='get_comments') def check_react(self, post): userObj = Users.objects.get(userID = self.context['user']) #print(type(userObj)) if Likes.objects.filter(postID = post, userID = userObj).exists(): isLiked = Likes.objects.get(postID = post, userID = userObj) likeObj = LikeSerializer(isLiked) #print('isLiked: ', likeObj.data['isLiked']) return (likeObj.data['isLiked']) return(False) #print(isLiked) def get_likes(self, post): count = Likes.objects.filter(postID = post).count() return count def get_comments(self, post): count = PostsComments.objects.filter(postID = post).count() return count class Meta: model = Posts fields = '__all__' and, here is my pagination.py, from rest_framework import pagination class CustomPagination(pagination.PageNumberPagination): page_size = 2 page_size_query_param = 'page_size' max_page_size = 3 page_query_param = 'p' I am importing this class on views.py and it works as expected when I try to retrieve a list of users via userMVS class … -
Django: I am unable to login as "user" from the user login page (after manually creating user in the admin page)
I am new to Django and created a project where a separate login page is created for the user. The user credentials are already created in the admin page under Authentication and Authorization >> Users. When I use the same login credentials in the user login page and click "Log In" button, it redirects to the login page again and shows invalid credentials even for correct credentials. I checked the credentials by inspecting the page and checking in the network tab. It returned 200 status code for invalid and valid credentials. Please tell me if I am missing something as I am not able to sort this out after so much research. I have connected sqlite3 database to my project by separately downloading it and it opens up when I give python manage.py dbshell. Is there anything wrong with my database? Why am I not able to login as a registered user? Project name - Project1 and App name- Authenticator My project's urls.py file: from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views urlpatterns = [ path('admin/', admin.site.urls), path('', include('Authenticator.urls')), ] My app's urls.py file: from django.contrib import admin from django.urls import path, include … -
Publish Django project to windows host
I have completed my web page and I want to publish it on windows server, but I am getting HTTP Error 500.0 - Internal Server Error Youtube video link she watched for broadcast link This is the error I get -
Why is the Django ORM not saving my objects
I created a simple blog with DRF and vue. When trying to save my Category & Tag Models Django returns objects with a null id. However, when trying to save my post objects it works fine. Does anyone know what I'm doing wrong here? class Category(models.Model): name = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, unique=True, null=False) posts = models.ManyToManyField(Post, related_name='categories', blank=True) def __str__(self): return self.name def save(self, *args, **kwargs): # new if not self.slug: self.slug = slugify(self.name) After I create the model I don't expect the id, but once I save the model the ID should show. Here's the manage.py shell I get the same thing if I put it through the following serializer. class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = [ 'id', 'name', 'slug' ] I'm getting the same data back with I call my viewset endpoint as well. How do I go about getting django to generate the id's and save the models? I've tried to do it manually as well (after recreating the test db) and the results were the same. I've also tried deleting and rebuilding the migrations from scratch. For reference here is the post model class Post(models.Model): owner = models.ForeignKey(User, on_delete=models.PROTECT) title = … -
Admin page not opening?
TypeError at /admin/ 'set' object is not reversible Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 4.0.1 Exception Type: TypeError Exception Value: 'set' object is not reversible Exception Location: E:\Django Project\Ecom\venv\lib\site-packages\django\urls\resolvers.py, line 494, in _populate Python Executable: E:\Django Project\Ecom\venv\Scripts\python.exe Python Version: 3.9.6 Python Path: ['E:\Django Project\Ecom', 'C:\Python39\python39.zip', 'C:\Python39\DLLs', 'C:\Python39\lib', 'C:\Python39', 'E:\Django Project\Ecom\venv', 'E:\Django Project\Ecom\venv\lib\site-packages'] Server time: Thu, 27 Jan 2022 15:56:51 +0000 -
Django: Parameterized expand with newly created model object doesn't work
I am trying to test some django code. I want to use parameterized.expand to provide newly created Boat model objects to the method named test_method I create these model objects Boat in the test class's setUp method. My (flawed) understanding is the following: MyTestClass.setUp is run and it creates the Boat objects into the test database test_method is run for each group of variables in the parameterized decorator. Note, the parameterized decorator references the newly created Boat objects. What actually happens: parameterized decorator is instantiated at build time, before setUp is run an error is thrown because there are no Boat objects (because setUp hasn't run yet`) Here is the code: from core.models import Boat from parameterized import parameterized class MyTestClass: def setUp(self): Boat.objects.create() @parameterized.expand( [ [[Boat.objects.all()], 1], ] ) def test_method(self, list_of_boats, expected_number_of_boats]): assert len(list_of_boats] == expected_number_of_boats I get the error sqlite3.OperationalError: no such table: core_boat How do I use newly created model objects with parameterized.expand? -
Django supervisord and apscheduler
In Django project, have a supervisord than start apscheduler [program:apscheduler] command=/home/user/Project/.venv/bin/python manage.py runapscheduler In apscheduler I have one job: # runapscheduler.py import logging import sys from django.conf import settings from django.core import management from apscheduler.schedulers.blocking import BlockingScheduler from apscheduler.triggers.cron import CronTrigger from django.core.management.base import BaseCommand from django_apscheduler.jobstores import DjangoJobStore from django_apscheduler.models import DjangoJobExecution from django_apscheduler import util logger = logging.getLogger(__name__) def my_management_command(): management.call_command('MyCommand') # The `close_old_connections` decorator ensures that database connections, that have become unusable or are obsolete, # are closed before and after our job has run. @util.close_old_connections def delete_old_job_executions(max_age=604_800): """ This job deletes APScheduler job execution entries older than `max_age` from the database. It helps to prevent the database from filling up with old historical records that are no longer useful. :param max_age: The maximum length of time to retain historical job execution records. Defaults to 7 days. """ DjangoJobExecution.objects.delete_old_job_executions(max_age) class Command(BaseCommand): help = "Runs APScheduler." def handle(self, *args, **options): scheduler = BlockingScheduler(timezone=settings.TIME_ZONE) scheduler.add_jobstore(DjangoJobStore(), "default") scheduler.add_job( my_management_command, trigger=CronTrigger(hour="*", minute="*"), # Every hour id="MyCommand", # The `id` assigned to each job MUST be unique max_instances=1, replace_existing=True, ) logger.info("Added hourly job 'my_management_command'.") scheduler.add_job( delete_old_job_executions, trigger=CronTrigger( day_of_week="mon", hour="00", minute="00" ), # Midnight on Monday, before start of the next work week. … -
Python class variable usage across thread have different value
I'm getting confused about class variable access through multi-thread. I'm in a django application and I initialize a class at server startups to inject some configuration. Then on user requests I call some method on that class but the config is None. class SharedService: _queue_name = None @staticmethod def config(queue_name=None): if queue_name: SharedService._queue_name = queue_name print(SharedService._queue_name) # this print the "alert" @staticmethod def send_message(data): print(SharedService._queue_name) # this print None if usefull in the django settings class loaded at startup I do: SharedService.config(queue_name="alert") and in the user endpoint I just call: SharedService.send_message("blabla") I'm sure it did work previously, but we did update to python 3.10 and django 3.2 recently and might be related (or not!) -
How to group multiple functions for parallel execution with Celery?
I wanted to group multiple functions for parallel execution in Django within the transaction.on_commit function -however, I got TypeError: cannot unpack non-iterable int object I have tried to resolve this, but I now think I'm misusing one of the args. This was my initial approach: # tasks.py def func_a(keys: tuple, link_set: dict): # keys contain random integers as pk return def func_b(keys: tuple, link_set: dict): return def func_c(keys: tuple, link_set: dict): return I tried to call these in my signal like this: @receiver(post_save, sender=Foo) def start_task(sender, instance, created, **kwargs): if created: ... keys = (instance.pk, foo.pk) link_set = {} transaction.on_commit(lambda: group([ tasks.func_a.si(keys, link_set), tasks.func_b.si(keys, link_set), tasks.func_c.si(keys, link_set) ]).delay()) The 3 functions in tasks.py are independent of each other with no return value, putting them together into one incurs a little cost that I'd like to avoid- how best can I compose these functions for a faster response? Thanks