Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Model queries with relationships. How to do the right join
Let's say I have 2 Models: class Auction(models.Model): seller = models.ForeignKey(User, on_delete=models.CASCADE, related_name="seller") title = models.CharField(max_length=64) class Watchlist(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_watchlist') auction = models.ForeignKey(Auction, on_delete=models.CASCADE, related_name='auction_watchlist') The view receives a request, creates a context variable with the auction objects the are: associated with the user who made the request and that have been added to the Watchlist Model, sends it to the template. I have set up my view to work like this: @login_required def watchlist(request): watchlist_objects = Watchlist.objects.filter(user=request.user) auction_objects = Auction.objects.filter(auction_watchlist__in=watchlist_objects).all() context = {'watchlist_auctions': auction_objects} print(context) return render(request, "auctions/watchlist.html", context) -I make the first query to get the list of items in the watchlist associate with the user. -Then I use that to get another query from the Auction Model and I pass it to the template. In the template I can access the attributes of Auction to display them. (title, author, and others that I did not include for simplicity) The question is: Is this the "right way? Is there a better way to access the attributes in Auction from the first Watchlist query? It seems to me that I'm doing something overcomplicated. -
How did Django send_mail work without EMAIL_HOST_PASSWORD?
I tested Django send_mail() function which I needed for a project. I had the EMAIL_HOST set to the SMTP server provider my company uses, EMAIL_PORT to 587, EMAIL_USE_TLS to True. Both EMAIL_HOST_USER and EMAIL_HOST_PASSWORD was set to "" (empty string). Then I used the send_mail as: from djanog.core import mail mail.send_mail( "Django mail sample", "Body", "myemail@example.com", ["myemail@example.com"] ) But calling the view actually sent the email to my mail from my mail, but I didn't provide any password at all. I also set recipient_list to my colleague's mail, it worked. Then I tried to change the from_email to my colleague's mail it didn't work. I have my mail setup in Thunderbird in my system. So how did Django sent the mail without my email's password? Was it because of my setup in Thunderbird? What happened exactly? -
Django IndexView does not refresh current date
I am using Django IndexView to display main page in my application with some data. The data contains field named date_time. I want to display data for date_time range starting from current time when I visit page to some point in future My code looks like below: class IndexView(LoginRequiredMixin, generic.ListView): """View class for home page""" template_name = 'core/index.html' model = Match context_object_name = 'match_list' now = datetime.now() queryset = Match.objects.filter(season__is_active=True, date_time__range=(now, "2050-12-31")) Unfortunately Django the value for variable now is not updating when I visit the page, instead it is the date when I start the Django application. Is this behaviour caused by using IndexView? Should use some other view instead? Thanks for your input. -
React + Django: best practices for generating + downloading file?
I am working on an app which uses React and Django. I need a functionality whereby a user on the app can click a button and download a csv file on their machine. Importantly, the file is not already available anywhere, it needs to be generated on the fly when the user requests it (by clicking on the download button). I am thinking of implementing this flow: when the user clicks on the button, an API call is made which tells the backend to generate the csv file and store it in an s3 bucket the backend then sends a response to the frontend which contains the URL that the frontend can access to download the file from the s3 bucket the file gets downloaded Would this be a good approach? If not, what is the best practice for doing this? -
Social auth Django / DRF
I use djoser, social_django, rest_framework_social_oauth2 for registration and authorization of users in django by github. For create a new user (if it doesn't exist) or log in use /convert-token. But the site needs functionality to link a social account (if the user is logged in with username / password). How can I do it? I tried to redefine pipline, but it didn't work. Now after the request(/convert_token), a new user is being created, and i dont know how to link a social account to a specific user manually. Write if you need to attach a code or something else. Also, if there are other modules that implement this functionality, please write -
Filter by Count of related field object Django
I need to filter available equipments of objects in a model relating to quantity used field in another model My models: """ Available equipments """ class CompanyPersonalProtectiveEquipment(Base): name = models.CharField(verbose_name="Nome", max_length=255) description = models.TextField(verbose_name="Descrição") quantity = models.IntegerField(verbose_name="Quantidade", default=1) @property def availability(self): unavailable_quantity = 0 for personal_protective_equipment in self.patient_personal_protective_equipments.all(): unavailable_quantity += personal_protective_equipment.quantity return { "available": self.quantity - unavailable_quantity, "unavailable": unavailable_quantity } """ Used equipments """ class PatientPersonalProtectiveEquipment(Base): personal_protective_equipment_id = models.ForeignKey(CompanyPersonalProtectiveEquipment, verbose_name="EPI", on_delete=models.CASCADE, related_name="patient_personal_protective_equipments") date = models.DateField(verbose_name="Data entrega") quantity = models.IntegerField(verbose_name="Quantidade", default=1) Since I can't filter by a property of model CompanyPersonalProtectiveEquipment, I need to filter by a related quantity of PatientPersonalProtectiveEquipment to get objects that have a quantity available less than x. small_quantity_comparison = request.data.get("small_quantity_comparison") or 15 small_quantity = CompanyPersonalProtectiveEquipment.objects.filter(quantity_available__lte=small_quantity_comparison) Any idea? -
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empt
[django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.settings.py configure](https://i.stack.imgur.com/oCAZX.png)permission settings Can anyone explain what am I doing wrong, I am trying to hide the secret key, but I kept getting this error. I set up the secret key under the environment, but I believe the secret key can't be executed during operation. I have tried to change permission, thinking that will resolve the problem, but no luck. -
fields of type ManyToManyField do not save data when sending a request, DRF
Basically I do something like 'Archive of Our Own' and I don't have work saved or saved but ManyToMany field data is not saved views.py if request.method == 'POST': serializer = FanficSerializerCreate(data=request.data) if serializer.is_valid(): serializer.save() return Response({'fanfic': serializer.data}, status = status.HTTP_201_CREATED) models.py class Fanfic(models.Model): ... user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) fandoms = models.ManyToManyField(Fandom) pairings = models.ManyToManyField(Pairing) characters = models.ManyToManyField(Hero) tags = models.ManyToManyField(Tag) .... serializer.py class FanficSerializerCreate(ModelSerializer): fandoms = FandomSerializer(many=True, read_only=True) pairings = PairingSerializer(many=True, read_only=True) characters = HeroSerializer(many=True, read_only=True) tags = TagSerializer(many=True, read_only=True) class Meta: model = Fanfic fields = ['id', 'user', 'title', 'fandoms', 'pairings', 'characters', 'translate', 'categories', 'end', 'relationships', 'tags', 'description', 'note', 'i_write_for', 'created', 'updated'] I think the problem is in the serializer for another section, for example, adding a character with the same view code, but without the manytomanyfield fields in the models works fine when I write this in the serializers.py fandoms = FandomSerializer(many=True, read_only=True) pairings = PairingSerializer(many=True, read_only=True) characters = HeroSerializer(many=True, read_only=True) tags = TagSerializer(many=True, read_only=True) displays { "fanfic": { "id": 4, "user": 3, "title": "Claimed", "fandoms": [], "pairings": [], "characters": [], "translate": "NO", "categories": "M", "end": "ENDED", "relationships": "M/M", "tags": [], "description": "", "i_write_for": "...", "created": "2022-11-14T13:46:44.425693Z", "updated": "2022-11-14T13:46:44.425693Z" } } id is just … -
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 …