Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django cant access variable from form created with ModelForm
I am trying to create a simple form based on ModelForm class in Django. Unfortunately I keep getting UnboundLocalError error. I checked numerous advises on similar issues, however it seems I have all the recommendations implemented. If I run the below code, I get following error: UnboundLocalError: cannot access local variable 'cook_prediction' where it is not associated with a value My models.py: from django.db import models class RecipeModel(models.Model): i_one = models.BigIntegerField(default=0) v_one = models.FloatField(default=0) My forms.py: from django import forms from .models import RecipeModel class RecipeInputForm(forms.ModelForm): class Meta: model = RecipeModel exclude = [] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['i_one'].initial = 0 self.fields['v_one'].initial = 0 My views.py: from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.decorators import login_required from . import forms @login_required def index(request): if request.method == 'POST': recipe_form = forms.RecipeInputForm(request.POST) else: recipe_form = forms.RecipeInputForm() if recipe_form.is_valid(): cook_prediction = recipe_form.cleaned_data if recipe_form.is_valid() == False: print("Recipe form is not valid!") After running the code, except for the above mentioned error message, I also get the Recipe form is not valid! printout from the last line of views.py. How to get rid of this error and successfully get variable from form based on ModelForm? -
Python async performance doubts
I'm running an websocket application through Django Channels and with Python 3.12. I have a ping mechanism to check if my users are still connected to my application where at a fixed time interval the fronted sends a ping message to my server (let's say every 5 seconds) and when I receive that message I do the following: I call await asyncio.sleep(time interval * 2) ; Afterwards I check if the timestamp of the last message I received in this handler or in any other of the ones that is active is higher than time_interval * 1.5 and if it is I disconnect the user in order to free that connection resources since it isn't no longer active; However we noticed that this sleep call we make every X seconds for each active connection that we have when a ping call is received may be causing some performance issues on the application as an all. We are assuming this because we noticed that every time we shut down this ping logic we need less resources (number of pods and CPU) to handle the median number of traffic we have then when we have this ping handler active. In other hand … -
Django override settings not being assigned in the __init__ method even though they are available
I am overriding settings for the entire test class like this: @mock_aws @override_settings( AWS_CLOUDFRONT_DOMAIN="fake_domain", AWS_CLOUDFRONT_KEY="fake_key", AWS_CLOUDFRONT_KEY_ID="fake_key_id", AWS_CLOUDFRONT_DISTRIBUTION_ID="fake_distribution_id", ) class TestCloudfrontClient(TestCase): def setUp(self): self.cf_client = CloudfrontClient() and here is the CloudfrontClient class: class CloudfrontClient: """Client to interact with AWS S3 through Cloudfront""" def __init__( self, cloudfront_pk_id=settings.AWS_CLOUDFRONT_KEY_ID, cloudfront_key=settings.AWS_CLOUDFRONT_KEY, cloudfront_distribution_id=settings.AWS_CLOUDFRONT_DISTRIBUTION_ID, cloudfront_domain=settings.AWS_CLOUDFRONT_DOMAIN, rsa_signer=rsa_signer ): self.cf_client = client('cloudfront') self.distribution_id = cloudfront_distribution_id self.cloudfront_signer = CloudFrontSigner(cloudfront_pk_id, rsa_signer) self.cloudfront_domain = cloudfront_domain breakpoint() At the breakpoint if I print settings.AWS_CLOUDFRONT_KEY_ID I get the fake_key_id but when I print cloudfront_pk_id I get empty string. This is also the case for other variables and it is messing my test results. Am I missing something about how override_settings work? -
PostgreSQL Azure database not connecting to Django app
I have issues with a Django deployment. I am deploying on Azure through github. The app builds and deploys successfully, I am able to migrate the database, but then I receive a error when I try to log in, it seems that the data is not being saved. [migrate](https://i.sstatic.net/it8xLAnj.png) [showmigrations](https://i.sstatic.net/7ogvwvye.png) [django error](https://i.sstatic.net/e8nY3xmv.png) I have added logs to see if I can find where the issue might be but I am unable to establish where the issue lies. -
How to create android app for Django website?
I have django website already running. It is using MySQL as database and hosted in windows VPS with windows IIS server. Now I need to create a mobile app (android app) for my django website. (I'm not too much familiar with android development) **1. So what is the better way to do this? And how to do this?** -
How to sum two datefields in sqlite using django orm
My django5 model has two datetime fields, bgg_looked_at and updated_at. They are nullable, but fields should not be null when this query is ran. So far I tried class UnixTimestamp(Func): function = 'strftime' template = "%(function)s('%%s', %(expressions)s)" # Escape % with %% output_field = FloatField() # Explicitly declare the output as FloatField and listings = Listing.objects.annotate( bgg_looked_at_timestamp=Coalesce( UnixTimestamp(F('bgg_looked_at')), Value(0.0, output_field=FloatField()) ), updated_at_timestamp=Coalesce( UnixTimestamp(F('updated_at')), Value(0.0, output_field=FloatField()) ) ).annotate( sum_fields=ExpressionWrapper( F('bgg_looked_at_timestamp') + F('updated_at_timestamp'), output_field=FloatField() ) ).order_by('sum_fields') but I get TypeError: not enough arguments for format string when I just do a len(listings) -
Unable to run frappe-gantt in my Django project
I develop a Django app that will display gantt projects graph and I came to frappe-gantt, an open source librairy (https://github.com/frappe/gantt/tree/master) that is exactly what I am looking for. But, I have an error when trying to run the simple example: Uncaught TypeError: t is undefined. Librairy seems to be correctly loaded as HTTP responses return 200 and console.log(typeof Gantt); return "function". Gantt function target a DOM element that currently exist. I did not find any answer in SO. To notice that when loaded, frappe-gantt.umd.js header Content-Type is text/plain instead of "application/json" that maybe could explain? Thanks for your help {% load static %} <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.2/css/bulma.min.css"> <script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script> <link rel="stylesheet" href="{% static 'dist/frappe-gantt.css' %}"> <script src="{% static 'dist/frappe-gantt.umd.js' %}"></script> </head> <body> <section class="section"> <div class="container"> <div class="columns"> <div class="column is-2"> <div class="aside"> <h3 class="menu-label">Projects</h3> <hr> <ul class="menu-list"> {%for p in projects %} {% if p.tasks.count > 0 %} <li> <a {% if p.id == id|add:0 %} class="is-active" {%endif%} href="?id={{p.id}}"> {{p.name}} </a> </li> {% endif %} {% endfor %} </ul> <hr> <h3 class="menu-label">Options</h3> <ul class="menu-list"> <li> <a target='_blank' href="/admin">admin</a> </li> </ul> </div> </div> {% if tasks_count %} <div class="column is-10"> <div … -
django alter checkconstraint with json field
I want to alter table to add check constraint in mysql, if using sql like below ALTER TABLE Test ADD CONSTRAINT chk_sss CHECK( JSON_SCHEMA_VALID( '{ "type":"object", "properties":{ "latitude":{"type":"number", "minimum":-90, "maximum":90}, "longitude":{"type":"number", "minimum":-180, "maximum":180} }, "required": ["latitude", "longitude"] }', sss ) ) class Test(models.Model): sss = models.JSONField(null=True) class Meta: constraints = [ CheckConstraint( check = ???????), ] how to write this sql in model ? -
How can I fix pycham wrong django type hint
member_meta_models: QuerySet[MemberWantedMetaModel] = MemberWantedMetaModel.objects.filter(member_id=member_id) Pycharm says "Expected type QuerySet[MemberWantedMetaModel,MemberWantedMetaModel], got QuerySet[MemberWantedMetaModel] I think type hint is right. How Can I fix it. If my type hint is wrong, How can I fix it? (I am using python 3.13.0, Django 5.1.4 mypy, pydantic) Thanks -
AttributeError: 'WSGIRequest' object has no attribute 'user_profile' in Django Web Application
When developing a Web application using the Python Django framework, I encountered an error 'AttributeError: 'WSGIRequest' object has no attribute 'user_profile''. My code attempts to access request.user_profile in a view function. I have already ensured that the user authentication middleware is enabled. What could be the possible reasons for this? I have tried the following methods: Checked the configuration and functionality of the user authentication middleware to ensure it operates properly and can correctly identify the user. Reviewed other operations related to the request object in the view function to confirm that the request object has not been accidentally modified. -
Slug Field in Django Model Not Including Related Tags on Save
I have the following save method in my Django model: slug = models.SlugField(unique=True, blank=True, null=True, max_length=255) def save(self, *args, **kwargs): if self.pk is None: super().save(*args, **kwargs) tags = Tag.objects.filter(office__id=self.id).values_list("name", flat=True) print("Tags") print(tags) location_work_override_id = self.location_work_override.id if self.location_work_override else '' location_work_id = self.contest.location_work_id if self.contest and self.contest.location_work_id else '' if not self.slug and tags: self.slug = slugify( f"{self.display_name}-{'-'.join(tags)}-{location_work_override_id}-{location_work_id}-{self.contest.short_name}-{self.contest.contest_number}" ) elif not self.slug: self.slug = slugify( f"{self.display_name}-{location_work_override_id}-{location_work_id}-{self.contest.short_name}-{self.contest.contest_number}" ) super().save(*args, **kwargs) The slug field is supposed to include related Tag names from a Tag model that has a ForeignKey to Office. However, when I create a new Office instance in the Django admin, the tags variable in the save method is always empty, even though I add the tags in the admin interface. I suspect this is a timing issue because the save method of Office runs before the related Tag objects are saved. My Questions: How can I ensure that the Tag objects are saved before the save method of the Office model accesses them? Is there a way to correctly populate the slug field with the tags in this scenario, preferably without relying on manual order of operations? I’m looking for a robust solution that works reliably in the Django admin … -
Unable to login subdomain of django tenant, primary domain and admin log in work
I have a multi tenant app using the library django-tenants. When logging into the core URL with the created superuser, the login page works completely fine. When using the subdomain address to login, the page returns a 500 error when using the correct username and password that exists and the console says Uncaught (in promise) SyntaxError: Unexpected token '<', " <!doctype "... is not valid JSON. When using an login username that doesn't exist, the output is 400 Bad Request. The odd part, is I can access the admin panel of a subdomain, log in completely fine, change the URL to go to a part of the app - and the user is now logged in. After being logged in, I can submit forms completely fine and data is being captured, it is solely the login page on a subdomain that has an error submitting. I am lost since subsequent data forms submit and go correctly, and there are no invalid tokens (from what I see) views.py def dual_login_view(request): """Authenticate users with both Django Authentication System and Django Rest Framework""" if request.method == "POST": username = request.POST.get("login") password = request.POST.get("password") user = authenticate(request, username=username, password=password) if user is not None: … -
uniqueConstraint and get_or_create not working?
I am trying to make a thread safe/concurrent aware create function for some moel, as I understood it the following should work: @transaction.atomic def create_new_request(self, request: Request): item_id = 1 item = Item.objects.get(id=item_id) print("creating", request.user) purchase_request, request_created = PurchaseRequest.objects.select_for_update().get_or_create( requester=request.user, status="draft", ) purchase_request.save() print("get or created: ", purchase_request.id, request_created) Then I created a unique constraint in the meta (as only "drafts" have this constraint of a single draft per user) class PurchaseRequest(models.Model): class Meta: verbose_name = "Original Purchaserequest" verbose_name_plural = "Original Purchaserequests" constraints = [ models.UniqueConstraint( fields=["requester", "status"], condition=Q(status="draft"), name="unique_draft_user" ) ] However the moment I sent multiple requests at once from the frontend (using promise.all to sent many simultaneously), I notice that the application crashes with the following errors: creating paulweijtens creating paulweijtens creating paulweijtens get or created: 483 True 2024-12-08 22:21:27,732 ERROR root duplicate key value violates unique constraint "unique_draft_user" DETAIL: Key (requester_id, status)=(224, draft) already exists. Traceback (most recent call last): File "", line 916, in get_or_create return self.get(**kwargs), False ^^^^^^^^^^^^^^^^^^ File "", line 637, in get raise self.model.DoesNotExist( isp.procure.purchase.models.PurchaseRequest.DoesNotExist: PurchaseRequest matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "", line 89, in _execute return … -
signnow API/django app/ send email/ e-signing contract/
thank you for your time. i had a task to do: Tasks at hand o Brief description of the tasks to be performed ▪ The objective is to create a Django app that enables a user to register, log in, and sign a pre-defined contract. The contract will have 2 signing parties: one of them is the user that logs in initially and signs the contract, the other signing party is to be invited to sign by email. o User Stories ▪ As a user, I want to register, so that I could get logged in to use the signing features of the app • Acceptance Criteria o Basic django authentication is enough (session auth) o Username and password is enough for registration o No extra validation required for password or username o Upon logging in, I should be directed to the contract instantiation page ▪ As a user, I want to log in, so that I could use the signing features of the app • Acceptance Criteria o Log in with username and password o No extra validation required for password or username o Upon logging in, I should be directed to the contract instantiation page ▪ As a … -
Django-Extensions: how to add local variables to shell_plus
I have multiple dictionaries, and I want each key/value pair to be defined in the local scope of a django-extensions shell_plus session. My current management command looks something like this: import django import code devs = { 'hot_water': object() 'air': object() } procs = { 'clean_keg': lambda x: 'do_something' } # unnecessary code when using `shell_plus` model_map = { model.__name__: model for model in django.apps.apps.get_models() } local = { 'procs': procs, 'devs': devs, **devs, **procs, **model_map } code.interact(local=local) Now I find myself wanting to add settings, models, and several other Django objects that are already included with shell_plus, but I can't find a way to add local variables to the shell_plus session. Brett Thomas's answer shows how to import modules into a shell_plus session, but doesn't show how to add variables from a dict-like object. How do I add variables to a shell_plus session? -
Django Allauth 65.2.0 headless mode - session token problems
I have a setup with django, drf, django-allauth headless and nextjs acting somewhat as a proxy to my django api, completely decoupled and server from different servers (a regular django setup and separate node server for next) Settings: AUTH_USER_MODEL = "user.User" ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "mandatory" AUTHENTICATION_BACKENDS = [ "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", ] HEADLESS_ONLY = True HEADLESS_FRONTEND_URLS = {} # HEADLESS_TOKEN_STRATEGY = "apps.core.backends.allauth_token_strategy.DRFTokenAndAnonSessionTokenStrategy" SOCIALACCOUNT_PROVIDERS = { "google": { "APP": { "client_id": config.OAUTH.GOOGLE.CLIENT_ID, "secret": config.OAUTH.GOOGLE.CLIENT_SECRET, }, "SCOPE": [ "profile", "email", ], "AUTH_PARAMS": { "access_type": "offline", }, "OAUTH_PKCE_ENABLED": True, } } URLs: (the change is purely for aesthetics) from allauth.headless.constants import Client from allauth.headless.urls import build_urlpatterns from django.urls import path, include from django.urls.resolvers import RoutePattern def build_allauth_url_patterns(): path_object = build_urlpatterns(Client.APP)[0] path_object.pattern = RoutePattern("") return [path_object] urlpatterns = [ path("user/", include((build_allauth_url_patterns(), "headless"), namespace="app")), path("accounts/", include("allauth.urls")), ] I want to use the headless mode since I don't need the CSRF features of django allauth browser implementation, however I want to use the handshake of django-allauth so I'm sending a post request to the api via a form from nextjs. for this example consider my domain as localhost <form method="post" action="https://api.localhost/v1/user/auth/provider/redirect" className="w-full"> <Button variant="outline" className="gap-2 w-full" type="submit"> <Icons.LogIn /> <span>Sign Up With Google</span> </Button> <Input … -
Integrate django with react
I want to integreate django with react, but it show error that "module 'myapp.views' has no attribute 'index'" URL.py urlpatterns = [ path('admin/', admin.site.urls), path('',ReactView.as_view() , name = "index"),] Views.py class ReactView(APIView): def get(self, request): output = [{ "user_ID":output.user_ID, "user_Name":output.user_Name, "user_Email":output.user_Email, "user_Account":output.user_Account, "user_Password":output.user_Password, "user_Image":output.User_Image, } for output in User.object.all()] return Response(output) def post(self , request): serializer = ReactSerializer(data = request.data) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data) serializer.py class ReactSerializer(serializers.ModelSerializer): class Meta: model = User field = ['user_ID' , "user_Name" , "user_Email" , "user_Account" , "user_Password" , "user_Image"] -
HTML form action - Login Page Validation in Django
I've a login page which takes Username, Email ID and Password. I check if these values are matching with database data in views.py file. If those three values are correct, that means, user already exists and user wants to see the homepage. If entered values are not matching, that means, user does not exist, and want to show an error message "User does not exist, please signup", in the same html page. I've done the verification part in views.py. But when I click on Submit button on Login page, even if the user doesn't exist, it's going to Homepage. Login.html <body> <div class = "tablediv"> <div><h1>LOGIN FORM</h1></div> {% if message != "verification successfull!" %} <p class = "error">{{ message }}</p> <form action="" method="POST"> {% else %} <form action="{% url 'addtodb' %}" method="POST"> {% endif %} {% csrf_token %} <div> <label for = "name"><b>Username</b></label><br> <input type = "text" id = "name" placeholder = "Enter username here" name = "username" required> </div><br> <div> <label for = "mail"><b>Email ID</b></label><br> <input type = "email" id ="mail" placeholder=" Enter mail id here" name = "email"> </div> <br> <div> <label for = "pass" maxlength = "10" ><b>Password</b></label><br> <input type = "password" id = "pass" name = … -
Using Polars data in Django template html
lets start with their demo. df = pl.DataFrame( { "foo": [1, 2, 3], "bar": [6, 7, 8], } ) df.write_json() '[{"foo":1,"bar":6},{"foo":2,"bar":7},{"foo":3,"bar":8}]' I pass in the df in the from the df.write_json() context = { 'df' : df, } But nothing i am trying in Django is working? the json was the only option i see to pass the data. techinally this is a list of dicts? <ul> {% for i in df %} # tried many option here {{ i.foo }} {% endfor %} <ul> i have tried all sorts of things. for Pandas i would just use df.to_records() what is best way to get Polars data into a Django template to use in things like tables? loving polars so far but getting confused by a few things. Like this one. Thanks! -
Single Click django app installation using kubernates
I have my own CMS written in Django and Python. It uses a PostgreSQL database. For caching, it uses Redis and Memcached, and for scheduled tasks/cron jobs, it uses Celery. I am looking for a solution where, upon signup and payment, customers can deploy the CMS with a single click. Once deployed, it should be accessible under a subdomain like customer1.example.com or customer2.example.com. My Django backend is not configured for multi-tenancy because each customer may have slightly different requirements, especially in terms of functionality. This means the codebase could vary slightly from one customer to another. Additionally, the database and files need to be backed up regularly. I want a cost-effective solution for this setup. I don’t have much knowledge about cloud infrastructure. What would be your best advice for handling such a situation? -
How to boostrap a Django login form
I am writing a library management system in Django for my own personal needs. I have experience in backend,but I lack expertise in frontend. The project makes use of Boostrap 4 and Django's crispy forms. I have a base template templates/base.html from which other children templates inherit from. <!-- templates/base.html --> <!doctype html> <html lang="en"> <head> <!-- required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- boostrap css --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <title>Book manager</title> </head> <body> <nav class="navbar navbar-expand-md navbar-dark bg-dark mb-4"> <a class="navbar-brand" href="">Books</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> {% if user.is_authenticated %} <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link dropdown-toggle" href="#" id="userMenu" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {{user.username}}</a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="userMenu"> <a class="dropdown-item" href="#"> Change password</a> </div> </li> </ul> {% else %} <form class="form-inline ml-auto"> <a href="{% url 'login' %}" class="btn btn-outline-secondary">Log in</a> <a href="" class="btn btn-primary ml-2">Sign up</a> </form> {% endif %} </div> </nav> {% block content %} <!-- here goes html content of childs--> {% endblock %} <!-- optional js --> <!-- jquery first, popper then bootstrap --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"> </script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"> </script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" … -
How do I save the email address I received from the Kivymd interface in the Django model?
My goal is to save the data I receive from the Kivymd interface in the Django model. Actually, there is no problem in saving many types of data, but the e-mail part caused problems. Below, I have shown the Django models and the operations on the Kivymd side (1. Getting the data from the front; 2. Post processing with DRF). from django.db import models class Model(models.Model): user_mail = Model.EmailField() And the posting progress ... def data(self): email = self.screen.ids.email_id.text requests.post(url, json('user_mail':'email') This is in its simplest form, I can give details if you want... And it returns a request 400 error as output: "POST /users// HTTP/1.1" 400 37 It is worth noting that I received the entered address, but as you can see, an error occurs in the sending part. -
Django - unable to import files in app directory
I am working on tutorial Django app. It is a very basic application, aimed at learning 'sceleton' structure of Django project. The problem - I am not able to do any imports between files in app directory. No imports between files like forms.py, views.py, models.py seem to work. In particular, I am not able to call: 'from models import ModelClass' in my forms.py file. I always get an error: ModuleNotFoundError: No module named ... (name of file here, e.g. 'models'). 'from .models import ModelClass' - (with dot before 'models') doesn't work either - same error. Also, I do have the usual 'init' file in the same directory. Any ideas on how to import model class from models.py into forms.py, both files in same directory? -
Docker Container gets down after an error shows up
I am developing a django project and the server is run by a docker container When there is an error in the code like a "syntax error". Docker logs shows that error and then shuts it self. The problem is until yesterday when I fix the error the docker log was showing "backend-1 | Watching for file changes with StatReloader" and I could still connect the server. How can I fix this problem? -
How to trigger Django task at specific date in model field
I have a model that contains the following field class EventConfig(models.Model): end_date = models.DateTimeField(blank=True, null=True) I have celery installed that's sending periodic emails and triggering other tasks at set time intervals e.g every hour or at 12pm. However, if I want to trigger an email as exactly when 'end_date' is reached, what is the best way to do this? I realise I could set a Celery schedule to run every minute to check the date, but is running a batch job every 60 seconds perpetually, the best approach or would this have drawbacks? Is there a way for example to set the crontab schedule to read from a list of values so that I could so something like schedule_list = EventConfig.objects.all().values_list(end_date, flat=True) or schedule_list.append(self.end_date) whenever a model instance is saved, and have Celery read from 'schedule_list' so the batch jobs then only fire at the correct times? Or is there a better way to do this either with or without celery?