Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: A/B test with Google Optmize not working
I'm trying to create an A/B test for my webpage following this tutorial. I'm using a library called django-google-optimize and I've been able to configure it and make it work. The problem is that the A/B test is for the homepage, and for some reason it never works on the first load. I need to load the page twice in order to see the variant. Do you have and idea of what am I doing wrong? Could it be possible that this is related to GDPR stuff? -
running an emulator on a django site
This is a somewhat general question, but I am having trouble finding any information about it through searches... I have an android app that I would like to integrate into my website and am wondering about the possibility of either running an emulator as part of my web app, or else running an emulator on my server and interacting with sections of the information. Is anyone aware of any apps or libraries that work with web emulators, either with JS or Django? Thank you! I am really only finding information for making a phone app people can use for your site... -
Django IntegrityError with UniqueConstraint
I have a model with a UniqueConstraint on fields: site, name, type when status is either live or draft. However, when I create 2 objects with the same site, name and type ( one with status = live and another with status = draft), it is throwing this error: django.db.utils.IntegrityError: UNIQUE constraint failed: site_config_configuration.site_id, site_config_configuration.name, site_config_configuration.type I leveraged this doc for UniqueConstraint: https://docs.djangoproject.com/en/3.2/ref/models/constraints/#uniqueconstraint Here is my model: class Configuration(models.Model): CSS = 'css' SECRET = 'secret' TYPES = [ (CSS, 'css'), (SECRET, 'secret') ] LIVE = 'live' DRAFT = 'draft' HISTORY = 'history' STATUSES = [ (LIVE, 'Live'), (DRAFT, 'Draft'), (HISTORY, 'History') ] site = models.ForeignKey(Site, on_delete=models.CASCADE) name = models.CharField(max_length=255, blank=False) type = models.CharField( max_length=255, choices=TYPES) value = models.JSONField( null=True) status = models.CharField( max_length=20, choices=STATUSES) created = models.DateTimeField(editable=False, auto_now_add=True) modified = models.DateTimeField(editable=False, auto_now=True) class Meta(object): constraints = [ models.UniqueConstraint( fields=['site', 'name', 'type'], condition=(Q(status='draft') | Q(status='live')), name='unique config') ] Here is my simple test where I am creating 2 objects and it is throwing the django.db.utils.IntegrityError when config2 is being created: import pytest from site_config.models import Site, Configuration @pytest.mark.django_db def test_configuration_model(): """ Tests for Configuration Model """ site = Site.objects.create(domain_name='hello-world.org') config_live = Configuration.objects.create( site=site, name="$cta-button-border", type='css', value="2px solid #0090c1", status='draft', structure_version='v1', author_email='example@example.com') … -
django rest framework aggregation
I'm trying to group ingredients by product, let me explain. models.py class Product(models.Model): name = models.CharField( "nome del prodotto", max_length=25, unique=True, ) cost = models.DecimalField( "costo", max_digits= 5, decimal_places= 2, ) classification = models.ForeignKey( Classification, on_delete=models.SET_NULL, null=True, related_name="prodotti", verbose_name="classificazione" ) def __str__(self) -> str: return f"{self.name}" class Meta: verbose_name = "Prodotto" verbose_name_plural = "Prodotti" class Ingredient(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="ingredienti", verbose_name="prodotto" ) ingredient = models.ForeignKey( Product, on_delete=models.PROTECT, related_name="ingrediente", verbose_name="ingrediente" ) quantity = models.FloatField("quantità") class Meta: verbose_name = "ingrediente" verbose_name_plural = "ingredienti" serializers.py class IngredientSerializers(serializers.ModelSerializer): class Meta: model = Ingredient fields = "__all__" views.py class IngredientViewsets(viewsets.ReadOnlyModelViewSet): queryset = Ingredient.objects.all() serializer_class = IngredientSerializers right now view this, ungrouped list { "id": 1, "quantity": 250.0, "product": 6, "ingredient": 7 }, { "id": 2, "quantity": 100.0, "product": 6, "ingredient": 9 }, { "id": 3, "quantity": 100.0, "product": 6, "ingredient": 8 }, i would like to get something like this, a list with grouped products and the ingridient's list like this { "id": 1, "quantity": 250.0, "product": 6, "ingredient":[ { "ingredient": 7, "quantity": 250.0, }, { "ingredient": 9 "quantity": 100.0, }, { "ingredient": 8 "quantity": 100.0, }, ] } in short, I tried to figure out how it could be done, but I … -
Can I specify join strategy right in a django model?
Is there a way to specify a join strategy not in a query (with prefetch_related or select_related), but right in a django model (like lazy='joined' in sqlalchemy)? -
How to send OTP in Django before saving model to database
I am working on a project in Django, but I am having some obstacles. I have a model, say Transaction. What I want is that, when the button to create Transaction is clicked, an otp would be sent as SMS to a mobile phone. If the OTP is verified (entered correctly), then the Transaction would be saved into the database. If not, it would not be saved into the database. All the libraries I have seen, such as django-otp are mainly for user authentication. Can they be used for my use case? Are there other libraries that can do this? -
Django - how to edit Tags in tagify
I installed "pip install django-tagify" I was able to register with tagify on the admin page. I know how to render and display tags in an html template. But I don't know how to edit tags properly. My code is: forms.py class ProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ['name', 'bio', 'birth_date', 'location', 'picture', 'tag_s'] views.py class ProfileEditView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = UserProfile form_class = ProfileForm form1 = TagsField template_name = 'social/profile_edit.html' def get_success_url(self): pk = self.kwargs['pk'] return reverse_lazy('profile', kwargs={'pk': pk}) def test_func(self): profile = self.get_object() return self.request.user == profile.user profile_edit.html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form | crispy }} <div class="d-grid gap-2"> <button class="btn btn-success mt-3">Update!</button> </div> </form> The above code can edit tags but no options (automatic sort) look It works fine in the admin panellook I want to edit code with auto separator. Just like it is in the admin panel. How to do it ? -
custom scopes based on application
I am trying to define different scopes for each oauth application in Django-oauth-toolkit. I realized I can define different scopes on the settings file. But it seems that they apply to every new oauth-application I create. OAUTH2_PROVIDER = { 'SCOPES': { 'read': 'Read scope', 'write': 'Write scope', 'custom': 'Custom scope.' }, Is there a way to define scopes for a particular oauth-application? -
My uuid and Foreign key not wokring while deploying on heroku
My user model in django app: from django.db import models import uuid from django.contrib.auth.models import AbstractUser, PermissionsMixin # Create your models here. class user_model(AbstractUser): id = models.UUIDField(default=uuid.uuid4,unique=True,primary_key=True) age=models.CharField(max_length=200,blank=True) password=models.CharField(max_length=8,blank=True) dob=models.CharField(max_length=200,blank=True) phone=models.CharField(max_length=200,blank=True) def __str__(self): return self.username My foreignKey model in django: #from backdata.userdata.models import user_model from userdata.models import user_model from django.db import models from django.db.models.fields import CharField import uuid # Create your models here. class notes_by_user(models.Model): userNotes=models.ForeignKey(user_model , on_delete=models.CASCADE,related_name="notes",blank=False) id=models.UUIDField(default=uuid.uuid4,unique=True,primary_key=True) note=models.CharField(max_length=500,blank=False) def __str__(self): return self.note My settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } import dj_database_url db_from_env=dj_database_url.config(conn_max_age=600) DATABASES['default'].update(db_from_env) I am using postgresql as database for deploying on heroku.. and im getting this problem ..while migrating on bash console of heroku. -
Where is mistake in applying resizable widget?
I'm trying to apply resizable widget to many elements. I'm using django for backend. Here is script code: var sizes = JSON.parse(localStorage.sizes || "{}"); $(function (){ var d = $("[class=resizable]").attr("id", function (i) { return "resizable_" + i }); $.each(sizes, function (id, pos) { $("#" + id).css(pos) }) d.resizable({ containment: ".main-container", stop: function (event, ui) { sizes[this.id] = ui.sizes localStorage.sizes = JSON.stringify(sizes) } }) }); then in html: ... <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js" type="text/javascript"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js" type="text/javascript"></script> <script src="{% static 'notes/resize.js' %}"></script> ... <div id="draggable" class="ui-widget-content draggable resizable"> ... The same code works perfectly with draggable (positions instead of sizes and id=draggable instead of class=resizable). It's not even available in PyCharm hints with resizable widget. What is wrong? -
django.db.utils.ProgrammingError: relation does not exist LINE 1
I encountered an issue while migrating a DB using django: Traceback (most recent call last): File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "myBlog_category" does not exist LINE 1: ...g_category"."name", "myBlog_category"."name" FROM "myBlog_ca... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management_init_.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management_init_.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 368, in execute self.check() File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\importlib_init_.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1014, in _gcd_import File "", line … -
Hide title if for statement is is empty
I have an image gallery for each users post. However if a user has not uploaded any images i dont want to display the title "Image Gallery". How would I go about hiding the title if the for loop does not return anything. <a>Image Gallery</a> <div class="row"> {% for images in postgallery %} <div class="col-md-3"> <a href="{{ images.images.url }}" data-lightbox="image-1"> <img class="img-thumbnail" src="{{ images.images.url }}" /> </a> </div> {% endfor %} </div> I have tried a few variations of {% if imagegallery == 0 %} but I cant get anything to work as I would like -
'The requested resource was not found on this server.' error in django-rest-framework and pythonanywhere
I hope you are well I have a simple DRF project and I want to deploy it on Pythonanywhere I did all the desired configurations, photos of which you can see below But when I want to click on the uploaded photo link (bottom photo) this is my api whit a picture link I encounter a "The requested resource was not found on this server." error(bottom photo) this is the error pic this is my pythonanywhere media config: this is my configs this is my media setting in settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/pictures/' BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'uploaded_pictures') this is my urls.py code: urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('api/', include('gardesh.urls')) ] this is my models.py code: class Profile(models.Model): owner = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.CharField(max_length=150, null=True, blank=False) img = models.ImageField(upload_to='user/prof',null=False, blank=False) def __str__(self): return self.owner.username class Post(models.Model): owner = models.ForeignKey(User,on_delete=models.CASCADE) cover = models.ImageField(upload_to='user/cover',null=False, blank=False) caption = models.TextField(max_length=250, null=False, blank=False) title = models.CharField(max_length=40, null=False, blank=False, default='no') def __str__(self): return self.title class Comment(models.Model): auther = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField(max_length=150, null=False, blank=False) post = models.ForeignKey(Post, on_delete=models.CASCADE,related_name='comments') published_date = models.DateTimeField(null=False, blank=False, auto_now_add=True) parent = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='replys') You can see all … -
Selected item changes after sort
I am making Django app and i have a quesiton i have made a select menu to sort by prices. When I click submit button it sorts but it also go back to the default selected item. views.py def sortView(request): if request.method == "GET": try: min_price = int(request.GET.get('min-price')) max_price = int(request.GET.get('max-price')) items = Item.objects.filter(Q(price__gte=min_price) & Q(price__lte=max_price)) except: sorting_method = request.GET.get('select') if sorting_method == 'v1': items = Item.objects.order_by('price') elif sorting_method == 'v2': items = Item.objects.order_by('-price') print(sorting_method) return render(request, 'shop/sort.html', {'items': items}) HTML: It is in a 'form' so it is not the issue. <label class="sort__dropdown" for="cars">Sorting method</label> <select name="select"> <option value="v1">Price: low to high</option> <option value="v2">Price: high to low</option> </select> <button class="sort__submit">SORT</button> -
How To Effectively Serve React Files on The Same Port as Python Backend
I've created a backend with Python's Django that effectively runs a single API page on port 8000. I've also created a frontend that effectively renders a single page on port 3000. My goal is to have my Django serve my React files all on port 8000. To try and achieve this, I added the following to my settings.py REACT_APP_DIR = os.path.join(BASE_DIR, 'frontend') STATICFILES_DIRS = [ os.path.join(REACT_APP_DIR, 'build', 'static'), ] So, I ran npm run build in my frontend, and then ran python3 manage.py runserver 0.0.0.0:8000 where my manage.py is located; however, the npm build is still on the port 4000, and my Django is still rendering its files on port 8000. Thanks, if you could let me know the right way, or point me in the right direction, that would be great! Happy coding. -
Deploying Django website on Host Monster shared account
How can I deploy my Django website on host monster account? I know it can be on a shared host monster, but I cant find a way to push it into production. -
How to pass foreign key from form in Django
Used FlatAndMeter as foreign key in Rented in new function flat variable stores the id(primary key for FlatAndMter key -
A Django view is being called when I don't want it to be - why?
I am working on the cs50 web development Network assignment. Essentially it is a barebones twitter copycat. I have an issue where a view from views.py is being called when I do not intend it to be called. I know below I am posting more than is needed of my code below, but I feel I need to since I don't know where the problem area is. The views.py function follow_count() is being called eventually when I call the index view but cannot determine why. I.e. it is called every time the homepage is loaded. I do not want it to be called until it is specifically called by the clicked event listener in the js file. I cannot figure out what is causing follow_count() to run early, every time I load the index view. As I follow the path of different functions calling each other, it doesn't appear that anything is calling follow_count() yet it runs anyway. views.py: from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.http.response import JsonResponse from django.shortcuts import render from django.urls import reverse from .models import User, Post, Profile def index(request): print("index running in python") if request.method … -
ckeditor from id not loading in insertAdjacentHTML
Thanks in advanced I want to have ckeditor comment box inside replay textarea and its not loading. every thing load textarea loads but ckeditor not loading with that id i think it loads once at page render. Before click on replay enter image description here after clicking on replay button form appears enter image description here my ckeditor main comment form enter image description here my comment form javascript <script> function formExit() { document.getElementById('newForm').remove(); } function myFunction(id) { if (document.contains(document.getElementById("newForm"))) { document.getElementById("newForm").remove(); } var a = document.getElementById(id); a.insertAdjacentHTML('afterend', ' \ <form id="newForm" method="post"> \ <div class="re_form"> \ <h2>Replay:</h2> \ <button type="button" class="btn re_form_close bg-red" onclick="formExit()"> \ Close \ </button> \ <p> \ <select name="parent" class="d-none" id="id_parentt"> \ <option value="' + id + '" selected="' + id + '"></option> \ </select> \ </p> \ <p> \ \ <textarea placeholder="Comment here" name="body" id="id_body" class="re_form_textarea"></textarea>\ </p> \ {% csrf_token %} \ <button type="submit" class="btn btn-primary btn-lg btn-block bg-olive">Submit</button> \ </div> \ </form> \ '); } $('#myForm').trigger("reset"); </script> at this above line see id="id_body" here ckeditor loads but it showing empty textbox without ckeditor <textarea placeholder="Comment here" name="body" id="id_body" class="re_form_textarea"></textarea>\ my replay form <button class="bg-yellow btn" onClick="myFunction({{ node.id }})">Reply</button> -
I created a custom Signup and Sign in form, and model to store a new user. I can't do login in django using custom login template form?? plz suggest
which are the best option to create my own user's register model and login models and functionality, please suggest to me one best and simple way ? and how to validate forms? I tried and created signup forms, models and login. signup is worked but I don't know how to do login. So I need help to do these functionalities. -
query set lost when page changes in Django
I created a search system for my objects called Property and it filters and search through my objects well in first page but when I change pagination or ordering or changing page all filters gone and it sends all objects to template is there anyway to fix this? here is my code views.py class SearchView(ListView): model = Property template_name = 'property/properties-list.html' context_object_name = 'properties' ordering = '-pub_date' paginate_by = 8 def get_context_data(self, *args, **kwargs): context = super(SearchView, self).get_context_data(*args, **kwargs) """somthing""" return context def get_paginate_by(self, queryset): if self.request.GET.get("paginate_by") == "": return self.paginate_by return self.request.GET.get("paginate_by", self.paginate_by) def get_ordering(self): ordering = super(SearchView, self).get_ordering() if self.request.GET.get('sort_by') == "Name": return ('-title') elif self.request.GET.get('sort_by') == "Price": return ('-price') elif self.request.GET.get('sort_by') == "Date": return ('-pub_date') else: return self.ordering def get_queryset(self): location = self.request.GET.get('location') category = self.request.GET.get('category') look_for = self.request.GET.get('look_for') if location or category or look_for: if look_for == '' and category == '': queryset = Property.objects.filter(Q(city__icontains = location)) elif look_for == '': queryset = Property.objects.filter(Q(city__icontains = location) & Q(category__slug = category)) elif category == '': queryset = Property.objects.filter(Q(city__icontains = location) & Q(property_status = look_for)) else: queryset = Property.objects.filter(Q(city__icontains = location) & Q(category__slug = category) & Q(property_status = look_for)) else: queryset = Property.objects.all() return queryset Obviously I'm new … -
slug not auto generate after add page in django
I tried to add page for posts blog article for my django site.But it's slug model is not autogenerate after add it into the add post page but it work well in admin page. example in title field when i type how to master python fastly it will auto generated in slug field with "-" in only admin page.but when I type same thing on add post page it won't generate slug automatically. mycode models.py from django.db import models from django.contrib.auth.models import User from django_summernote.fields import SummernoteTextField from django.urls import reverse from django.template.defaultfilters import slugify STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) title_type = models.CharField(max_length=50, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = SummernoteTextField(blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) image = models.ImageField(upload_to='images',null=True, blank=True) class Meta: ordering = ['-created_on'] def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('home') views.py class AddPostView(CreateView): model = Post form_class = PostForm template_name = 'add_post.html' admin page And add post page -
Как добавить форму в django, для добавления пользователем разного товара? [closed]
models - тут несколько моделей и не понимаю как их перевести в View и на сам сайт class Product(models.Model): class Meta: abstract = True category = models.ForeignKey(Category, verbose_name='Категория', on_delete=models.CASCADE) title = models.CharField(max_length=255,verbose_name='Наименование') slug = models.SlugField(unique=True) image = models.ImageField(verbose_name='Изображение') description = models.TextField(verbose_name='Описание', null=True) price = models.DecimalField(max_digits = 9, decimal_places=2,verbose_name='Цена') class Notebook(Product): diagonal = models.CharField(max_length=255, verbose_name='Диагональ') display = models.CharField(max_length=255, verbose_name='Тип дисплея') Processor_freq = models.CharField(max_length=255, verbose_name='Частота ЦП') class SmartPhones(Product): diagonal = models.CharField(max_length=255, verbose_name='Диагональ') display = models.CharField(max_length=255, verbose_name='Тип дисплея') sd = models.BooleanField(default=True) -
beat: Connection error: Error while reading from socket: (104, 'Connection reset by peer')
I am deploying my Django backend on Heroku and I have used celery and Redis as a broker. But I am getting these errors on the worker log: 2021-08-23T17:43:05.148602+00:00 app[worker.1]: [2021-08-23 17:43:05,148: ERROR/Beat] beat: Connection error: Error while reading from socket: (104, 'Connection reset by peer'). Trying again in 32.0 seconds... 2021-08-23T17:43:35.862615+00:00 app[worker.1]: [2021-08-23 17:43:35,862: ERROR/MainProcess] consumer: Cannot connect to redis://:**@ec2-52-22-18-101.compute-1.amazonaws.com:30320//: Error while reading from socket: (104, 'Connection reset by peer'). 2021-08-23T17:43:35.862624+00:00 app[worker.1]: Trying again in 32.00 seconds... (16/100) setting.py: CELERY_BROKER_URL = 'redis://:*******.compute-1.amazonaws.com:port' CELERY_RESULT_BACKEND = 'redis://:***********.compute-1.amazonaws.com:port' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SELERLIZER = 'json' CELERY_TIMEZONE = 'Asia/Kolkata' BROKER_POOL_LIMIT = None celery.py : from __future__ import absolute_import from datetime import timezone import os from celery import Celery from django.conf import settings from celery.schedules import crontab, schedule # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'NewsApi.settings') app = Celery('NewsApi') app.conf.beat_schedule = { 'add-every-1-hour': { 'task': 'Api.tasks.task_news_update', 'schedule': crontab(minute=0, hour='*/1'), } } app.conf.update(timezone = 'Asia/Kolkata') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) -
How to set entry point after building the image in docker?
I'm trying to dockerize my django application and my Django has a dependency with GDAL and I added the dependency command in Dockerfile. The content in Dockerfile FROM ubuntu RUN apt-get update RUN apt install python -y RUN apt install python3-pip -y RUN apt install python3-dev libpq-dev -y RUN apt-get install gdal-bin RUN apt-get install libgdal-dev RUN apt install sudo WORKDIR /app COPY . /app RUN pip3 install -r requirements.txt ENTRYPOINT ["python3","manage.py" , "runserver" , "0.0.0.0:8000"] So, the problem here is that 6th line will ask for timezone like to select from 1-99 how can I pass those too as an argument in this file. So, to solve the above issue I remove line 6 and 7 and also the last line and installed it via docker run -it <image_name> and I committed it to a new image and now I can't execute the command I need which is python3 manage.py runserver 0.0.0.0:8000.