Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make slight changes to objects related to each other without copying/creating new instances in Django
I have a Lessons Model, and I have a Challenges model. Right now they are related with foreign keys. So 1 lesson can have multiple challenges. My problem is that I want to re-use the Challenges objects in other lessons, but sometimes with very slight changes in the given challenge object. Up until now, I have just copied the challenge object, slightly changed it, and used that for the new lesson. The problem with this is that the database gets polluted with a bunch of similar objects, making it hard to scale with many lessons. -
Django: Project name is duplicated in the template path
My project structure is roughly as follows: dinnerproject/ dinnerproject/ settings.py dinners/ templates/dinners/ main.html templates/ base.html manage.py In settings.py I've got TEMPLATE configured like so: TEMPLATES = [ { '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', ], }, }, ] And dinners app is added to INSTALLED_APPS. I use a TemplateView with template_name = "main.html", which extends base.html. But when I try to open the page that's supposed to return main.html, I keep getting a TemplateDoesNotExist error saying: Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\Users\User\dinnerproject\dinnerproject\templates\main.html (Source does not exist) (...) django.template.loaders.app_directories.Loader: C:\Users\User\dinnerproject\dinnerproject\dinners\templates\main.html (Source does not exist) For some reason, my project name is duplicated in the paths, so django cannot find the right directories. What am I doing wrong? -
Django allauth-django Exception Type: KeyError at /accounts/signup/ Exception Value: 'username'
I'm trying to implement a Custom User Model for allauth-django, also adding custom form and other attributes. I'm getting the error when I'm adding the 'username' field on the form class so I can style it. I also changed allauth login to use email instead of a username, so username will be used for display only. Any idea what I'm doing wrong? setting.py SITE_ID = 1 AUTH_USER_MODEL = "xmain.User" ACCOUNT_USER_MODEL_USERNAME_FIELD = "username" ACCOUNT_USER_MODEL_EMAIL_FIELD = "email" AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ] ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_USER_MODEL_USERNAME_FIELD = "username" ACCOUNT_SIGNUP_REDIRECT_URL ="settings.LOGIN_REDIRECT_URL" ACCOUNT_USERNAME_BLACKLIST = ["admin","user"] ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 10 ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 1800 ACCOUNT_PASSWORD_MIN_LENGTH = 8 ACCOUNT_DEFAULT_HTTP_PROTOCOL = "https" ACCOUNT_LOGIN_ON_PASSWORD_RESET = True SOCIALACCOUNT_AUTO_SIGNUP = False ACCOUNT_FORMS = { 'login': 'xmain.forms.xMainLoginForm', 'signup': 'xmain.forms.xMainRegisterForm', } # Password validation AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] models.py from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser, PermissionsMixin ) from django.db import models # Create your models here. class UserManager(BaseUserManager): def create_user(self, … -
Python qrcode module generating qrcode with data not in source code
I'm creating an app for tracking stock using qr codes, I'm writing my app using Django and am using the qrcode module for generating qrcodes for items. In a previous version of my app the data I passed to the qrcode.make() function was different for the url it was representing. For some reason when generating the first wetsuit item, the qr code generated uses the old data for the url even though it's not present in my code. All other items work fine and any wetsuit instance after the first one generates a correct qr code with the correct data. My app is on my github here a folder named qrcodes in the static folder for the app to work correctly And the relevant code snippets: def generateQRCode(stockType, number, fileName): print(bcolors.OKGREEN+"Generating a new "+stockType+" QR code..."+bcolors.ENDC) #Generate qrcode from data qrData = 'http://192.168.0.72:8000/detail/'+stockType+'&'+str(number) print(bcolors.FAIL+qrData+bcolors.ENDC) qr = qrcode.make(qrData) print(bcolors.OKGREEN+"Saving generated QR code..."+bcolors.ENDC) path = 'static/qrcodes/'+fileName qr.save(path) if(exists(path)): return print(bcolors.OKBLUE+"Successfully generated and saved QR code!"+bcolors.ENDC) else: return print(bcolors.FAIL+"QR code failed to save!"+bcolors.ENDC) For some reason wetsuit instance 1's qrData is being generated as if the code below was written instead of what is in the snippet above: 'ip address'+stockType+'/'+brand+'&'+gender+'&'+size+'&'+number -
Django annotate average multiple columns
I have a model that has many to many fields to the same model class Project(models.Model): owner = models.ManyToManyField(User, related_name="owner_projects", blank=True) editor = models.ManyToManyField(User, related_name="editor_projects", blank=True) price = models.FloatField() So I am looking to return user average price, without knowing if the one is an owner or editor user_qs = User.objects.all().annotate( average_price = Avg(F('owner_projects') + F('editor_projects')) ) The problem is whenever one of the relationships is blank, the whole 'average_price' is returned as null. Is there a good way to average two columns on the database side? -
How to wrap a file downloading REST API with GraphQL?
I'm using Graphene and Django. And I tried to wrap the code below with GraphQL. def download(request): file_path = "/a/file/path/" if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 The wrapper looks like below (simply send an API call within the resolver): class Query(ObjectType): download_a_file = graphene.String(required=True) def resolve_download_a_file(root, info): url = info.context.build_absolute_uri(reverse("download")) response = requests.post(url) return str(response.status_code) If I send a GraphQL call, nothing is downloaded, I only get a 200 status code.If I use the REST API, I get the file. I'd like to know how I could get the file when calling the endpoint with GraphQL. -
what is the right way to use prefetch_related or select_related to achieve this in django
hey guys i have these models class Category(models.Model): name = models.charfield() class Product(models.Model): ...... class Order(models.Model): product = models.ForeigKey(Product) i want to fetch the product and the category of the product from an order instance in one query, i know that for forward foreignkey you should use select related but i don't think there's a way to fetch the product category when you use this: Order.objects.all().select_related('product') so is it right to use this one then: Order.objects.all().prefetch_related('product__category') -
Return existing csv file in django as download
I have a csv file in an assets folder with a few entries in my django project, and I want my angular frontend to be able to download this csv file. The existing examples show how to create a new csv file and send that, but I don't need to create a new csv file, I already have one, so how does the view/controller have to look? How can I return a csv file in django and make it able to be downloaded by my frontend? Please don't mention this reference, as it is not my intention to create a new csv file: https://docs.djangoproject.com/en/4.0/howto/outputting-csv/ -
I'm currently working on an online store website and I have a problem with updating the cart
views.py: from django.contrib.auth.decorators import login_required from django.shortcuts import render from .cart import Cart from product.models import Product def add_to_cart(request, product_id): cart = Cart(request) cart.add(product_id) return render(request, 'cart/partials/menu_cart.html') def cart(request): return render(request, 'cart/cart.html') def update_cart(request, product_id, action): cart = Cart(request) if action == 'increment': cart.add(product_id, 1, True) else: cart.add(product_id, -1, True) product = Product.objects.get(pk=product_id) quantity = cart.get_item(product_id) if quantity: quantity = quantity['quantity'] item = { 'product': { 'id': product.id, 'name': product.name, 'image': product.image, 'get_thumbnail': product.get_thumbnail(), 'price': product.price, }, 'total_price': (quantity * product.price) / 100, 'quantity': quantity, } else: item = None response = render(request, 'cart/partials/cart_item.html', {'item': item}) response['HX-Trigger'] = 'update-menu-cart' return response @login_required def checkout(request): return render(request, 'cart/checkout.html') def hx_menu_cart(request): return render(request, 'cart/partials/menu_cart.html') def hx_cart_total(request): return render(request, 'cart/partials/cart_total.html') cart.html: {% extends 'main/base.html' %} {% block title %}Shopping cart | {% endblock %} {% block content %} <div class="max-w-6xl mx-auto flex flex-wrap item-start py-6 px-6 xl:px-0"> <div class="products w-full lg:w-3/4"> {% for item in cart %} {% include 'cart/partials/cart_item.html' %} {% endfor %} </div> <div class="summary w-full md:w-1/4 p-6 bg-gray-100 rounded-xl mt-3"> <h2 class="uppercase text-lg mb-5">Summary</h2> <div class="mb-6 flex justify-between"> <span class="font-semibold">Total</span> <span hx-get="{% url 'hx_cart_total' %}" hx-trigger="update-menu-cart from:body" hx-swap="innerHTML"> {% include 'cart/partials/cart_total.html' %} </span> </div> <a href="{% url 'checkout' %}" class="inline … -
DRF - Relate an object to another using views, serializers and foreign key
Basically I have two models with one-to-one relationship. And I want retrieve information from one, when I call the other. My models: class Customer(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class CurrentAccount(models.Model): customer_account = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='customer_account', blank=True, null=True) balance = models.FloatField() So I can just call an POST and create an Customer, that customer will have id, first_name and last_name. For now everything is working. But when I try to call my endpoint to create an CurrentAccount informing my Customer to relate, nothing happens. My input: { "customer_account": 1 #this is some id from an Customer that is already created, "balance": 0.0 } The output that I expected: { "id": 42, "customer_account": { "id": 2, "first_name": "Michele", "last_name": "Obama" } "balance": 0.0 } The output that I received: { "id": 4, "balance": 0.0 } As you can see, Django are ignoring the relationship (In the database the field 'customer_account_id' is null too, so isn't just an problem with my return). Here is my serializers: class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = ('id', 'first_name', 'last_name') class CurrentAccountSerializer(serializers.ModelSerializer): customer_account = CustomerSerializer(read_only=True) class Meta: model = CurrentAccount fields = ('id', 'customer_account', 'balance') And my views to create the CurrentAccount: @api_view(['GET', … -
AUTH_USER_MODEL refers to model 'account_account.CustomUser' that has not been installed
I have checked solutions for the issue for two days only with failures. I have defined a customUser in my model.py to create a login system with email. The code snippet from the model is as following. class CustomUser(AbstractUser): email = models.EmailField(unique=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ("username", ) def __str__(self): return self.username also installed my app in settings.py added AUTH_USER_MODEL INSTALLED_APPS = [ 'account.apps.AccountConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ............. AUTH_USER_MODEL = "account.CustomUser" When I ran the migrations I got the following error: Traceback (most recent call last): File "F:\Ecom\my_env\lib\site-packages\django\apps\config.py", line 270, in get_model return self.models[model_name.lower()] KeyError: 'customuser' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "F:\Ecom\my_env\lib\site-packages\django\contrib\auth\__init__.py", line 170, in get_user_model return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) File "F:\Ecom\my_env\lib\site-packages\django\apps\registry.py", line 213, in get_model return app_config.get_model(model_name, require_ready=require_ready) File "F:\Ecom\my_env\lib\site-packages\django\apps\config.py", line 272, in get_model raise LookupError( LookupError: App 'account' doesn't have a 'CustomUser' model. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "F:\Ecom\ecomProject\manage.py", line 22, in <module> main() File "F:\Ecom\ecomProject\manage.py", line 18, in main execute_from_command_line(sys.argv) File "F:\Ecom\my_env\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "F:\Ecom\my_env\lib\site-packages\django\core\management\__init__.py", line 420, in execute django.setup() File "F:\Ecom\my_env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "F:\Ecom\my_env\lib\site-packages\django\apps\registry.py", … -
How to get total number
Kindly guild me on how to get the total number of loved clicked. See my attempt below, but it is not working. This is my model: class Review(models.Model): reviewer = models.ForeignKey(User, related_name='review', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='review', on_delete=models.CASCADE, null=True) date_time = models.DateTimeField(auto_now_add=True) comment = models.TextField(max_length=250, blank=True, null=True) rating = models.CharField(choices=RATING_CHOICES, max_length=150) loved = models.BooleanField(default=False) This is my view: class ListReviewAPIView(generics.ListAPIView): queryset = Review.objects.filter(loved="True").count() serializer_class = ReviewSerializers The serializers class ReviewSerializers(serializers.ModelSerializer): class Meta: model = Review fields = ['product', 'comment', 'rating', 'loved', 'date_time', 'reviewer'] -
SQL data base in Django
Please i have some issues if anyone can help me. I have an SQL data base (SSMS) with different tables contains data that i need for create reporting web application. I'll work with Django/python . But i noticed that in settings Django support just mysql,oracle,sqlite or postgres and there isn't SQL! How i can connect to my Data base SQL to get the data ? I tried many solutions from stackoverflow but doesn't work! Thanks in advance Settings file: DATABASES={ ENGINE :'sql_server.pyodb', PS: for enging i tried mssq too ERROR: django.core.exceptions.ImproperlyConfigured: 'mssql' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' -
Nested Serializers - how to access attrs from serializer's field during validate
I created nested serializers and during validate method in parent serializer I don't have any data from child serializer. When i raise error with 'attrs' as message then i get only data from 'pk' and 'name' fields. How can i get data from OpenningTimeSerializer in WarehouseSerializer? serializers.py class OpenningTimeSerializer(serializers.ModelSerializer): class Meta: model = OpenningTime fields = ['weekday', 'from_hour', 'to_hour'] class WarehouseSerializer(serializers.ModelSerializer): openning_time = OpenningTimeSerializer(many=True) class Meta: model = Warehouse fields = ['pk', 'name', 'openning_time'] def validate(self, attrs): raise serializers.ValidationError(attrs) -
interdicting django admin page except superuser
I made a web application called contact and I want to make it so that no one except the superuser can enter the admin page even by entering the url and after entering the url like : 127.0.0.1:800/admin then show them a 404 page or redirect to the home page. please help me !!! -
Get list of values from object in FastApi
I want to get list of values on a query instead of objects. Coming from a Django World I want to get something like values = list(MyModel.objects.filter(data=data).values('field_1', 'field_2')) Which would directly coming me something like values = [ { 'field_1': 'data_1', 'field_2': 'data_2' }, { 'field_1': 'data_1', 'field_2': 'data_2' } ] -
How to access a Uvicorn web server with it's domain name rather than it's IP address and port number?
I use uvicorn and Django to run an ASGI application and I would like to access the web server with it's domain name. I create a A record in the DNS server to point to the correct IP address and it is now reachable with http://my-domain.com:8000 How can I tell him to accept the URL without the port number ? The desired URL is http://my-domain.com This is how I run the server with systemd: uvicorn myapp.asgi:application --host 0.0.0.0 --port 8000 --lifespan off settings.py ALLOWED_HOSTS=['my-domain.com', '1.22.333.332'] Firewall rules : (env) user@ubuntu-1cpu-2gb-pl-waw1:/var/www/myapp$ sudo ufw status Status: active To Action From -- ------ ---- OpenSSH ALLOW Anywhere 8000 ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6) 8000 (v6) ALLOW Anywhere (v6) -
Django importing excel in not good format
I am a starting programmer and I need to create a site in django, with the ability to add an excel file, where some columns are merged, there is a header and convert it to a normal view. Can anyone please tell me some advices/books/paccages, that can help me to do this? The example of excel file in the screen below image Thank you very much! -
TypeError at /admin/ , 'QueryDict' object is not callable
I am getting this error when i am check this validation ,in django forms , how i can solve this error form.py d=[] b=[] my_tuple = [] for i in range(count): start_new = int(self.data.get(f'applicationruntime_set-{i}-start_new') or 0) start_old = int(self.data.get(f'applicationruntime_set-{i}-start_old') or 0) end_new = int(self.data.get(f'applicationruntime_set-{i}-end_new') or 0) end_old = int(self.data.get(f'applicationruntime_set-{i}-end_old') or 0) d.append((start_new,start_old)) b.append((end_new,end_old)) my_tuple.append((d[0],b[0])) for i in my_tuple[0]: my_result = [sub for sub in i if all(element >= 0 for element in sub)] if len(my_result)>2: raise ValidationError( f" Positive Start values and Positive End values are not allowed to be used in conjunction") -
I can only login with an administrator account but I need to do it with a custom user model
Users can register without any problem, but they cannot login, only a super user Im using a custom user model, so i can login with just the email and the password, i already tried using the django build-in templates for login but they doesn't work, it give the same error When i try to login as a normal user, it gives me this error <ul class="errorlist"><li>__all__<ul class="errorlist nonfield"><li>Invalid login</li></ul></li></ul> My models.py class CustomUserManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError("Users must have an email address") if not username: raise ValueError("Users must have a username") user = self.model( email = self.normalize_email(email), username = username, ) user.set_password(password) user.save(using = self.db) return user def create_superuser(self, email, username, password): user = self.create_user( email = self.normalize_email(email), password = password, username = username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using = self.db) class CustomUser(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=150, unique=True) username = models.CharField(max_length=150, unique=True) # password = models.CharField(max_length=150) date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = CustomUserManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin def … -
Why doesn't Azure show me my design files CSS, HTML, JavaScript
When I enter the command: 'az webapp up' My Django/Python site appears but with no design at all. When I enter the command: 'python manage.py runserver' in the terminal, the app works as usual with the design. Am I missing a command? Or maybe something in the settings is not correct? -
Django admin inlines: single inline for multiple foreign keys
I have a model that stores Conversations as follows: class Conversation: sender_user = models.ForeignKey("test_app.User", on_delete=models.PROTECT, related_name="conv_starter_user") recipient_user = models.ForeignKey("test_app.User", on_delete=models.PROTECT, related_name="conv_recipient_user") It references the User model twice. I would like to be able to go to Django Admin and see a section called 'Conversations' that would list all conversations that the user participates in, both as a starter and as a recipient. Currently, I am creating two separate inlines ConversationRecipientInline and ConversationSenderInline that I add to the User admin. This splits the Conversation view into two which is not ideal. -
Attempting to Bulk Update A Priority List - DRF
I'm attempting to Bulk Update my entire priority list. Here's the model: class OrderPriority(models.Model): order = models.OneToOneField(Order, related_name='priority_order', on_delete=models.CASCADE) priority = models.BigIntegerField(unique=True) Here's my Bulk Update Serializer and List Serializer Class: class BulkPriorityUpdateListSerializer(serializers.ListSerializer): def update(self, instances, validated_data): instance_hash = {index: instance for index, instance in enumerate(instances)} result = [ self.child.update(instance_hash[index], attrs) for index, attrs in enumerate(validated_data) ] writable_fields = [ x for x in self.child.Meta.fields if x not in self.child.Meta.read_only_fields ] try: self.child.Meta.model.objects.bulk_update(result, writable_fields) except IntegrityError as e: raise ValidationError(e) return result def to_representation(self, instances): rep_list = [] for instance in instances: rep_list.append( dict( id=instance.id, order=instance.order.id, priority=instance.priority, ) ) return rep_list class BulkOrderPrioritySerializer(serializers.ModelSerializer): class Meta: model = OrderPriority fields = ("id", "order", "priority") read_only_fields = ("id",) list_serializer_class = BulkPriorityUpdateListSerializer Here's my view along with the custom bulk update view: class CustomBulkUpdateAPIView(generics.UpdateAPIView): def update(self, request, *args, **kwargs): def validate_ids(data, field="id", unique=True): if isinstance(data, list): id_list = [int(x[field]) for x in data] if unique and len(id_list) != len(set(id_list)): raise ValidationError("Multiple updates to a single {} found".format(field)) return id_list return [data] ids = validate_ids(request.data) instances = self.get_queryset(ids=ids) serializer = self.get_serializer( instances, data=request.data, partial=False, many=True ) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return Response(serializer.data) class OrderPriorityUpdateAPIView(CustomBulkUpdateAPIView): serializer_class = BulkOrderPrioritySerializer def get_queryset(self, ids=None): return OrderPriority.objects.filter( id__in=ids, ) I then … -
How to define headers for authorization in django testing?
I want to write a test case for a function in my views in my Django project. I am just a beginner in this field, I have changed my settings.py and added the below line of code to the DATABASES dictionary, and also create a new user using MySQL shell based on this post: 'TEST': { 'NAME': 'test_sepantadb', } In function, there is a try/catch for checking the authorization using the request.headers. Here is the API code: @api_view(['GET']) def Get_users(request, **kwargs): try: user = request.headers['Authorization'] p = Profile.objects.get(username=user) except Exception as e: print(e) return Response(status=status.HTTP_401_UNAUTHORIZED) users = Device.objects.filter(owner=p) res = [] for u in users: user_inf = {} try: pdm = PersonDeviceMapper.objects.filter(device=u)[0] prof = pdm.person user_inf['name'] = prof.name user_inf['username'] = prof.username except Exception as e: print(e) user_inf['name'] = u.name user_inf['username'] = "default_" + str(u.id) user_inf['created_at'] = u.created_at user_inf['id'] = u.id user_inf['device_id'] = u.device_id res.append(user_inf) return Response(res) And here is the code in models.py for Profile class: class Profile(models.Model): GENDER_MALE = 1 GENDER_FEMALE = 2 GENDER_CHOICES = [ (GENDER_MALE, _("Male")), (GENDER_FEMALE, _("Female")), ] code = models.IntegerField(null=True, blank=True) username = models.CharField(max_length=128, null=False, blank=False, unique=True) password = models.CharField(max_length=128, null=False, blank=False) name = models.CharField(max_length=50, null=True, blank=True) lastname = models.CharField(max_length=50, null=True, blank=True) birthday = models.DateField(null=True, … -
How to make django_cron works in setted time
I have the following code: class ChangeStatusJob(CronJobBase): hours = [f"{str(el).zfill(2)}:30" if yel else f"{str(el).zfill(2)}:00" for el in range(0, 24) for yel in (0, 1)] schedule = Schedule(run_at_times=hours) code = "project.cron.ChangeStatusJob" def do(self): pass Cron doesn't work at a time which in run_at_times value and as a result, he works with a default 5 min delay. How to fix it? PS. cron should work every hour at **:00 and **:30