Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Connecting checkboxes to the database (Django, python, html)?
total noob here. I'm in my third week of a bootcamp and I'm trying to go a bit beyond what we've been taught by creating a to-do list page in which, once a user is finished with a task, they can check a checkbox, hit save, and the completion status of a task with be sent to the database. I'm running into a 404 error, which is raising a number of questions for me, in addition to the code just being noob-code to begin with. I welcome any corrections and explanations because this is all very new to me and I've done a lot of reading but there are still gaps in my understanding. I apologize if I don't even know how to ask what I want to ask. Again, this is only 3 weeks of coding for me... Related question: Let's say I want the website to be just one page. But I need to create a form and a view function for the checkbox POST... does this require me to also create a new path in the apps url.py? And/or a new html template? I just want to stay on the same page forever but is it the … -
One rest endpoint works just fine, other gives CORs error
I have a react client app and django server app. React app is running on port 9997 and server API is available on port 9763. Frontend is able to access some APIs while some APIs are failing with error: As you can see first URL works, but second does not: API that works React code: import axios from "axios"; // ... async getRestEndpoint1() { let url = '/app/api/rest_endpoint1/' const axiosInstance = axios.create(); try { const response = await axiosInstance.get(url, { params: { 'format': 'json', 'propId': this.props.routeProps.match.params.propId } } ) return response.data; } catch (err) { console.error(err); } } Django REST code: def getHttpJsonResponse(obj): resp = json.dumps(obj, default=str) return HttpResponse(resp, content_type="application/json", status=status.HTTP_200_OK) @api_view(http_method_names=['GET']) def getRestEndpoint1(request): entityId = request.GET['entityId'] headers = EntityObject.objects.filter(entity_id=entityId).all() resp = [] for header in headers: resp.append({ 'id': entity.id, 'subEntityName': header.subEntity_name}) return getHttpJsonResponse(resp) API that does not work React code: import axios from "axios"; // ... async getRestEndpoint2() { let url = '/app/api/rest_endpoint2/' const axiosInstance = axios.create(); try { const response = await axiosInstance.get(url, { params: { 'format': 'json' } } ) return response.data; } catch (err) { console.error(err); } } Django code: @api_view(http_method_names=['GET']) def getRestEndpoint2(request): # business logic return getHttpJsonResponse(respStatsJson) Both APIs are in same views.py file and … -
Nested List in Django Admin
I have two models, something like this: class Category(models.Model): title = models.CharField(max_length=32) date_created = models.DateTimeField(auto_now_add=True) class Post(models.Model): title = models.CharField(max_length=64) text = models.TextField() parent = models.ForeignKey(Category, on_delete=models.CASCADE) Please tell me, is it possible to display these models in the standard Django admin panel like this: perhaps there is some extension to implement verbose output? -
Image prediction Django API predicts same result and generates errors
I tried making an API with DJANGO which I call, the api has a function called predictimage which takes the image input from the website (choose file from device on website) and sends it to the api then processes the image (with mediapipe hands to draw a mesh on the image) and then calls the pretrained model and predicts what's in the image. The problem is that when I predict the first image from the website it works but when I try to choose another file (image) from device and predict another time, it doesn't draw the hand mesh correctly and doesn't make the right prediction (it predicts the same as the first CORRECT image) making the second prediction false. This sign is supposed to be A not B and the mesh is not drawn correctly ++IM MAKING THIS API TO CALL IT FROM DART CODE :) is there a solution for this too ? thanks This is the code #DJANGO from keras.models import load_model import cv2 import numpy as np from cvzone.HandTrackingModule import HandDetector import math import time from django.core.files.base import ContentFile from django.core.files.storage import default_storage from django.shortcuts import render import base64 #imageWhite=[] detector= HandDetector(maxHands=1) offset = 20 imgSize … -
Django-debug-toolbar return error while trying to see static files
I have django-debug-toolbar and everythings works fine except i try to see static files which uses on this page Pannel shows me how many static files are using on this page but i cant get info about them I got an error 400 Bad Request and error in terminal: django.core.exceptions.SuspiciousFileOperation: The joined path (/css/style.css) is located outside of the base path component (/home/kirill_n/PycharmProjects/my_proj/venv/lib/python3.10/site-packages/django/contrib/admin/static) Bad Request: /__debug__/render_panel/ GET /__debug__/render_panel/?store_id=62e0bb7a200049efa762b6b5d59c118f&panel_id=StaticFilesPanel HTTP/1.1" 400 2 settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_ROOT_FILES = os.path.join(BASE_DIR, 'static_src') STATICFILES_DIRS = ( 'static_src', ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'django.contrib.staticfiles.finders.FileSystemFinder', ) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') ALLOWED_HOSTS = ['*'] INSTALLED_APPS += [ 'debug_toolbar', ] MIDDLEWARE += [ 'debug_toolbar.middleware.DebugToolbarMiddleware', ] INTERNAL_IPS = [ '127.0.0.1', ] urls.py if settings.DEBUG: import debug_toolbar urlpatterns = [ path('__debug__/', include(debug_toolbar.urls)), ] + urlpatterns urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Is it possible to restrict admin (Django Administration) not to access to Users' private information (Journal entries) in Django?
I am currently developing a journal application with Django. As the journal entries would be a private thing. Is it possible to restrict admin not to access the Journal information? I have tried to add some codes in the admin.py, put it doesn't work. from django.contrib import admin from .models import Journal class JournalAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super().get_queryset(request) if request.user.is_superuser: return qs else: return qs.filter(user=request.user) admin.site.register(Journal, JournalAdmin) This code as well. from django.contrib import admin from .models import Journal class JournalAdmin(admin.ModelAdmin): def has_view_permission(self, request, obj=None): if obj and obj.user != request.user: return False return True admin.site.register(Journal,JournalAdmin) -
why showing this error [ WARN:0@11.723] global net_impl.cpp:174 setUpNet DNN module was not built with CUDA backend; switching to CPU
I have try this python code in local its trained and save the image but i have use server if its using same code the did not trained the image .plz advice me. its showing [ WARN:0@11.723] global net_impl.cpp:174 setUpNet DNN module was not built with CUDA backend; switching to CPU. I install python opencv-contrib-python.but again show. I try image upscale process using djano. but its successfully run on local but ubuntu server not running its before process its windup the process .plz advice me why its not trained? -
Follow button for a profile follows the wrong profile
When I click on the Follow button for Profile 2 for example, instead of Unfollow button to show on the Profile 2, it shows on Profile 1 (which is the currently logged in profile). Then, the followers (authours) count for Profile 1 and the following (fans) profile for Profile 1 count increases instead of just the following count for Profile 1 to increase. URLS.PY path("profile/<int:user_id>", views.profile, name="profile"), path("follow/<int:user_id>", views.follow, name="follow"), MODELS.PY class User(AbstractUser): authors = models.ManyToManyField( "self", blank=True, related_name="fans", symmetrical=False ) def __str__(self): return str(self.username) PROFILE.HTML {% if user.is_authenticated %} {% if user in profile.authors.all %} <a href="{% url 'follow' user.id %}" class="btn btn-primary">Unfollow</a> {% else %} <a href="{% url 'follow' user.id %}" class="btn btn-primary"> Follow </a> {% endif %} {% else %} <button class="btn btn-outline-primary">Message</button> <p class="text-muted"> please, login to follow </p> {% endif %} <ul class="about"> {% if profile.authors.count <= 1 %} <li><span>{{ profile.authors.count }}</span>Follower</li> {% else %} <li><span>{{ profile.authors.count }}</span>Followers</li> {% endif %} <li><span>{{ profile.fans.count }} </span>Following</li> {% if post_count <= 1 %} <li><span>{{post_count}} </span>Post</li> {% elif post_count >= 2 %} <li><span>{{post_count}} </span>Posts</li> {% endif %} </ul> VIEWS.PY def profile(request, user_id): profile = User.objects.get(pk = user_id) post_count = NewTweet.objects.filter(user = user_id).count() context = { "profile": profile, "post_count": … -
NoReverseMatch at /reset-password/... in Django
I'm new to Django; I get this error when I want to reset a user's password by using a code that is set to account in db. views class ResetPassword(View): def get(self, request, active_code): user : User = User.objects.filter(email_active_code__iexact=active_code).first() if User is None: return redirect(reverse('login-page')) else: reset_password_form = ResetPasswordForm() context={ 'reset_password_form' : reset_password_form, 'title': 'Reset My Password' } return render(request, 'account_module/reset_password.html', context) urls path('reset-password/<str:active_code>', views.ResetPassword.as_view(), name='reset_password') html <form action="{% url "reset_password" %}"> {% csrf_token %} {{ reset_password_form.label_tag }} {{ reset_password_form }} {{ reset_password_form.errors }} <button type="submit" class="btn btn-default">Reset My Password</button> </form> the active code that is set Would someone please take a look and help? Thank you. -
I'm working with a tutorial and I got the error: The view main.views.home didn't return an HttpResponse object. It returned None instead
Im creating a very simple Django Website but I keep getting the same problem. my views.py file is `from django.shortcuts import render from django.http import HttpResponse from .models import ToDoList, Item Create your views here. def index(response, id): ls = ToDoList.objects.get(id=id) return render(response, "main/base.html", {}) def home(response): return render(response, "main/home.html", {})` Ive checked all necesary indentation and syntax. Im actually following an online tutorial but I think there's the problem is from my code -
Use aggregate functions in subquery Dajngo
I'm trying to get the sum of the minimum values of an option price, grouped by option type, to use in a Subquery when displaying products, but I can't use the aggregate functions I need. My code: class ProductManager(models.Manager): def get_queryset(self): add_subquery = OptionOfProduct.objects.filter( product_fk_id=OuterRef('pk'), option_fk__required=True, price__isnull=False, option_fk__operation='add' ).values('option_fk').annotate( min_price=Min('price') ).values('min_price') # ^ I need to get Sum from this subquery results # it return structure like this: # <QuerySet [{'min_price': Decimal('200')}, {'min_price': Decimal('100')}]> lowest_option_price_subquery = OptionOfProduct.objects.filter( product_fk_id=OuterRef('pk'), option_fk__required=True, price__isnull=False ).values('product_fk').annotate( cheapest_equal_price=Min('price', filter=models.Q(option_fk__operation='equal')), cheapest_add_price=Subquery(add_subquery), cheapest_price= Case( When( cheapest_add_price__isnull=False, cheapest_equal_price__isnull=True, then=F('cheapest_add_price') + F('product_fk__price') ), When( cheapest_add_price__isnull=False, then=F('cheapest_equal_price') + F('cheapest_add_price') ), When( cheapest_add_price__isnull=True, then=F('cheapest_equal_price') ), default=F('product_fk__price') ), ).values('cheapest_price') return super().get_queryset().annotate( lowest_option_price_2=Coalesce( Subquery(lowest_option_price_subquery), F("price"), output_field=DecimalField(decimal_places=2, max_digits=9) ) ) -
How to validate JSON using serializers with rest_framework
i'm face with this problem : how to serialize list of int, string and bool using rest_framework ? Imagine this JSON : { "start_hour": "14:02:26", "DEVICE_INFO": [ "0101", true, 13 ] } I have tried ListSerializer(), ListField()... Any ideas ? -
A type errpr on my django admin site trying to load an image
TypeError at /media/images/Shirt_1.jpeg serve() got an unexpected keyword argument 'documents_root' Request Method: GET Request URL: http://127.0.0.1:8000/media/images/Shirt_1.jpeg Django Version: 4.2 Exception Type: TypeError Exception Value: serve() got an unexpected keyword argument 'documents_root' Exception Location: /Users/mac/Desktop/Duefex/myvenv/lib/python3.10/site-packages/django/core/handlers/base.py, line 197, in _get_response Raised during: django.views.static.serve Python Executable: /Users/mac/Desktop/Duefex/myvenv/bin/python Python Version: 3.10.9 Python Path: ['/Users/mac/Desktop/Duefex/ecommerce', '/opt/homebrew/Cellar/python@3.10/3.10.9/Frameworks/Python.framework/Versions/3.10/lib/python310.zip', '/opt/homebrew/Cellar/python@3.10/3.10.9/Frameworks/Python.framework/Versions/3.10/lib/python3.10', '/opt/homebrew/Cellar/python@3.10/3.10.9/Frameworks/Python.framework/Versions/3.10/lib/python3.10/lib-dynload', '/Users/mac/Desktop/Duefex/myvenv/lib/python3.10/site-packages'] Server time: Wed, 12 Apr 2023 09:37:21 +0000 Iran my server and trying to load my image but it didn’t work -
How to send an e-mail with image atachment using celery and dajngo?
I want to use celery for sending an e-mail with photo, but I am getting the "Object of type bytes is not JSON serializable" error. I just don't understand how to properly do it. As far as I see, celery doesn't support bytes. But I tried to convert it to string and get other error. views.py from main_app.tasks import send_creator_submission_email_task class BecomeCreatorView(TemplateView): template_name = 'become_creator.html' become_creator_form = BecomeCreatorForm success_url = reverse_lazy('index') def get(self, request, *args, **kwargs): form = self.become_creator_form() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.become_creator_form(request.POST, request.FILES) if form.is_valid(): photo = form.cleaned_data['photo'] send_creator_submission_email_task.delay(self.kwargs.get('slug'), photo.file, photo.name) messages.success(request, "Thank you!") return redirect(self.success_url) messages.error(request, "Error!") return render(request, self.template_name, {'form': form}) tasks.py @shared_task def send_creator_submission_email_task(slug, image_file, image_filename): return send_creator_submission_email(slug, image_file, image_filename) email.py def send_creator_submission_email(slug, image_file, image_filename): user = get_object_or_404(User, slug=slug) current_site = Site.objects.get_current().domain email_context = { 'current_site': current_site, 'user_email': user.email, 'user_slug': user.slug, 'approve_url': f"http://{current_site}{reverse_lazy('approve_user', kwargs={'slug': user.slug})}", "decline_url": f"http://{current_site}{reverse_lazy('decline_user', kwargs={'slug': user.slug})}" } html_message = render_to_string('email/admin_decision_email.html', email_context) plain_message = strip_tags(html_message) email = EmailMultiAlternatives( subject="New creator submission", body=plain_message, from_email=settings.DEFAULT_FROM_EMAIL, to=[settings.EMAIL_ADMIN], ) email.attach_alternative(html_message, "text/html") email.attach(image_filename, image_file.read()) email.send() If you want to recreate the case, these files are for you: forms.py class BecomeCreatorForm(forms.Form): photo = forms.ImageField( required=True, widget=forms.ClearableFileInput ) admin_decision_email.html {% autoescape off … -
How to prevent the user from seeing other subscribers email in Django
I created a django newsletter functionality where users subscribe and I use the emails subscribed to send the newsletter to those emails. Now the problem I want your help is when I send the newsletter to the subscribers the receiver can see other subscribers emails. I have tried to add BCC but still not working. bellow is my views.py def send_newsletter(request): if request.method == 'POST': subject = request.POST['subject'] body = request.POST['body'] from_email = settings.EMAIL_HOST_USER # get all subscribers' email addresses subscribers = Newsletter.objects.all() to_email = [subscriber.email for subscriber in subscribers] bcc = [instance.email if instance.email != from_email else None for instance in subscribers] html_message = get_template('newsletter/newsletter.html').render({'message': body}) # Create the email message object email = EmailMessage( subject, strip_tags(body), from_email, to_email, bcc, headers={'To': 'Undisclosed Recipients <{}>'.format(from_email)} ) email.content_subtype = 'html' email.attach_alternative(html_message, "text/html") email.send() # Save newsletter to database newsletter = NewsletterText.objects.create(subject=subject, body=body, status='Published') newsletter.save() messages.success(request, 'Newsletter sent successfully') return redirect('blog:home') return render(request, 'newsletter/send_newsletter.html') I also tried to use Undisclosed recipients as the code bellow shows def send_newsletter(request): if request.method == 'POST': subject = request.POST['subject'] body = request.POST['body'] from_email = settings.EMAIL_HOST_USER # get all subscribers' email addresses subscribers = Newsletter.objects.all() to_email = [subscriber.email for subscriber in subscribers] bcc = [] html_message = … -
Daterange not found in django
I am trying to build an app in my django. When I am trying to run the server it's showing the error of daterange module not found. i have installed daterange multiple time. what else could be the issue? This is the issue These are the folders Kindly let me know where and what I am doing wrong -
How to avoid similiar queries in for loop in django template
I have code with 2 for loops in django template which iterate my model and show info in template from that model But for some reason Debugger show me that i have similiar queries in my second for loop and i dont know how to avoid that template.html {% for info_list in details_list %} <tr> <td>{{ info_list.presence_info.object_presence }}</td> <td>{{ info_list.presence_info.counter_presence }}</td> <td>{{ info_list.work_date }}</td> <td>{{ info_list.amount_of_workers }}</td> <td> {% for sections in info_list.parts_with_sections.all %} {{ sections.presence_sections.name }} | {% endfor %} </td> </tr> {% endfor %} models.py class PresenceListInfo(models.Model): object_presence = models.ForeignKey(ObjectList, on_delete=models.CASCADE, verbose_name='Объект', default=None, null=True) counter_presence = models.ForeignKey(CounterParty, verbose_name='Контрагенты', default=None, null=True, on_delete=models.CASCADE) class PresenceDetailInfo(models.Model): presence_info = models.ForeignKey(PresenceListInfo, verbose_name='Объекты', default=None, null=True, on_delete=models.CASCADE, related_name='details_info') work_date = models.DateField(verbose_name='Дата', default=None) amount_of_workers = models.IntegerField(verbose_name='Количество работников', default=0) def parts_with_sections(self): return self.presence_sections_list.select_related('presence_sections') class PresenceSectionList(models.Model): presence_detail = models.ForeignKey(PresenceDetailInfo, on_delete=models.CASCADE, related_name='presence_sections_list') presence_sections = models.ForeignKey(CleanSections, blank=True, on_delete=models.CASCADE, null=True) views.py class ShowPresenceInfoList(ListView): model = PresenceDetailInfo template_name = 'common/presence_info.html' context_object_name = 'details_list' -
How do I set a one-to-many relationship in the Django database, so that the foreign key is the primary key?
enter image description here Here, for example, are such tables. When I connect them (it is necessary to connect them with such a connection), I get an error. This is what my code looks like from django.db import models class Pupil(models.Model): objects = models.Manager() last_name = models.CharField(max_length=15) first_name = models.CharField(max_length=15) id_control = models.IntegerField(unique=True, blank=False, null=False) class Control(models.Model): objects = models.Manager() id = models.ForeignKey('Control', on_delete=models.CASCADE, primary_key=True) answer_one = models.CharField(max_length=15) answer_two = models.CharField(max_length=15) answer_three = models.CharField(max_length=15) -
Not able to connect Django with rabbitmq using docker
I am trying to connect Django and rabbitmq using docker but I am getting this error "socket.gaierror: [Errno -2] Name or service not known" when I run docker-compose up. There is a connection failure between the Django container and rabbitmq container in producer.py even though I have given the name of rabbitmq container name in connection string. docker-compose.yml version: '3.8' services: rabbitmq: image: rabbitmq:3.8-management-alpine ports: - 15673:15672 environment: RABBITMQ_DEFAULT_VHOST: vhost RABBITMQ_DEFAULT_USER: guest RABBITMQ_DEFAULT_PASS: guest healthcheck: test: rabbitmq-diagnostics check_port_connectivity interval: 30s timeout: 30s retries: 10 restart: always backend: build: context: . dockerfile: Dockerfile command: python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 volumes: - .:/app restart: always depends_on: rabbitmq: condition: service_healthy view.py from .producer import publish class SampleView(APIView): def get(self, request): print('HERE') publish('data send', {'message':'Here'}) return Response({'message': 'HERE'}) producer.py import pika import json import os connection = pika.BlockingConnection( pika.ConnectionParameters(host='amqp://guest:guest@rabbitmq:5672/vhost') ) channel = connection.channel() channel.queue_declare(queue='main') def publish(method, body): properties = pika.BasicProperties(method) # body = bytes(body) channel.basic_publish(exchange='', routing_key='main', body=body, properties=properties) channel.close() -
Django get value from foreign key in views.py
I am a beginner in dango. I am trying to retrieve the price from the service and make a sum of all the prices. I am asking for help. logopedija/models.py class Pricelist(models.Model): name=models.CharField('Name of service', max_length=60) price=models.DecimalField(default=0, decimal_places=2, max_digits=20) def __str__(self): return "%s %s" % (self.name, self.price) class Service(models.Model): id = models.AutoField(primary_key=True) user=models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, limit_choices_to={'active': True},) service=models.ForeignKey(Pricelist, on_delete=models.CASCADE, null=True, blank=True) day=models.DateField(default=date) time_service = models.CharField(max_length=10, choices=TIME-CHOICE, default="16:00") is_paid = models.BooleanField(default=False) def __str__(self): return f"{self.user.name} | dan:{self.day} | time:{self.time_service} | service:{self.service.price}" logopedija/views.py def show_service(request, service_id): service = Service.objects.get(pk=service_id) return render(request, 'users/show_service.html', {'service':service}) logopedija/show_service.html {% extends 'pacijenti/base.html' %} {% block content %} \<div class="card"\> \<div class="card-header"\> Detalji termina \</div\> \<div class="card-body"\> \<h5 class="card-title"\>{{ service }}\</h5\> \<p class="card-text"\> {{ service.id }}\<br/\> {{ service.user }}\<br/\> {{ service.service }`your text`}\<br/\> {{ service.day }}\<br/\> {{ service.time_service }}\<br/\> \</p\> \</div\> \</div\> {% endblock %} -
How to override font familly in Django 4.2?
Django 4.2 release notes: The admin’s font stack now prefers system UI fonts and no longer requires downloading fonts. Additionally, CSS variables are available to more easily override the default font families. I noticed that the font familly of the admin panel changed from : font-family: Roboto, "Lucida Grande", "DejaVu Sans", "Bitstream Vera Sans", Verdana, Arial, sans-serif; To font-family: var(--font-family-primary); --font-family-primary: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; How can I customize font-family-primary and make it use Roboto as before ? -
Django raw SQL queries
Here is my code for raw SQL query: timeSeries=TimeSeries.objects.raw('select avg(value) from TimeSeries where station=%s group by date',[request.POST['station-number']]) it throws error: relation "timeseries" does not exist. what can be the problem can someone kindly help? -
Webpack does not allow Django to set sessionid Cookies
I setup React application using Webpack and Django for Backend, i wanted to make authorization with sessions, but whenever i try to make a request i get 200 OK status Response and in the Response Headers i see session-id in Set-Cookie header, but not in the COOKIES, everything is fine when i setup app with create-react-app, and i think that Webpack just does not allow Django to set Cookies or something, so are there anyone that can help me? Here is the React code: await fetch('http://127.0.0.1:8000/api/v1/account/login', { method: 'POST', body: JSON.stringify({ username: formData?.username, password: formData?.password }), headers: { 'Content-Type': 'application/json', 'X-CSRFToken': Cookies.get('csrftoken') as string, 'withCredentials': 'include' }, }) i tried to make requests with RTKQuery, but it didn't work, it just seems like Webpack does not allow to set Cookies :/ -
Axios can't sent value from template to viwes.py Django
I try to use axios with method POST in Django ,but This case server can't collect submodel value . it output to template always "Test". Where am I wrong ? IN TEMPLATE IN VIEWS.PY IN BROWSER Solution to solve it -
Set cronjobs to run everyday at 6am in django python
I am using Django-Crontabs to execute my function every day in the morning at 6 am. Here is my code for Django-Crontabs. Firstly I install Django-Crontabs with this command. pip3 install Django-crontab Settings.py INSTALLED_APPS = [ 'django_crontab', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp' ] CRONJOBS = [ ('* 6 * * *', 'myapp.cron.cronfunction') ] Here I have set the code to run every day at 6 AM. As per the following template. But it is not working. # Use the hash sign to prefix a comment # +---------------- minute (0 - 59) # | +------------- hour (0 - 23) # | | +---------- day of month (1 - 31) # | | | +------- month (1 - 12) # | | | | +---- day of week (0 - 7) (Sunday=0 or 7) # | | | | | # * * * * * command to be executed cron.py def cronfunction(): logger.warning("========== Run Starts ====") logger.warning("========== Run Ends ======") If I am running this function every 2 or 3 minutes then it works fine. ('*/2 * * * *', 'myapp.cron.cronfunction') How do I set my cronjob to run every day, Can anyone help? please.