Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Gunicorn related error: ModuleNotFoundError: No module named 'django'
Below is my error log. I am running this command in the same folder as manage.py.... I have ensured that I am in a virtual environment and that Django is installed as a part of it. I don't understand why have issues with the following command -> gunicorn --bind 0.0.0.0:8000 ctfWebsite.wsgi (djangodev) jordangethers@jordangethers-VirtualBox:\~/FSU-CTF-Website-main/FSUweb/x_ctfWebsite$ gunicorn --bind 0.0.0.0:8000 ctfWebsite.wsgi \[2023-03-22 18:06:08 -0400\] \[9894\] \[INFO\] Starting gunicorn 20.1.0 \[2023-03-22 18:06:08 -0400\] \[9894\] \[INFO\] Listening at: http://0.0.0.0:8000 (9894) \[2023-03-22 18:06:08 -0400\] \[9894\] \[INFO\] Using worker: sync \[2023-03-22 18:06:08 -0400\] \[9895\] \[INFO\] Booting worker with pid: 9895 \[2023-03-22 18:06:08 -0400\] \[9895\] \[ERROR\] Exception in worker process Traceback (most recent call last): File "/usr/lib/python3/dist-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/usr/lib/python3/dist-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/usr/lib/python3/dist-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/lib/python3/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/lib/python3/dist-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/usr/lib/python3/dist-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/lib/python3/dist-packages/gunicorn/util.py", line 384, in import_app mod = importlib.import_module(module) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return \_bootstrap.\_gcd_import(name\[level:\], package, level) File "\<frozen importlib.\_bootstrap\>", line 1050, in \_gcd_import File "\<frozen importlib.\_bootstrap\>", line 1027, in \_find_and_load File "\<frozen importlib.\_bootstrap\>", line 1006, in \_find_and_load_unlocked File "\<frozen importlib`your text`.\_bootstrap\>", line 688, … -
anybody acn help me solved problev ModelForm has no model class specified
I'm learne django and i'm beginner.I don't understand what the problem is in my code. I get problem, ModelForm has no model class specified, when i try create reviews. And i'm realy don't understand wheare problem. def createreview(request, movie_id): movie = get_object_or_404(Movie, pk=movie_id) if request.method == 'GET': return render(request, 'createreview.html', {'form':ReviewForm(), 'movie': movie}) else: try: form = ReviewForm(request.POST) newReview = form.save(commit=True) newReview.user = request.user newReview.movie = movie newReview.save() return redirect('detail', Review.movie.id) except ValueError: return render(request, 'createreview.html', {'form':ReviewForm(), 'error':'bad data passed in'}) class ReviewForm(ModelForm): def __init__(self, *args, **kwargs): super(ModelForm, self).__init__(*args, **kwargs) self.fields['text'].widget.attrs.update({'class':'form-control'}) self.fields['watchAgain'].widget.attrs.update({'class':'form-check-input'}) class Meta: models = Review fields = ['text', 'watchAgain'] labels = {'watchAgain': ('Watch Again')} widgets = {'text': Textarea(attrs={'rows': 4}), } class Review(models.Model): text = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE) movie = models.ForeignKey(Movie, on_delete=models.CASCADE) watchAgain = models.BooleanField() def __str__(self): return self.text Please help solve it's problem -
why do i get this error mssg- Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings
I already have the latest version of python3 installed in my computer, why do i get this error message "Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases". This is the command am trying to run on Pycharm terminal window - "python3 manage.py runserver". I am using a window PC. It supposed to give me my development web server -
Django Selenium running tests in particular order
I'm having a problem running tests in a registration system using Django and Selenium since it starts testing my last written test in app/tests.py. I'm testing a registration system so I first wrote the user registration tests which it pass, then I wrote the login tests but when running ./manage.py test myapp it tries first to log in before registering a user. Any idea how to organize tests to run one before another, and, why is it running my last test before, any clues? -
How to loop to add event handler to buttons?
I have made my scripts.js and my html page and have successfully linked them together, however, the loop to add event listeners to my buttons doesn't seem to be applying. I have tried re writing the code and have tried to get a different value but nothing comes out as the output. JavaScript JavaScript console.log('Successful Connection!') var updateBtns = document.getElementsByClassName("update-cart") for (let i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function () { var productID = this.dataset.product var action = this.dataset.action console.log('product id:', productID, 'action', action) }) } HTML {% extends 'pages/home.html' %} {% block content %} <h3>Video Games</h3> <h6>Name | Publiser | Price | Rating</h6> {% for game in video_games %} <div class="card col-sm product" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">{{game.name}}</h5> <h6 class="card-subtitle mb-2 text-muted">This game is rated {{game.age_rating}}</h6> <h6 class="card-subtitle mb-2 text-muted">{{game.publisher}}</h6> <h6 class="card-subtitle mb-2 text-muted">${{game.price}}.00</h6> <h6>{{game.id}}</h6> <button onclick="" data-product="{{game.id}}" data-action="add" class="update-cart btn add-btn">Add to cart</button> </div> {% endfor %} {% endblock content %} -
Django AJAX can't find url
I'm using AJAX request to delete comment from product page, but django can't find url (I'm getting this log ). Box url: path('box/<int:id>', views.box, name='box') , delete url: path('delete-comment/<int:id>', views.delete_comment, name='delete_comment'),. My AJAX call: comment.addEventListener("click", () => { fetch(`delete-comment/${comment.dataset.comment_id}`, { method: "DELETE", headers: { "X-Requested-With": "XMLHttpRequest", } }) }); And view: def delete_comment(request, id): if request.headers.get("X-Requested-With") == "XMLHttpRequest": if request.method == 'DELETE': comment = Comment.objects.get(id=id) if comment.user == request.user: comment.delete() return HttpResponseBadRequest('ok') else: return HttpResponseBadRequest('Invalid request') I think there is something wrong with url. Why is django looking for /box/delete-comment/id, shouldn't it look for /delete-comment/id or /box/box-id/comment/id? I tried some options but none of them worked. I also couldn't find any similar problem. I even can't identify problem properly. Can you help me? -
Generated // in the URL (Django)
Somehow my program generated two slashes // when I tried to add a new Menu item. Don't know how to fix that Page not found (404) Request Method:POSTRequest URL:http://127.0.0.1:8000/restaurant/menu/desserts-menu//add_menuItem/ Using the URLconf defined in WAD_Group_Project.urls, Django tried these URL patterns, in this order: [name='index'] restaurant/ [name='index'] restaurant/ about/ [name='about'] restaurant/ menu/<slug:menu_name_slug>/add_menu_item/ [name='add_menu_item'] restaurant/ menu/<slug:menu_name_slug>/ [name='show_menu'] restaurant/ menu/<slug:menu_name_slug>/<slug:menuItem_name_slug>/ [name='show_menu_item'] restaurant/ add_menu/ [name='add_menu'] restaurant/ menu/<slug:menu_name_slug>/<slug:menuItem_name_slug>/add_review/ [name='add_review'] restaurant/ restricted/ [name='restricted'] admin/ accounts/ ^media/(?P<path>.*)$ The current path, restaurant/menu/desserts-menu//add_menuItem/, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Urls.py from django.urls import path from restaurant import views app_name = 'restaurant' urlpatterns = [ path('', views.index, name='index'), path('about/', views.about, name = 'about'), path('menu/<slug:menu_name_slug>/add_menu_item/', views.add_menu_item, name='add_menu_item'), path('menu/<slug:menu_name_slug>/', views.show_menu, name='show_menu'), path('menu/<slug:menu_name_slug>/<slug:menuItem_name_slug>/', views.show_menu_item, name='show_menu_item'), #Template shows form but without any functionality path('add_menu/', views.add_menu, name="add_menu"), path('menu/<slug:menu_name_slug>/<slug:menuItem_name_slug>/add_review/', views.add_review, name="add_review"), path('restricted/', views.restricted, name='restricted'), ] Views.py def show_menu(request,menu_name_slug): context_dict = {} try: menu = Menu.objects.get(slug=menu_name_slug) menuItems = MenuItem.objects.filter(menu=menu) context_dict['menuItems'] = menuItems context_dict['menu'] = menu except Menu.DoesNotExist: context_dict['menu'] = None context_dict['menuItems'] = None return render(request, 'restaurant/menu.html', context=context_dict) def show_menu_item(request, menu_name_slug, menuItem_name_slug): context_dict = {} try: menu = Menu.objects.get(slug=menu_name_slug) menuItem = MenuItem.objects.get(slug=menuItem_name_slug) … -
best way to generate statistical data in python for django objects
so i have 3 models; Employee, Products and Sale the Sale object has a JSON string of products sold in this sale, a category field, datetime of the sale and a reference to the Employee object who completed the sale i need to create graphs on demand where the user would specify the time period and intervals for the graph's X axis and choose what to display in the Y axis (choices are amount, total, ..etc for all sales or for a specific employee or product) what is the most efficient way to generate graph data for all these objects? for example i want to create a sales per day for a specific employee or a profit per day or hour or month that would count how many sales this employee made per day for a specified time period or create a profit per day for a specific category or product(which is saved as json in sale objects) problems arise when i want to calculate the graph data for a specific product because it is saved as json data in the Sale object. what i am looking for is an efficient way to generate all these graphs and tips for … -
Django ImageField specific directory is full (maximum number of files in linux dir)
While having this: profile_pic: ImageField = models.ImageField( _("profile_picture"), upload_to='profile_pic', blank=True, null=True) And 23M record I found out that profile_pic is "full" ("no space left on device") while having 300GB free. I thought of splitting the the files to folders with the first 3 letters, but how can I achieve that in the django ? REF: https://askubuntu.com/questions/1419651/mv-fails-with-no-space-left-on-device-when-the-destination-has-31-gb-of-space https://pylessons.com/django-images -
I can't find and fix the error in the code
I'm a beginner and I'm creating my first website on DJANGO and when writing the code I get this error products.append(Product(body,'red','100 pcs','9999 rub','4500 gramm')) ^^^^^^^^^^^^^^^ AttributeError: 'Product' object has no attribute 'append' please help me find what the code error is and fix it from django.shortcuts import render from django.http import HttpResponse,HttpRequest import random class Product: __MAX_ID = 0 def __init__(self, name:str, color: str, availability: str, cost: str, weight: str): self.id = Product.__MAX_ID self.name = name self.color = color self.availability = availability self.cost = cost self.weight = weight Product.__MAX_ID += 1 def __str__(self): return ( f'{self.name}\n' + f'color: {self.color}\n' + f'availability: {self.availability}\n' + f'cost: {self.cost}\n' + f'weight: {self.weight}\n' ) products=Product('nuke','red','100 pcs','9999 rub','4500 gramm') def test(request:HttpRequest): body=request.body.decode('UTF-8') products.append(Product(body,'red','100 pcs','9999 rub','4500 gramm')) return HttpResponse('\n'.join(str(product) for product in products))` I tried to change the product, but alas, nothing happened.maybe I have poor programming knowledge -
can not display form in django
i made a from , but for some reason it not show up when i try to display it. my forms supposed to collet information for blood donation. i did it by tutorial, and in the tutrial it just showed up, same as in any other tutorial i saw after. my models.py from django.db import models from django.contrib.auth.models import User class donate(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) doner_ID = models.CharField(max_length=9) blood_types = [ ('A+','A+'), ('B+','B+'), ('AB+','AB+'), ('O+','O+'), ('A-','A-'), ('B-','B-'), ('AB-','AB-'), ('O-','O-'), ] blood_type = models.CharField( max_length=3, choices=blood_types, default=blood_types[0], ) donation_date = models.DateField(auto_now_add=True) def __str__(self): return self.first_name my forms.py from django import forms from django.forms import ModelForm from .models import donate class donationForm(ModelForm): class Meta: model = donate fields = ('first_name', 'last_name', 'doner_ID', 'blood_type') my views.py from .forms import donationForm from .models import donate def donation(request): form=donationForm if request.method == 'POST': return render(request, 'main\donation.html', {'from':form}) else: return render(request, 'main\donation.html', {'from':form}) the donation.html page {% extends 'main\design.html'%} {% block design %} {{ errors }} <form action="" method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-outline-danger btn-block">Submit</button> </form> {% endblock %} -
Pytest-django won't post json data leading to assertion error. Not permission/method related
I'm writing a test for my django online project and I'm stuck in a function that returns 201 if data is valid (it's testing if data is valid when creating a new product for the store.). Django version 4.1.7 Django Rest Framework 3.14.0 pytest 7.2.2 pytest-django 4.5.2 The issue is that no matter what data I input in the function it always returns a 400 error. I'm sure it's not a permission issue because I've got authenticate(is_staff=True), which works in the previous functions. Also, I'm able to post a "Product" both in the Admin panel and in the products url if i'm logged with an account with Staff privileges. Here's the test_products.py code: from store.models import Collection, Product from rest_framework import status import pytest from model_bakery import baker @pytest.fixture def create_product(api_client): def do_create_product(product): return api_client.post('/store/products/', product) return do_create_product @pytest.mark.django_db class TestCreateProduct: def test_if_user_is_anonymous_returns_401(self, create_product): response = create_product({'title': 'a'}) assert response.status_code == status.HTTP_401_UNAUTHORIZED def test_if_user_is_not_admin_returns_403(self, authenticate, create_product): authenticate() response = create_product({'title': 'a'}) assert response.status_code == status.HTTP_403_FORBIDDEN def test_if_data_is_invalid_returns_400(self, authenticate, create_product): authenticate(is_staff=True) response = create_product({'title': ''}) assert response.status_code == status.HTTP_400_BAD_REQUEST assert response.data['title'] is not None def test_if_data_is_valid_returns_201(self, authenticate, create_product): authenticate(is_staff=True) response = create_product({ "title": "abc", "slug": "abc", "inventory": 1, "unit_price": 2, "collection": … -
raise ToolError(u"Command %s failed" % name) cfnbootstrap.construction_errors.ToolError: Command 01_makemigrations failed
I'm trying to deploy a Django project in AWS Elastic Beanstalk and seems to be an error with the command makemigrations.. I've configured it this way in my django.config file: container_commands: 01_makemigrations: command: "source /var/app/env/*/bin/activate && python3 manage.py makemigrations --noinput" leader_only: true 02_migrate: command: "source /var/app/env/*/bin/activate && python3 manage.py migrate --noinput" leader_only: true I don't know if my config is OK. It's my first time trying to deploy a project and I've followed the steps i've found in a tutorial.. -
Hello Ј'ai this error after deploying my application, Key error
Hello Ј'ai this error after deploying my application, I checked everything works locally for users on Django admin. I don't understand this mistake; Could you help me? It looks like it's from the library in django admin and he says he doesn't know the value 1, so maybe it's a problem with this version of django; I would like to point out that I am using version 3.2.12 of django and that I am using a mysql database. enter image description here -
Django - How do I update one field after my ModelForm has changed another?
I have a ModelForm that currently is used to update 2 fields in a Model. Users don't have to update both fields, however, when they do update the "study" field I need to trigger an update to the "user_study_tag" field to 'True' in the model instance. If they simply update the "notes" field (and not the "study" field), I don't want that update happening. forms.py class Run_UpdateForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") site_study_list = kwargs.pop("site_study_list") super(Run_UpdateForm, self).__init__(*args, **kwargs) self.fields["study"].queryset = Study.objects.filter(name__in=site_study_list) class Meta: model = Runs fields = ( "study", "notes", ) models.py class Runs(models.Model): name = models.CharField(max_length=200) guid = models.CharField(max_length=100) site = models.CharField(max_length=30, choices=site_choices, default="-") instrument = models.CharField(max_length=30, default="-") study = models.ForeignKey(Study, on_delete=models.CASCADE, null=True, blank=True) user_study_tag = models.BooleanField(default=False) project = models.CharField(max_length=30, default="-") inventory = models.BooleanField(default=False) inventory_missing = models.BooleanField(default=False) inventory_dismissed = models.BooleanField(default=False) qc_run = models.BooleanField(default=False) analysis_end_date = models.DateTimeField(default=datetime.now, blank=True) archive = models.BooleanField(default=False) notes = models.CharField(max_length=200, default="-", null=True, blank=True) def __str__(self): return f"{self.name}" I thought I could use the clean(self) method in the model, but I don't think that is the right way to handle this issue since I don't know how to compare the form self.study to the model study that is potentially being changed. -
List comprehension vs. for loop
In an effort to avoid Django ModelSerialization performance hits, I am looking at "serializing" a result set on my own. Research says that list comprehension should be the fastest, but my own tests are showing nested for loops being consistently faster. I have raw DB results (100) that need to be converted into a list of OrderedDict based on an ordered list of fields (14). Is my use case too complex for the list comprehension performance advantage, or my sample size too small? Maybe the performance is negligible? Nested for-loop (0.000919342041015625) serialized = [] start = time.time() for raw in results: result = OrderedDict() for index, field in enumerate(fields): result[field] = raw[index] serialized.append(result) end = time.time() print("For loop + for loop " + str(end - start)) Nested list comprehension (0.011911153793334961) serialized = [] start = time.time() serialized = [OrderedDict((field, raw[index]) for index, field in enumerate(fields)) for raw in results] end = time.time() print("List comprehensions + list comprehensions " + str(end - start)) For-loop + list comprehension (0.020151615142822266) serialized = [] start = time.time() for raw in results: result = OrderedDict((field, raw[index]) for index, field in enumerate(fields)) serialized.append(result) end = time.time() print("For loop + list comprehensions " + str(end - start)) -
How to broadcast a message to channels groups from the outside of consumer in django channel
If you have any suggestions and solutions please let me know. Currently I'm using channels=4.0.1 -
Images not appearing on page - Django
I'm writing my django tutorial project and I've run into a problem that hasn't happened before. When I try to display a picture loaded into a model instance using it, it does not want to be displayed in any way, while the rest of the model fields are displayed correctly: models.py: from django.db import models from django.urls import reverse class Product(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(unique=True) price = models.PositiveIntegerField() description = models.TextField() time_create = models.TimeField(auto_now_add=True) is_published = models.BooleanField(default=True) category = models.ForeignKey('ProductCategory', on_delete=models.PROTECT, verbose_name="Категории") brand = models.ForeignKey('Brand', on_delete=models.PROTECT, verbose_name="Бренд") photo_front = models.ImageField(upload_to="photos/%Y/%m/%d/", verbose_name="Главное фото", blank=True) photo2 = models.ImageField(upload_to="photos/%Y/%m/%d/", verbose_name="Фото 2", blank=True) photo3 = models.ImageField(upload_to="photos/%Y/%m/%d/", verbose_name="Фото 3", blank=True) photo4 = models.ImageField(upload_to="photos/%Y/%m/%d/", verbose_name="Фото 4", blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('product', kwargs={'product_slug': self.slug}) test.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{ title }}</title> </head> <body> {% for b in posts %} <p>{{ b.title }}</p> <img src="{{ b.photo_front.url }}"> {% endfor %} </body> </html> the result is the following output: Images not found And this is what the code outputs in the browser: Browser code And this is what the console says Not Found: /media/photos/2023/03/16/616036_XJFF9_1152_001_100_0000_Light-Cotton-T-shirt-with-Gucci-Blade-print.jpg Not Found: /media/photos/2023/03/16/623953_XDBBQ_4011_001_100_0000_Light-Regular-fit-washed-jeans.jpg Not Found: /media/photos/2023/03/16/clipboard_image_bfd7cf0e7879207e.jpg In general, I assume that … -
django getting data from other model with fk
i have this models class Bus(models.Model): bus_name = models.CharField('Name', max_length=10, unique=True, blank=False, null=False) __________________________________________________ class Soc(models.Model): value = models.FloatField(...) bus = models.ForeignKey(Bus....) __________________________________________________ class Iso(models.Model): value = models.FloatField(...) bus = models.ForeignKey(Bus....) What i want is access to iso value and soc value from the bus model but i dont know how ... any ideas?? -
Django API Query of 2198 Items takes almost 6min how can i improve the speed
I need to query my whole table. This is my view and serializer: @api_view(['GET']) def autofill_api(request): items = Product.objects.all() print(items) serializer = AutoFillSerializer(items, many=True) return Response(serializer.data) class AutoFillSerializer(serializers.ModelSerializer): # integrating the foreignkey Brand_Name into the serializer brand_name = serializers.CharField(source='brand.brand') class Meta: model = Product fields = __all__ Problem The Query takes almost 6min. These are the infos the Django Debug Toolbar gives me. 2198 SQL Queries 376888.26ms Are there any options to make this query faster? In the future i will use Django cache_page decorator. But for the case when my database is updated i don't want the user to wait 6min. -
encoding with 'idna' codec failed (UnicodeError: label empty or too long) Django send_mail
When sending a message to the mail via the send_mail function, an error appears - encoding with 'idna' codec failed (UnicodeError: label empty or too long) What could be the problem and how to make the encoding work correctly And what is most interesting, everything worked fine on another computer and messages were sent without any problems, so the error is clearly not in settings.py models.py file: from django.db import models from django.utils import timezone from django.urls import reverse from django.contrib.auth.models import User from slugify import slugify class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, related_name='blog_posts', on_delete=models.CASCADE) body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=9, choices=STATUS_CHOICES, default='draft') name = models.CharField(max_length=25, default='') email = models.EmailField(default='') to = models.EmailField(default='') comments = models.TextField(null=True) class Meta: ordering = ('-publish',) def get_absolute_url(self): return reverse('post-detail', args=( self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug, )) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(f'{self.title} {self.author}') super().save(*args, **kwargs) def __str__(self): return self.title settings.py file: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'my_mail@gmail.com' EMAIL_HOST_PASSWORD = 'my_password' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_USE_SSL = False views.py file: def post_share(request, slug): post … -
Custom BooleanField name in Django admin list filter
In Django admin I can change default True/False representation of BooleanField using choices argument. It appears in object page and list page. But it doesn't changes in admin list filter. Why? How can I change defaults 'All/Yes/No/Unknown' in list_filter? app/models.py CHOICES_BUILDING_CONDITION = ( (True, 'New'), (False, 'Old'), (None, 'Unknown'), ) class Flat(models.Model): is_new_building = models.BooleanField( 'Building condition', null=True, blank=True, choices=CHOICES_BUILDING_CONDITION ) app/admin.py class FlatAdmin(admin.ModelAdmin): list_filter = ('is_new_building', ) -
How to run django-apscheduler within a docker container that runs django via gunicorn
Is it possible to run django-apscheduler inside a docker container that runs django via gunicorn? Currently I have the problem that the custom manage.py command inside my entrypoint script runs forever and therefore gunicorn is never being executed. My entrypoint script: #!/bin/sh python manage.py runapscheduler --settings=core.settings_dev_docker My runapscheduler.py # runapscheduler.py import logging from django.conf import settings from apscheduler.schedulers.blocking import BlockingScheduler from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.triggers.cron import CronTrigger from django.core.management.base import BaseCommand from django_apscheduler.jobstores import DjangoJobStore from django_apscheduler.models import DjangoJobExecution from django_apscheduler import util from backend.scheduler.scheduler import scheduler logger = logging.getLogger("backend") def my_job(): logger.error("Hello World!") # Your job processing logic here... pass # The `close_old_connections` decorator ensures that database connections, that have become # unusable or are obsolete, are closed before and after your job has run. You should use it # to wrap any jobs that you schedule that access the Django database in any way. @util.close_old_connections # TODO: Change max_age to keep old jobs longer def delete_old_job_executions(max_age=604_800): """ This job deletes APScheduler job execution entries older than `max_age` from the database. It helps to prevent the database from filling up with old historical records that are no longer useful. :param max_age: The maximum length of time to retain … -
Django Queryset: group by two field values
I have a model like this Class ExchangeMarket(models.Model): base_currency = models.ForeignKey(Currency) quote_currency = models.ForeignKey(Currency) ... various other fields And some entries like base: EUR, quote: USD ... base: EUR, quote: USD ... base: USD, quote: EUR ... base: BTC, quote: USD ... ... I need to find entries sharing the base/quote combination, i.e. in my example that's the first three How to create such a queryset? If I do something like ExchangeMarket.objects.all().values('base_currency', 'quote_currency').annotate(pks=ArrayAgg('pk')) I will only find exact matches with same bases and quotes (like EUR/USD, first two of my entries) while I need to find both EUR/USD and USD/EUR. Thanks! -
Django: color test result in console
I have a Django project for which I have tests (nothing special). The thing is I'd like to have colored results when running tests and I don't know how to do that. On a daily basis, I run tests from my Ubuntu terminal with the command python3 ./backend/manage.py test --settings="backend.settings.testing" backend/ --no-input --verbosity=2 and applying the migrations looks like this at the beginning of the tests : whereas the tests themselves have uncolored results like so : My question is : Is there a simple way to get those ok colored in green and if applicable 'ko' in red ? Thank you in advance.