Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add name attribute in dynamically generated HTML form?
I am generating a dynamic input field in my form using javascript in Django template. But on submitting the form in Django, I need the name attribute in every input field. Like this: For input field with From Area label I need a name to be something like this: fromArea-1 Similarly, For input field with To Area label I need a name to be something like this: toArea-1 Any help would be beneficial. Here is my code: function addRow() { const div = document.createElement('div'); div.className = 'card'; div.innerHTML = ` <div class="card-body"> <div class="form-group"> <label>From Area</label> <select class="form-control" id="exampleFormControlSelect1"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> <br/> <label>To Area</label> <select class="form-control" id="exampleFormControlSelect1"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> <br> <label>Distance</label> <input class="form-control" type="text"></input> </div> </div> `; document.getElementById('permission-wrapper').appendChild(div); } <div class="mt-4 ml-4 mr-4"> <form class="mt-4" method="post"> <div id="permission-wrapper"> <div class="card mb-2"> <div class="card-body"> <div class="form-group"> <label>From Area</label> <select class="form-control" id="exampleFormControlSelect1"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> <br/> <label>To Area</label> <select class="form-control" id="exampleFormControlSelect1"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> <br> <label>Distance</label> <input class="form-control" type="text"></input> </div> </div> </div> </div> <br/> <button class="btn btn-primary float-right" onClick="addRow()">Add</button> <button class="btn btn-success" type="submit">Submit</button> </form> </div> -
Herko collect static question. How do I make it run python3 manage.py collect static instead of python manage.py collect static
I have python3 installed on my virtual env, but the default python version on my laptop is 2. I run python3 ... for everything I do. Heroku runs python manage.py collectstatic, so it does not work, as my default version is python2. I want it to run python3 manage.py collectstatic. Is there a way I can do this? Also is there a way I can collecstatic files and disable heroku from doing it, so that I can manually get the static files ready for production? Please help me out here, I am very confused. -
I can access fatimatestpro.pythonanywhere.com but not fatimatestpro.pythonanywhere.com/help/
I am working on PythonAnywhere and made my first project. I am trying to access many views (HTML pages) from my views.py. Here is my project tree: emailpro --emailpro ----url.py --emailapp ----urls.py ----views.py --templates ----emailapp ------index.html ------help.html Code inside my emailpro>emailpro>urls.py is from django.conf.urls import url, include from django.contrib import admin #from emailapp import views urlpatterns = [ url(r'^admin/', admin.site.urls), #url(r'^$', views.index, name='index'), url('', include('emailapp.urls')), ] Code inside my emailpro>emailapp>urls.py is: from django.conf.urls import url from emailapp import views urlpatterns=[ url('', views.index, name='index'), url(r'^help/$', views.help, name='help'), ] Code inside my emailpro>emailapp>views.py is from django.shortcuts import render #from django.http import HttpResponse # Create your views here. def index(request): my_dict={'insert_me': "Hi I am index coming from views.py"} return render(request, 'emailapp/index.html', context=my_dict) def help(request): help_dict={'help_insert': "HELP PAGE"} return render(request, 'emailapp/help.html', context=help_dict) My emailpro>templates>emailapp>index.html is <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Index</title> </head> <body> <h1>Index page</h1> {{ insert_me }} </body> </html> Code inside my emailpro>templates>emailapp>help.html is <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title> Help </title> </head> <body> <h1>This is my Help HTML</h1> {{ help_insert }} </body> </html> Now when I run my site and access http://fatimatestpro.pythonanywhere.com/, it shows me my index.html page which means it is going inside my emailpro>emailapp>urls.py … -
Update Django Model
How to i update a certain value in the database? class Userdata(models.Model): user = models.OneToOneField(User, on_delete= models.CASCADE) faculty = models.ForeignKey(Fakultas,on_delete=models.CASCADE,default= 1) is_voted = models.BooleanField(default=False) def __str__(self):return self.user.username class Voting(models.Model): name = models.CharField(max_length=50) faculty = models.ForeignKey(Fakultas, on_delete=models.CASCADE, default=1) pic = models.CharField(max_length=50) text = models.TextField() voters = models.IntegerField() def __str__(self): return self.name My Views : def voted(response): if response.method == 'POST': id = response.POST.get['idcalon'] user = Userdata.objects.get() #get the username calon2 = Voting.objects.get() #get user selection in html user.is_voted = True calon2.voters +=1 user.save(['is_voted']) calon2.save(['voters']) I'm trying to grab the user's name and then when update the user's is_voted value to True when triggered. Then, I wanted to grab my Voting model by id, for example, I wanted to edit id = 1 So how do I do it? I've been trying to understand the documentation, but still have 0 idea how to do it. Thank you -
Docker Django database connection error: UNICODE Using encoding ASCII 'UTF-8' and UNICODE 'UTF-16LE'
I'm running into an issue with docker and django when trying to connect to a remote database (on a different server). Using Python 3.4 and django 1.9.7. I can perform runserver just fine when running locally, and can connect using tsql or pyodbc.connect() in the docker container. However, when performing runserver on the docker container for the project, here is the error I receive: [ODBC][14][1604961520.418108][SQLDriverConnectW.c][290] Entry: Connection = 0x7f48618ecba0 Window Hdl = (nil) Str In = [UID={{UID}};PWD={{password}};DRIVER=FreeTDS;SERVER={{serverIP}};DATABASE={{databaseName}};unicode_results=True;][length = 110] Str Out = (nil) Str Out Max = 0 Str Out Ptr = (nil) Completion = 0 UNICODE Using encoding ASCII 'UTF-8' and UNICODE 'UTF-16LE' This error is mentioned on https://docs.microsoft.com/en-us/sql/connect/odbc/linux-mac/known-issues-in-this-version-of-the-driver?view=sql-server-ver15 with the comment: There is more than one Driver Manager installed and your application is using the wrong one, or the Driver Manager was not built correctly. I have tried everything I can think of and feel like I'm overlooking something really obvious here, but I've had no luck figuring out this error, or if I even have more than one driver being used (and if so how to fix that). Here are other related setup files, perhaps someone will spot something or have an idea. Any help is greatly … -
Django Rest API ManyToMany on exsiting Database not working
I have a database with one table for recipes without the ingredients and one table with the ingredients each with a recipe id to reference each other. Now I don't know how to refer to the recipe id column, because at the moment (I build a rest API) it returns no ingredients. My models.py class Ingredients(models.Model): ingredientid = models.AutoField(db_column='IngredientID', primary_key=True, blank=True) recipeid = models.ForeignKey('Recipe', models.DO_NOTHING, db_column='RecipeID', blank=True, null=True, related_name='+') amount = models.CharField(blank=True, null=True, max_length=100) unit = models.CharField(blank=True, null=True, max_length=100) unit2 = models.CharField(blank=True, null=True, max_length=100) ingredient = models.CharField(db_column='Ingredient', blank=True, null=True, max_length=255) class Meta: managed = False db_table = 'Ingredients' class Recipe(models.Model): recipeid = models.AutoField(db_column='RecipeID', primary_key=True, blank=True) # Field name made lowercase. title = models.CharField(db_column='Title', blank=True, null=True, max_length=255) # Field name made lowercase. preperation = models.TextField(db_column='Preperation', blank=True, null=True) # Field name made lowercase. images = models.CharField(db_column='Images', blank=True, null=True, max_length=255) # Field name made lowercase. ingredients = models.ManyToManyField(Ingredients) class Meta: managed = True db_table = 'Recipes' If there is no issue it has to be somewhere on the api part: Serializer: class FullRecipeSerializer(serializers.ModelSerializer): ingredients = serializers.PrimaryKeyRelatedField(queryset=Ingredients.objects.all()) class Meta: model = Recipe fields = ['title','ingredients'] ViewSet: class FullRecipesView(generics.ListCreateAPIView): serializer_class = FullRecipeSerializer permission_classes = [ permissions.AllowAny ] queryset = Recipe.objects.all() I hope you understand my … -
How to setup a socket server on django?
how can i use django to create a socket server that could be able to call procedures on a python client from the server ? it has to be launched on init, so when i just add a server like this one : https://pypi.org/project/aiohttp-json-rpc/ in the __init__.py it starts the RPC server, and block django, not allowing the HTTP server to start -
Block title renders but Block content does not, on the same page
The {% block title %} is being rendered, so Test is displayed on the page, and changes when I change whatever is in there. However, no matter what I do with {% block content %}, the content does not display on the page. I would have assumed that either both of them, or none of them would display. Why would only one block type display and not the other? <!-- templates/registration/password_reset_complete.html --> {% extends 'base.html' %} {% block title %} Test {% endblock %} {% block content %} <div id="content" class="colM"> <p>We've emailed a new password to the e-mail address you submitted. You should be receiving it shortly.</p> <p> You can log in now on the <a href="{% url 'login' %}">log in page</a>.</p> <h1>Password reset sent</h1> <br class="clear"> </div> {% endblock %} -
Error 'int' object has no attribute 'get'
This one is really confusing me. I am reading a excel file into my python script. When I run the script with about 5 rows it runs perfectly. When I run it with 10 rows it gives me this error. I looked the error up and it seems the solution is to use HttpResponse. I am already using the HttpResponse. io = BytesIO() writer = ExcelWriter(io) data.to_excel(writer, 'Results', index=False) data2.to_excel(writer, 'Suggestions', index=False) writer.save() rFile = io.getvalue() response = HttpResponse(rFile ,content_type='application/ms-excel') response['Content-Disposition'] = f'attachment; filename={FilePath}.xlsx' return response return render(request, 'home.html') Here is the error Environment: Request Method: POST Request URL: http://127.0.0.1:8000/page_objects/ Django Version: 3.1.2 Python Version: 3.8.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\e0185446\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\e0185446\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\deprecation.py", line 116, in __call__ response = self.process_response(request, response) File "C:\Users\e0185446\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: Exception Type: AttributeError at /page_objects/ Exception Value: 'int' object has no attribute 'get' If you think any other part of my code would be useful to see let me know and I will edit it in. -
Django: grid of 5 by 5 elements on desktop on 2/3 of the width screen
I need to make a grid of images of 5 by 5 (total 25) in desktop mode, but only occupaying 2/3 of the width of the screen (this is why I first create a col-md-8) on top of evertything. However, my grid is showing 3 images in the first row, 2 images in the second row, and 3 in the last element. I thought it was because of the size of the images, but made them smaller and the layout is still the same. So I think problem is in my code: DB only has 8 elements at the moment but grid will show 25 (5 by 5) images. Code: <div class="row"> <div class="col-md-8"> <div class="row"> {% for product in products %} <div class="col-sm-4"> <img src="https://picsum.photos/100/110" style="margin-right: 5%; margin-top: 5%;"> </div> {% if forloop.counter|divisibleby:5 %} </div> <div class="row"> {% endif %} {% endfor %} </div> </div> <div class="col-md-4"></div> </div> -
Celery task can not call Channels consumer via channel_layer.send
I've been setting up a websocket for a fairly simple application. I wrote a JsonWebsocketConsumer as well as some celery tasks in order to perform some longer-running tasks (db accesses). Everything is working without error but my consumers are never getting called. Any ideas? consumers.py class NetworkCompConsumer(JsonWebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive_json(self, content): include = content['include'] # exclude = content['exclude'] # Reduce Dimensions of Inputs to 2, Just in Case User uploads 3D # Geojson wkb_w = WKBWriter() wkb_w.outdim = 2 include = GEOSGeometry(json.dumps(include)) include = GEOSGeometry(wkb_w.write_hex(include)) # if exclude is not None: # exclude = GEOSGeometry(json.dumps(exclude)) # exclude = GEOSGeometry(wkb_w.write_hex(include)) print("firing tasks") genPolySize.delay(include.json, None, self.channel_name) genBuildingCount.delay(include.json, None, self.channel_name) self.send_json({ "hello world": "Hi!!!" }) def polygon_area(self, event): print("poly area consumer called!!") self.send_json( {"area": event['value']} ) def building_count(self, event): print("building count consumer called!!") self.send_json( {"buildingCount": event['value']} ) tasks.py def sync_send(channelName, consumer, value): channel_layer = get_channel_layer() print(channel_layer) async_to_sync(channel_layer.send)( channelName, { "type": consumer, "value": value, } ) @shared_task def genBuildingCount(include, exclude, channelName): query_skeleton = building_count_skeleton query_skeleton = getQueryTemplate(query_skeleton, exclude is not None, False) with connections['gis_data'].cursor() as cursor: cursor.execute( query_skeleton, [include, exclude] if exclude is not None else [include]) results = cursor.fetchone() buildingCount = results[0] sync_send(channelName, "building.count", buildingCount) print("successfully completed … -
Django admin field. get value in relation field
Models.py class Student(models.Model): first_name = models.CharField(max_length=255) class Room(models.Model): room_name = models.CharField(max_length=20) student = models.OneToOneField(Student, on_delete=models.CASCADE) Admin.py class RoomAdmin(admin.ModelAdmin): model = Room fields = ('room_name', 'student__first_name',) I need to appear field "first_name" on add room admin page. So i set admin follow source code, I recived errors. ERRORS: <class 'building.admin.RoomAdmin'>: (admin.E108) The value of 'fields[1]' refers to 'student__first_name', which is not a callable, an attribute of 'RoomAdmin', or an attribute or method on 'building.Room'. Please guide or suggess for this thank you :) -
Django set ModelForm ModelChoiceField initial value in UpdateView class
There are many related questions I checked on so before posting my own, but I still can't figure this out. Using Django 2.2.x. I want the owner field of my html form to initially display only 1 username and this username has to be the current event instance owner. Being a ModelChoiceField, the field on the html form is rendered as a dropdown. This dropdown for the time being contains all the app users, since the ModelChoiceField has queryset=User.objects.all() I tried to override the get_initial() method of my UpdateView but, afaict, this has no effect on the ModelChoiceField. I'm able to set all forms.CharField() initial values though. I tried also to override the __init__ method of my class EventForm(forms.ModelForm) without luck. forms.py class EventForm(forms.ModelForm): class Meta: model = Event fields = ["customer", "owner", ...] # the helper block comes from crispy_forms extension. # It rules the form layout, allowing to specify css classes, fields order # and even adding custom buttons helper = FormHelper() helper.layout = Layout( Field('customer'), Field('owner'), ... Submit('submit', 'Update') ) customer = forms.CharField(disabled=True) owner = forms.ModelChoiceField(queryset=User.objects.all()) ... views.py class EventUpdateView(LoginRequiredMixin, UpdateView): """ this view renders the update form that allows service desk operators to update event status, … -
How can I navigate through different links in DJango
I know how to access different views in django but I want to put links in my pages and them navigate through. Is this possible. What I am saying is that instead of typing the url path myself in django, i want to put links in pages and then click on them to navigate from page to page. Is it possible? -
no python at "C:\Users\AccountName\AppData\Local\Programs\Python\Python38-32\python.exe" error in VsCode
I was running the Django project without any problems. Until I reinstalled Windows and then reinstalled vscode! Now that I am running the Django project, vscode shows the following error. please guide me -
Multiple forms in one django template
I have a django template that has 2 forms. Each form submits to different models, and each form has one field to populate. The two models are: Coverletter Snippits My page allows users to add content to the coverletter via form and click submit, which will populate the content field in the coverletter model. On the same html page / template, the user can add content to snippits via form and click submit, which will populate the body field in the snippit model. I am using 2 views: CoverLetterUpdateView, which uses django built in UpdateView SnippitCreateView, which uses django built in CreateView The problem I cannot get each form to populate their own models. They both only populate the coverletter model. I'm not sure what I am doing wrong and cannot seem to find an answer online. I've been stuck at this for a couple days now. I'm sure I am missing something obvious like naming the forms different, but I cannot seem to figure out how to solve this. Any guidance would be appreciated. -
How can I return additional data when using a raw query on a model using Django?
I am new to django and have a question in regards to db queries. I am currently using a raw query to get places within x radius of a given lat lng. My query is query = """SELECT id, (3959*acos(cos(radians(%2f)) *cos(radians(lat))*cos(radians(lng)-radians(%2f)) +sin(radians(%2f))*sin(radians(lat)))) AS distance FROM businesses_business WHERE approved > 0 HAVING distance < %2f ORDER BY %s LIMIT %d OFFSET %d;""" % ( float(lat), float(lng), float(lat), details['radius'], details['orderBy'], details['limit'], details['offset'] ) and I am serlializing the data using the following: queryset = Business.objects.raw(query) serialized_data = serializers.serialize('json', queryset) I get back the data which matches the Business model. However, I also want to receive back the distance which is calculated in the query. How could I do this so that the distance for each row is also returned? p.s. If there is a better way to do this then I'd love to hear about it :) -
Django: how to use AWS access key without revealing it in source code
I'm following tutorial from https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/hls-playback.html#how-hls-ex1 It works great! But the access key is visible to user in the source code. How can I go about hiding access key from the user using Django? Tutorial puts it visible in the source code: var options = { accessKeyId: $('#accessKeyId').val(), secretAccessKey: $('#secretAccessKey').val(), sessionToken: $('#sessionToken').val() || undefined, region: $('#region').val(), endpoint: $('#endpoint').val() || undefined } var kinesisVideo = new AWS.KinesisVideo(options); var kinesisVideoArchivedContent = new AWS.KinesisVideoArchivedMedia(options); I think I need to set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY variables in settings.py, but how can I use them without revealing them to the user? -
Django module tests: Failing to attach a non-anonimous user to a request
I am trying to test that my custom permissions in DRF work properly, so I need to imitate some requests made by users with different rights (the rights are stored as attributes in the db in a table linked to the default User table). I am using RequestFactory for setting the request user, but it doesn't seem to work properly, as it still sees the request user as AnonymousUser, and returns AttributeError when checking the permission. Here's an example of my testcase: class TestSingleClient(TestCase): def setUp(self): self.factory = RequestFactory() self.user = User.objects.create( username='admin', password='admin', first_name='Name', last_name='Surname', email='user@gmail.com', is_staff=True ) AccountProfile.objects.create( phone='8999999999', occupation='tst_occupation', user=self.user ) Client.objects.create( name='Client1', type=0) def test_get_single_client(self): client = Client.objects.get(name='Client1') request = self.factory.get('/system/clients/{}/'.format(client.id)) request.user = self.user response = ClientView.as_view()(request, id=client.id) client_data = Client.objects.get(id=client.id) serializer = ClientSerializer(client_data) self.assertEqual(response.data, serializer.data) self.assertEqual(response.status_code, status.HTTP_200_OK) which results in: File "***/core/extra.py", line 10, in my_permissions_func roles = AccessRoles.objects.filter(user_groups=user.user_profile.group_id, can_read=True).\ AttributeError: 'AnonymousUser' object has no attribute 'user_profile' Any suggestions for fixing that? P.S. A similar topic was discussed here: Django RequestFactory doesn't store a User, which didn't bring me any closer to the answer. -
When using natural_keys in Django, how can I distinguish between creates & updates?
In Django, I often copy model fixtures from one database to another. My models use natural_keys (though I'm not sure that's relevant) during serialization. How can I ensure the instances that have been updated in one database are not inserted into the other database? Consider the following code: models.py: class AuthorManager(models.Manager): def get_by_natural_key(self, name): return self.get(name=name) class Author(models.Model): objects = AuthorManager() name = models.CharField(max_length=100) def natural_key(self): return (self.name,) Now if I create an author called "William Shakespeare" and dump it to a fixture via python manage.py dumpdata --natural_keys I will wind up w/ the following sort of file: [ { "model": "myapp.author", "fields": { "name": "Wiliam Shakespeare" } } ] I can load that into another db and it will create a new Author named "William Shakespeare". But, if I rename that author to "Bill Shakespeare" in the original database and recreate the fixture and load it into the other database then it will create another new Author named "Bill Shakespeare" instead of update the existing Author's name. Any ideas on how to approach this? -
Does Django's ConditionalGetMiddleware play nicely with multiple servers behind a load balancer?
I read in a few places that if you're using etags you might run into issues if your app is horizontally scaled. Does Django's ConditionalGetMiddleware work out of the box if you run multiple app servers behind a load balancer? -
Removing all after specific character in Django
This is my string: Text1 - Text2 - Text2 This is the output wanted: Text1 I looked for a filter that could do this, but couldn't find it. Thanks. -
Prefilling a form field through url
I have a register form , in which when a already registered email gets entered , it shows a error message with a login link, when clicked on login link it redirects to login page, here I want to prefill the the email field with that user email. I am using django. Does anyone know how to do it? I would appreciate some help. Thank you. my login url in urls.py: path('login/', views.login, name="login") my login link in error message: <a href="login/">login</a> Please let me what to do add to the link in url to prefill it with the user email ID. -
How to write create/update statements for a multiple depth django_restframework serializer
I'm new to Django's rest_framework and have been working alongside the documentation to build out the application I'm working on. I've been stuck on how to handle serializing multiple nested levels and have run out of ideas to try. My code looks like below: models.py from django.db import models class EntityType(models.Model): entity_type_id = models.AutoField(primary_key=True) name = models.CharField(max_length=10) class Meta: managed = True class Entity(models.Model): entity_id = models.AutoField(primary_key=True) entity_type = models.ForeignKey(to=EntityType, on_delete=models.CASCADE) class Meta: managed = True class Person(models.Model): person_id = models.AutoField(primary_key=True) entity = models.ForeignKey(to=Entity, on_delete=models.CASCADE) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) date_of_birth = models.DateField() gender = models.CharField(max_length=10) class Meta: managed = True serializers.py from .models import Entity, EntityType, Person from rest_framework import serializers class EntityTypeSerializer(serializers.ModelSerializer): class Meta: model = EntityType fields = ['entity_type_id', 'name'] class EntitySerializer(serializers.ModelSerializer): entity_type = EntityTypeSerializer(many=False, read_only=False) class Meta: model = Entity fields = ['entity_id', 'entity_type'] def create(self, validated_data): entity_type_data = validated_data.pop('entity_type') entity_type, _ = EntityType.objects.get_or_create(**entity_type_data) validated_data['entity_type'] = entity_type entity = Entity.objects.create(**validated_data) return entity class PersonSerializer(serializers.ModelSerializer): entity = EntitySerializer(many=False, read_only=False) class Meta: model = Person fields = ['person_id', 'entity', 'first_name', 'last_name', 'date_of_birth', 'gender'] depth = 2 def create(self, validated_data): entity_data = validated_data.pop('entity') entity, created = Entity.objects.get_or_create(**entity_data) validated_data['entity'] = entity person = Person.objects.create(**validated_data) return person urls.py from django.contrib … -
celery : Received unregistered task of type 'celery_deploy.tasks._stocks'
When I run celery as below: celery -A bookmarks worker -l INFO it returned: [2020-11-10 23:14:21,649: ERROR/MainProcess] Received unregistered task of type 'celery_deploy.tasks._stocks'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? KeyError: 'celery_deploy.tasks._stocks' my celery.py in project bookmarks directory(where the Django project settings.py is): from __future__ import absolute_import, unicode_literals import os from celery import Celery, platforms from datetime import timedelta from . import settings BROKER_URL = 'redis://localhost:6379/0' BACKEND_URL = 'redis://localhost:6379/1' os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bookmarks.settings') app = Celery('bookmarks', backend=BACKEND_URL, broker=BROKER_URL) app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda : settings.INSTALLED_APPS) platforms.C_FORCE_ROOT = True app.conf.update( CELERY_ACKS_LATE = True, CELERY_ACCEPT_CONTENT = ['json'], CELERY_FORCE_EXECV = True, CELERY_CONCURRENCY = 4, CELERYD_MAX_TASKS_PER_CHILD = 10, CELERYBEAT_SCHEDULE = { 'get_stock_': { 'task': 'celery_deploy.tasks._stocks', 'schedule': timedelta(seconds=21), }, }, ) @app.task(bind = True) def debug_task(self): print('Request: {0!r}'.format(self.request)) My tasks.py in Django app celery_deploy: from __future__ import absolute_import from celery import shared_task from django.core.cache import cache from urllib.request import urlopen from bookmarks.celery import app import json import redis apibase = "https://financialmodelingprep.com/api/v3/" apikey = "[KEY]" exchange_open_day = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] json_parsed = {} CACHE_TIMEOUT = 60*60 @app.task def _stocks(): url = apibase + "quotes/nyse" + "?" + apikey response = urlopen(url) stocks_parsed …