Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django - how do I handle exception for integrity error when deleting an instance?
I have two models, a Vehicle and an Asset where they are related with a one-to-one relationship. Vehicle model: class Vehicle(commModels.Base): vehicle_no = models.CharField(max_length=16, unique=True) vehicle_type = models.ForeignKey(VehicleType, related_name='%(class)s_vehicle_type', on_delete=models.SET_NULL, default=None, null=True) tonage = models.DecimalField(max_digits=4, decimal_places=1, blank=True, default=None, null=True) asset = models.OneToOneField( assetModels.Asset, related_name='vehicle', on_delete=models.CASCADE, null=True, ) ..... Asset model: reg_no = models.CharField(max_length=100, unique=True) name = models.CharField(max_length=255, null=True, blank=True) type = models.ForeignKey(AssetType, related_name='%(class)s_type', on_delete=models.SET_NULL, null=True) user = models.ForeignKey( orgModels.Company, related_name='%(class)s_user', on_delete=models.CASCADE, blank=True, null=True, ) When I delete a vehicle, the asset related to vehicle should be deleted as well. My code for deleting vehicle: @login_required def vehicle_delete_view(request, id=None): obj = get_object_or_404(Vehicle, id=id) if request.method == "DELETE": try: obj.delete() # this code causing an issue messages.success(request, 'Vehicle has been deleted!') except: print('exception triger-------') messages.error(request, 'Vehicle cannot be deleted!') return HTTPResponseHXRedirect(request.META.get('HTTP_REFERER')) return HTTPResponseHXRedirect(reverse_lazy('vehicle_list')) Now, I created a signal that deletes the asset tied to the vehicle upon successfully deleting it. signal.py: @receiver(post_delete, sender=models.Vehicle) def delete_asset(sender, instance, *args, **kwargs): print('signal is trigger') if instance.asset: asset = asset_models.Asset.objects.get(id=instance.asset_id) if asset: print('asset is being delete') asset.delete() On top of that, my vehicle has foreign key constraint on a few other models as well that points to it. When I create a new vehicle, it creates … -
Django restframework SerializerMethodField background work
I am writing a project in Django with rest framework by using SerializerMethodField. This method makes queries for every row to get data, or View collects all queries and send it to DB? Django can make it as one joint query? class SubjectSerializer(serializers.ModelSerializer): edu_plan = serializers.SerializerMethodField(read_only=True) academic_year_semestr = serializers.SerializerMethodField(read_only=True) edu_form = serializers.SerializerMethodField(read_only=True) def get_edu_plan(self, cse): return cse.curriculum_subject.curriculum.edu_plan.name def get_academic_year_semestr(self, cse): semester = cse.curriculum_subject.curriculum.semester return {'academic_year': semester.academic_year, 'semester': semester} def get_edu_form(self, cse): return cse.curriculum_subject.curriculum.edu_form.name class Meta: model = CurriculumSubjectEmployee fields = [ 'id', 'name', 'edu_plan', 'academic_year_semestr', 'edu_form' ] class SubjectViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = SubjectSerializer def get_queryset(self): contract = self.request.user.employee.contract if contract is None: raise NotFound(detail="Contract not found", code=404) department = contract.department cses = CurriculumSubjectEmployee\ .objects\ .filter(curriculum_subject__department=department) return cses -
ZeroDivisionError: division by zero using django
enter image description here i try klik staff profile in html ZeroDivisionError: division by zero -
How can I do to access to a foreign key in the other side?
I am working a on projects using Django. Here is my models.py : class Owner(models.Model): name = models.CharField(max_length=200) class Cat(models.Model): owner = models.ForeignKey(Owner, on_delete=models.CASCADE) pseudo = models.CharField(max_length=200) I did that : first_owner = Owner.objects.get(id=1) And I would like to do something like that first_owner.Cat to get all the cats from an owner I know I can do something like that : first_cat = Owner.objects.get(id=1) owner = first_cat.owner But I would like the reverse operation without using ManyToMany field because every cats has an only owner in my case. My aim is to do that using only one query. Could you help me please ? Thank you very much ! -
Trying to get two random samples to have the same matching foreignkey value
nooby programmer here. I am working on a django app that creates random fantasy character names that pull from the following models: `` class VillagerFirstNames(models.Model): first_name=models.CharField(max_length=30, unique=True) race = models.ForeignKey(Race, on_delete=models.CASCADE) def __str__(self): return self.first_name class VillagerLastNames(models.Model): last_name = models.CharField(max_length=30, unique=True) race = models.ForeignKey(Race, on_delete=models.CASCADE) def __str__(self): return self.last_name `` My issue is arising in my Views. In order to pull a random.sample I have to convert my query to a list like so: `` foreign_first = list(VillagerFirstNames.objects.all() foreign_first_random = random.sample(foreign_first, 3) context["foreign_first"] = foreign_first_random foreign_last = list(VillagerLastNames.objects.filter(race__race=foreign_first_random.race)) context["foreign_last"] = random.sample(foreign_last, 3) `` Basically, I want the last names pulled to be of the same race as the ones pulled in the first random sample. I'm having trouble figuring this one out, since the way I'm doing it above takes away the "race" attribute from foreign_first_random. Any help would be appreciated. I'm sorry if this is hard to follow/read. It's my first post. Thank you! -
Protect an existing wagtail application
I'm working on a Wagtail'based corporation intranet site. There are for now about 30,000 pages, with about 1500 users. I'm administrator of the application and the servers. Actual situation I'm serving the site through Apache2 with authnz_ldap, with 3 different LDAP domains. I'm using the REMOTE_USER auth. All pages are marked as "public", as the auth is provided globally. Wanted situation Serve the site with nginx, using django-auth-ldap as auth source (The auth module with multiple LDAP servers already works). Remote auth will be disabled. All users have to be connected to view the site content. My problem is that I have to protect the site globally, marking ALL pages as private, and avoid that editors set pages as public accidentally. Questions How to set the entire site as private ? How to block the public status of pages, to force the private status, aka. only visible for authenticated users ? Thanks for your help ! PS: Wagtail / Django versions are not relevant for now, as I'm migrating the application to newer versions. -
Running Scrapy with a task queue
I built a web crawler with Scrapy and Django and put the CrawlerRunner code into task queue. In my local everything works fine until run the tasks in the server. I'm thinking multiple threads causing the problem. This is the task code, I'm using huey for the tasks from huey import crontab from huey.contrib.djhuey import db_periodic_task, on_startup from scrapy.crawler import CrawlerRunner from scrapy.utils.log import configure_logging from scrapy.utils.project import get_project_settings from twisted.internet import reactor from apps.core.tasks import CRONTAB_PERIODS from apps.scrapers.crawler1 import Crawler1 from apps.scrapers.crawler2 import Crawler2 from apps.scrapers.crawler3 import Crawler3 @on_startup(name="scrape_all__on_startup") @db_periodic_task(crontab(**CRONTAB_PERIODS["every_10_minutes"])) def scrape_all(): configure_logging() settings = get_project_settings() runner = CrawlerRunner(settings=settings) runner.crawl(Crawler1) runner.crawl(Crawler2) runner.crawl(Crawler3) defer = runner.join() defer.addBoth(lambda _: reactor.stop()) reactor.run() and this is the first error I get from sentry.io, it's truncated Unhandled Error Traceback (most recent call last): File "/home/deployer/env/lib/python3.10/site-packages/twisted/internet/base.py", line 501, in fireEvent DeferredList(beforeResults).addCallback(self._continueFiring) File "/home/deployer/env/lib/python3.10/site-packages/twisted/internet/defer.py", line 532, in addCallback return self.addCallbacks(callback, callbackArgs=args, callbackKeywords=kwargs) File "/home/deployer/env/lib/python3.10/site-packages/twisted/internet/defer.py", line 512, in addCallbacks self._runCallbacks() File "/home/deployer/env/lib/python3.10/site-packages/twisted/internet/defer.py", line 892, in _runCallbacks current.result = callback( # type: ignore[misc] --- <exception caught here> --- File "/home/deployer/env/lib/python3.10/site-packages/twisted/internet/base.py", line 513, in _continueFiring callable(*args, **kwargs) File "/home/deployer/env/lib/python3.10/site-packages/twisted/internet/base.py", line 1314, in _reallyStartRunning self._handle... the task is set to run every 10 minutes, on the second run I'm getting … -
django.db.utils.IntegrityError: NOT NULL constraint failed: xx_xx.author_id ** author error in python/django
i'm trying to setup a databased website with Python and Django. I can not POST with my self created index-interface. It works with the django admin interface. Here's my code: views.py: from django.shortcuts import render from .models import Item from django.db.models import Q from django.contrib.auth.decorators import login_required from django.views.generic import ListView, DetailView from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic.edit import CreateView # Create your views here. def mylist(request): if request.method == 'POST': Item.objects.create(name = request.POST['itemName'], beschreibung = request.POST['itemBeschreibung'], link = request.POST['itemTag'], public = request.POST['itemPublic'], useridnummer = request.POST['itemUserid'],) post = request.save(commit=False) post.author = request.user all_items = Item.objects.all() if 'q' in request.GET: q = request.GET['q'] # all_items = Item.objects.filter(name__icontains=q) multiple_q = Q(Q(name__icontains=q) | Q(beschreibung__icontains=q) | Q(link__icontains=q)) all_items = Item.objects.filter(multiple_q) return render(request, 'index.html', {'all_items': all_items}) @login_required(login_url='user-login') def private(request): all_items = Item.objects.all() return render(request, 'private.html', {'all_items': all_items}) models.py: from django.db import models from django.conf import settings from datetime import date from django.contrib.auth import get_user_model # Create your models here. User = get_user_model() class Item(models.Model): created_at = models.DateField(default=date.today) name = models.CharField(max_length=200) beschreibung = models.TextField(max_length=10000, default="") link = models.CharField(max_length=200, default="") public = models.CharField(max_length=200, default="") useridnummer = models.CharField(max_length=200, default="") author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): #return self.title + ' | ' + self.author return str(self.id) + ' ' … -
Support german translation in export csv in django
I have the german translation on my website and I want to export data in CSV . Unfortunately it prints this "â€Ernährungssouveränität" instead of the german character "Ernährungssouveränität". what can I do? I tested utf-8 but it didn't work. response = HttpResponse(content_type="text/csv", charset="utf-8") -
Send app and its models' verbose_names via rest_framework?
I want to get app and its models' verbose_names via rest_framework. Let's say we have this catalog app and its model I just want to get all this verbose_names with django rest framework and send them via api. Are there any methods? -
Webhook Django - Local POST requests with Postman fail
I'm trying to receive webhooks within my Django app. I have created my app as follows: models.py : class Webhook(models.Model): """ Class designed to create webhooks. """ name = models.CharField(_('Nom'), max_length=50) url = models.URLField(_('URL')) event = models.CharField(_('Event'), max_length=50) active = models.BooleanField(_('Actif'), default=True) company = models.ForeignKey(Company, on_delete=models.DO_NOTHING, blank=True, null=True) id_string = models.CharField(_('ID'), max_length=32, blank=True, null=True) def __str__(self): return self.name def save(self, *args, **kwargs): current_url = Site.objects.get_current().domain self.id_string = get_random_string(length=32, allowed_chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') self.url = f'{current_url}/{self.company.id}/{self.id_string}' super(Webhook, self).save(*args, **kwargs) views.py: @csrf_exempt def webhook(request, pk, ref): if request.method == 'POST': print(request.body) return HttpResponse(request.body, status=200) else: return HttpResponse('Failed') urls.py: urlpatterns = [ path('webhook/<int:pk>/<str:ref>', webhook, name='webhook'), ] At the moment, I'm running my app locally. When I create a webhook object, I have the following URL : 127.0.0.1:8002/webhook/4/maPYUvcYZROq60cwJioIrqV5Y5OqXRiy When I try the following POST request: I always end up with the response "Failed". I don't understand why. -
Django converter type works for values >= 2 but not for 0 or 1
I am following a Django course on Udemy and have encountered this issue when trying to use the HttpResponseRedirect for the most basic of tasks. views.py looks like this: from django.shortcuts import render from django.http.response import HttpResponse, HttpResponseNotFound, Http404, HttpResponseRedirect from django.urls import reverse articles = { 'food': 'Food page', 'politics': 'Politics page', 'sports': 'Sports page', 'finance': 'Finance page', } def news_view(request, topic): try: result = articles[topic] return HttpResponse(result) except KeyError: print(type(topic)) raise Http404('404 GENERIC ERROR') # else: # articles[topic] = f"{(topic.title())} page" # return HttpResponse(articles[topic]) def add_view(request, num1, num2): # domain.com/first_app/3/4 --> 7 result = num1 + num2 return HttpResponse(str(result)) # domain.com/first_app/0 --> food def num_page_view(request, num): topics_list = list(articles.keys()) topic = topics_list[int(num)] return HttpResponseRedirect(reverse('topic-page', args=[topic])) urls.py looks like this: from django.urls import path from . import views # first_app/ urlpatterns = [ # path('<int:num1>/<int:num2>/', views.add_view), path('<int:num>', views.num_page_view), path('<str:topic>/', views.news_view, name='topic-page'), ] I tried typing in all indexes in the browser, 1 by 1, and I get the expected result for anything above 1: http://127.0.0.1:8000/first_app/2 redirects properly to http://127.0.0.1:8000/first_app/sports/ and so on up to 8 (I haven't populated the dictionary with more than 8 pairs). http://127.0.0.1:8000/first_app/0 and http://127.0.0.1:8000/first_app/1 return the custom 404 built into the "news_view" function, and the … -
Django view to export vsdx format
I am currently working on a view that needs to export visio files. I already have a view that exports doc files (see below), but not sure how to do that to return vsdx file as response from docx import Document def get(self, request, *args, **kwargs): document = Document() document.add_heading('Document Title', 0) response = HttpResponse( content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document') response['Content-Disposition'] = 'attachment; filename=download.docx' document.save(response) return response I'm aware that I need to update the content_type, and the way I need to open the file, but I've tried a few things and the response provided doesn't seem to open properly Any help is appreciated from vsdx import VisioFile def get(self, request, *args, **kwargs): filename = 'test.vsdx' response = HttpResponse(VisioFile(filename), content_type="application/vnd.visio", status=status.HTTP_200_OK) response["Content-Disposition"] = f"attachment; filename=temp.vsdx" return response -
django rest_framework ValueError: Cannot assign "'xx'": "xxx" must be a "xxx" instance
I'm trying to create an API to insert the current user's officeid but failed this is my models.py class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) userid = models.CharField(null=True, max_length=9) officeid = models.CharField(max_length=50, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email class ClearanceItem(models.Model): cl_itemid = models.CharField(primary_key=True, max_length=20, default=get_default_id) office = models.ForeignKey('ClearingOffice', models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'clearance_item' I did try to create this def perform_create(self, serializer): serializer.save(office=self.request.user.officeid) but it's giving me an error -
How to deploy django based application in AWS EC2 kubernetes cluster using loadbalancer and map the IP to DNS like godaddy
i have configured Kubernetes cluster in the AWS EC2 instance and using Kubernetes load-balancers exposed my docker based django project app. Please advise unable to connect Postgresql database using pgadmin. NAME STATUS ROLES AGE VERSION INTERNAL-IP EXTERNAL-IP OS-IMAGE KERNEL-VERSION CONTAINER-RUNTIME master-node Ready control-plane 22d v1.25.3 172.31.0.161 Ubuntu 18.04.6 LTS 5.4.0-1084-aws containerd://1.5.5 worker01 Ready 22d v1.25.3 172.31.0.203 Ubuntu 18.04.6 LTS 5.4.0-1088-aws containerd://1.5.5 After Execute below command error: ** Kubectl cluster-info dump** The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.9/site-packages/django/utils/deprecation.py", line 116, in call response = self.process_request(request) File "/usr/local/lib/python3.9/site-packages/django_tenants/middleware/main.py", line 39, in process_request tenant = self.get_tenant(domain_model, hostname) File "/usr/local/lib/python3.9/site-packages/django_tenants/middleware/main.py", line 27, in get_tenant domain = domain_model.objects.select_related('tenant').get(domain=hostname) File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 431, in get num = len(clone) File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 262, in len self._fetch_all() File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 51, in iter results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1173, in execute_sql cursor = self.connection.cursor() File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 33, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 259, in cursor return self._cursor() File "/usr/local/lib/python3.9/site-packages/django_tenants/postgresql_backend/base.py", line 135, in _cursor cursor = super()._cursor() File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 235, in _cursor self.ensure_connection() … -
Creating a dynamic input field with Django
I'm new to Django and when I press a button on a form, I want to dynamically create a new input field and save it to the database. I have no idea how to do this. Can you help with this? Since I don't know exactly how to do something, I couldn't try anything, but I know the form I need to create in html and javascript, but I have no idea how to save it to the database. -
Error when running "python manage.py runserver"
I'm doing a project where we are using Django to make a sales website. The day we started doing the project, it worked perfectly and there were no errors, but today i opened the project and tried to run the server and got this errors: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\gabri\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Users\gabri\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\gabri\Documents\Django\prj_lojavirtual\venv\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\gabri\Documents\Django\prj_lojavirtual\venv\Lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\gabri\Documents\Django\prj_lojavirtual\venv\Lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\gabri\Documents\Django\prj_lojavirtual\venv\Lib\site-packages\django\core\management\__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "C:\Users\gabri\Documents\Django\prj_lojavirtual\venv\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\gabri\Documents\Django\prj_lojavirtual\venv\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\gabri\Documents\Django\prj_lojavirtual\venv\Lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gabri\Documents\Django\prj_lojavirtual\venv\Lib\site-packages\django\apps\config.py", line 193, in create import_module(entry) File "C:\Users\gabri\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\gabri\Documents\Django\prj_lojavirtual\venv\Lib\site-packages\stdimage\__init__.py", line 1, in <module> from .models import JPEGField, StdImageField # NOQA ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gabri\Documents\Django\prj_lojavirtual\venv\Lib\site-packages\stdimage\models.py", line … -
Django/React CSRF Failed: Origin checking failed - http://localhost:8000/ does not match any trusted origins
I am building a web application using Django for the backend, RestApi for information transfer, and ReactJs for the frontend. When I run a POST request, in which I send data from a form, I get an error: "CSRF Failed: Origin checking failed - http://localhost:8000/ does not match any trusted origins."This means that Django recognizes the question but rejects it for some unknown reason. ReactJs is using a proxy to work with server data. I've read already solved articles on forum such as article 1, article 2, article 3, article 4, their solutions didn't help me. My request from ReactJs: const item = {tittle : data.target.tittle.value, description : data.target.description.value}; axios({ headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, method : "post", url : "api/articles/", data : item }).catch((e) => {console.log(e)}) Setting.py: CSRF_TRUSTED_ORIGINS = [ 'http://localhost:8000' ] ALLOWED_HOSTS = [ 'localhost', ] CORS_ORIGIN_WHITELIST = [ 'http://localhost:8000', ] CORS_ORIGIN_ALLOW_ALL = True class for processing requests in views.py: class ArticleList(generics.ListCreateAPIView): def post(self, request, format=None): serializer = ArticleSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request, format=None): snippets = Articles.objects.all() serializer = ArticleSerializer(snippets, many=True) return Response(serializer.data) -
In Django create a model method which determines an id for all objects that share the same foreign key
Kind of new to Django and while trying to create my first own project, i stumbled upon a problem. I have two different model classes: Star and Planet. Each planet has a foreignkey which belongs to a Star. Now I would like to have a field for Planet, which is basically the id/pk for its star system that is given on creation/discovery. All known planets of the star system already have their star system id and thus the newly created/discovered planet would require an id that is incremented on the last id that was given. Id Star Id in Star System Name 1 Sun 1 Neptune 2 Alpha Centauri 1 Hoth 3 Alpha Centauri 2 Coruscant 4 Sun 2 Earth 5 Sun 3 Jupiter 6 Alpha Centauri 3 Yavin4 7 Sun 4 Venus My models are looking like this models.py: class Star(models.Model): name = models.CharField(max_length=200) class Planet(models.Model): name = models.CharField(max_length=200) star = models.ForeignKey(Star, on_delete=models.CASCADE) def starSystemPlanetId(self): What could work in here? This new Id should be available to be called in a template like this: {% for planets in object_list %} <li> <p>Planet {{planets.name}} is the Nr. {{planets.customer_id}} planet of the star system</p> </li> {% endfor %} I have learned … -
How to calculate aggregate sum with django ORM?
I'm trying to group_by() data based on dates and with every day I want to calculate Count on that day also the total count so far. Sample output I'm getting: [ { "dates": "2022-11-07", "count": 1 }, { "dates": "2022-11-08", "count": 3 }, { "dates": "2022-11-09", "count": 33 } ] Sample output I'm trying to achieve: [ { "dates": "2022-11-07", "count": 1, "aggregate_count": 1 }, { "dates": "2022-11-08", "count": 3, "aggregate_count": 4 }, { "dates": "2022-11-09", "count": 33, "aggregate_count": 37 } ] -
django.core.exceptions.ValidationError: ['“” value has an invalid date format. It must be in YYYY-MM-DD format.'] problem
In 'models.py' i have this fields. first_name = models.CharField(max_length=30, null=True) last_name = models.CharField(max_length=30, null=True) date_of_brith = models.DateField(default='YYYY-MM-DD', null=True) email = models.EmailField(max_length=50, null=True) When i try to migrate. I get this error. I tryed to delete also the field and I still have the same error django.core.exceptions.ValidationError: ['“” value has an invalid date format. It must be in YYYY-MM-DD format.'] -
Django can't close persistent Mysql connection
Problem: Our Django application includes zipping large folders, which takes too long (up to 48 hours) so the Django connection with the database gets timed out and throws: "MySQL server has gone away error". Description: We have a Django version==3.2.1 application whose CONN_MAX_AGE value is set to 1500(seconds). The default wait_timeout in Mysql(MariaDB) is 8 hours. ExportStatus table has the following attributes: package_size zip_time Our application works this way: Zip the folders set the attribute 'package_size' of ExportStatus table after zipping and save in the database. set the attribute 'zip_time' of ExportStatus table after zipping and save in the database. Notice the setting of the columns' values in database. These require django connection with database, which gets timedout after long zipping process. Thus throws the MySQL server gone away error. What we have tried so far: from django.db import close_old_connections` close_old_connections() This solution doesn't work. Just after zipping, if the time taken is more than 25 minutes, we close all the connections and ensure new connection as: from django.db import connections for connection in connections.all(): try: # hack to check if the connection still persists with the database. with connection.cursor() as c: c.execute("DESCRIBE auth_group;") c.fetchall() except: connection.close() connection.ensure_connection() Upon printing … -
Django: Send mail to admin on every error raised
I have a project where we process data from various sources. My problem is I want a to send email every time there is an error or error raise my me. Currently I do something like this where on every raise I send a email. But I want a system where on every error there would be a email sent. # send an email alert email_content = "Email content" subject = "Subject" if settings.ENVIRONMENT == 'PROD': BaseScraper.email_alert_for_error( subject, email_content, ["admin@mail.com"], ) else: BaseScraper.email_alert_for_error( subject, email_content, ["admin@mail.com"], ) -
duplicate record when combine `distinct` and `order_by`
I'm using filter_backend for ordering my fields, but I have a problem, when I order by product__company__name, the API responds 1 result as me as expected, but with 2 records duplicated. I read the Note in this docs https://docs.djangoproject.com/en/3.2/ref/models/querysets/#distinct that If you order by fields from a related model, those fields will be added to the selected columns and they may make otherwise duplicate rows appear to be distinct. Since the extra columns don’t appear in the returned results (they are only there to support ordering), it sometimes looks like non-distinct results are being returned. So how can I resolve this problems ? Thank so much. filter_backends = [filters.SearchFilter, filters.OrderingFilter] search_fields = ["product__company__name"] ordering_fields = [ "created", "product__company__name", ] def get_queryset(self): if self.kwargs.get("shelf_type") == "want_to_read": result = ( MyModel.objects.filter( <logic_code> ) return result.distinct() -
insertion command via an API (Django project)
I am developing an e-commerce site using API calls. I would like to insert orders, the idea is after having selected several products on the cart (assume 4 products), I would like to insert them using the API only once, not with a loop. That is to say, I call the API only once and this inserts the 04 products into the database. And not put the API call in the shopping cart session loop, which will call the url 4 times. API Noted that if I remove its rows from the loop, it only inserts the last product url='http://myAPI/Product/postProduct' x=requests.post(url,json=data) Views.py @login_required def postCommande(request): for key,value in request.session.get("cart", {}).items(): data={ 'my_commande':[ { 'date':str(datetime.now()), 'name': request.user.client.name, 'content':[ { 'article':value.get('product_id'), 'designation':value.get('name'), 'quantite':value.get('quantity') } ] } ] } url='http://myAPI/Product/postProduct' x=requests.post(url,json=data)