Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Order models by a property or custom field in Django Rest Framework
Am having this kind of a Model, and I wanted to order by blog_views property, how best can this be done. This is the model : class Post(TimeStampedModel, models.Model): """Post model.""" title = models.CharField(_('Title'), max_length=100, blank=False, null=False) # TODO: Add image upload. image = models.ImageField(_('Image'), upload_to='blog_images', null=True, max_length=900) body = models.TextField(_('Body'), blank=False) description = models.CharField(_('Description'), max_length=400, blank=True, null=True) slug = models.SlugField(default=uuid.uuid4(), unique=True, max_length=100) owner = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) bookmarks = models.ManyToManyField(User, related_name='bookmarks', default=None, blank=True) address_views = models.ManyToManyField(CustomIPAddress, related_name='address_views', default=None, blank=True) likes = models.ManyToManyField(User, related_name='likes', default=None, blank=True, ) class Meta: ordering = ['-created'] def __str__(self): """ Returns a string representation of the blog post. """ return f'{self.title} {self.owner}' @property def blog_views(self): """Get blog post views.""" return self.address_views.all().count() I read about annotate but couldn't get a clear picture, how can I formulate this in my view. class PostList(generics.ListCreateAPIView): """Blog post lists""" queryset = Post.objects.all() serializer_class = serializers.PostSerializer authentication_classes = (JWTAuthentication,) permission_classes = (PostsProtectOrReadOnly, IsMentorOnly) filter_backends = [filters.SearchFilter, filters.OrderingFilter] search_fields = ['title', 'body', 'tags__name', 'owner__email', 'owner__username' ] I want to filter by a property in the URL -
Django Hosted on Apache: Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state:
I am trying to host a Django app on Apache 2.4. The service won't start and produces the folowing error [Thu Oct 28 13:12:37.898096 2021] [mpm_winnt:notice] [pid 5144:tid 628] AH00418: Parent: Created child process 7828 Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = 'python' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = 'C:\\apache24\\bin\\httpd.exe' sys.base_prefix = 'C:\\Users\\myuser\\AppData\\Local\\Programs\\Python\\Python310' sys.base_exec_prefix = 'C:\\Users\\myuser\\AppData\\Local\\Programs\\Python\\Python310' sys.platlibdir = 'lib' sys.executable = 'C:\\apache24\\bin\\httpd.exe' sys.prefix = 'C:\\Users\\myuser\\AppData\\Local\\Programs\\Python\\Python310' sys.exec_prefix = 'C:\\Users\\myuser\\AppData\\Local\\Programs\\Python\\Python310' sys.path = [ 'C:\\Users\\myuser\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip', '.\\DLLs', '.\\lib', 'C:\\apache24\\bin', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x00000fa0 (most recent call first): <no Python frame> [Thu Oct 28 13:12:38.413708 2021] [mpm_winnt:crit] [pid 5144:tid 628] AH00419: master_main: create child process failed. Exiting. The server ran before I did all the configurations and went to the "it worked" screen. I think it has to do with either my httpd-host conf <Directory /some/path/project> Require all granted </Directory> <VirtualHost *:80> ServerName localhost WSGIPassAuthorization On ErrorLog "C:/Users/myuser/Desktop/app.error.log" CustomLog "C:/Users/myuser/Desktop/app.access.log" combined WSGIScriptAlias / "C:/Users/myuser/Desktop/app/wsgi_windows.py" <Directory "C:/Users/myuser/Desktop/app/EmployeeKiosk"> <Files wsgi_windows.py> Require all granted </Files> </Directory> Alias … -
django many to one relationships
In the django document https://docs.djangoproject.com/en/3.2/topics/db/examples/many_to_one/, there are two tables, Report and Article, class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __str__(self): return "%s %s" % (self.first_name, self.last_name) class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) def __str__(self): return self.headline class Meta: ordering = ['headline'] My question, if you have a list of Reports, how would you get their articles? I've tried articles = [] for report in reports: article = Article.objects.filter(report = report) articles.append(article ) but this does not give me all my data. -
I'm building a website where users can download digit assets and I wanna know if anyone can throw some light to speed up the load time in Django
Hello guys please I would really appreciate it if someone could help me out with this website problem I am building a website where users can download digital assets from using Django, for example download website templates, graphics templates and all that. But now the issue is that when it's already hosted it takes a whole lot of time loading up because I think the files are slowing down the website and I don't really know the perfect way to fix this because I'm still kind of a beginner in Django and any help will be really appreciated. -
Django Form so many fields
I have a Django page using bootstrap and crispy forms that present a form. but the form is growing so much now that I probably have around 50 fields :( which are all within 1 massive HTML page. I'm pretty sure this is the wrong way to do it. Is it possible to split the forms into say 5 pages, but still have a submit button to post all of the fields to the database? For now, what I have done is to create tabs for each section of the giant form so it's easy than scrolling. I'm thinking it's probably better to create different views for each section and then link the data somehow back using an IndexKey or something? But i have no idea how i would configure the button to capture all the fields. I know this is a rubbish question, but I don't really know what to search for? Cheers -
DRF nested serialization without raw sql query
I've stuck with this problem for few days now. Tried different approaches but without success. I have two classes - Poll and PollAnswer. Here they are: class Poll(Model): title = CharField(max_length=256) class PollAnswer(Model): user_id = CharField(max_length=10) poll = ForeignKey(Poll, on_delete=CASCADE) text = CharField(max_length=256) what is the right way to get list of polls which have answers with used_id equal to the certain string with nested list of that user's answers? like this: { 'poll_id': 1, 'answers' : { 'user1_answer1: 'answer_text1', 'user1_answer2: 'answer_text2', 'user1_answer3: 'answer_text3', }, } and if it's the simple question i probably need some good guides on django orm. the first thing i tried was to make serializer's method (inherited from drf's ModelSerializer) but got an error that this class can't have such method. after that i tried to use serializer's field with ForeignKey but got polls nested in answers instead. right now i believe i can make Polls.objects.raw('some_sql_query') but that's probably not the best way. -
How to get and post data (serialize) in a desirable way (in both ways) using react & django-rest-framework
I'm working on a project where API based on django-framework works as a server, front is created using react/redux. My problem is, that i've written a few serializers regarding Django Users & Project. While fetching the project or projects i receive json in format: { "project_leader": { "id": user_id, "last_login": ..., "username": ..., "first_name": ..., "last_name": ..., } "project_name": string, "project_description": string, "done": boolean, "due_date": time } project_leader(User) data are the same format like in a serializer below. The data format i want to receive is nice, but the problem starts when i try to create new one. When i format the data in react component in a way like in serializer - i receive errors like: Cannot parse keyword query as dict When i format the data in a "django-way" - for example a user is only a user id, not the whole dictionary - the project is created but i what i receive back in a user field is just a user id, so i cannot dispatch action to the reducer because i don't have all the user data i map. Models: class Project(models.Model): project_leader = models.ForeignKey(User, on_delete=models.CASCADE) project_name = models.CharField(max_length=128) project_description = models.TextField() done = models.BooleanField(default=False) due_date … -
Right html side-bar covered by fixed html table
I'm not sure exactly what's happening here. It looks like there is the table element which shows the table but appears to expand white space almost all the way to the right side of the page which is covering my right side-bar and I don't know how to make it show up. Could someone confirm if this is the case or not and potentially give me some clues as to what to to do fix? I've tried changing the margins on both bits of html from Px to % and a few other things and can't figure it out. Sorry if this is a really long post, not sure what to cut out. Thanks! html: <html> <section id="header"> <header> <span class="image avatar"><img src="images/avatar.jpg" alt="" /></span> <h1 id="logo"><a href="#">Willis Corto</a></h1> <p>I got reprogrammed by a rogue AI<br /> and now I'm totally cray</p> </header> <nav id="nav"> <ul> <li><a href="#one" class="active">About</a></li> <li><a href="#two">Things I Can Do</a></li> <li><a href="#three">A Few Accomplishments</a></li> <li><a href="#four">Contact</a></li> </ul> </nav> </section> <div id="wrapper"> <!-- Main --> <div id="main"> <head> <title>Territorial</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" /> </head> <body style="margin: 25px;"> {% if state %} <h2>You Searched For: {{ state }}</h2> <table class= "content-table"> <thead> <tr> … -
Django adding millions of many to many objects fast
I currently have a running program that is able to add 500 records to a many to many relationship's through table a second but I have 50,000,000 rows of data to go through. Here are the models. class TransactionItem(models.Model): Type_Product = models.CharField(max_length=100, null=True, blank=True) Category = models.CharField(max_length=100, null=True, blank=True) Name = models.CharField(max_length=500, null=True, blank=True) def __str__(self): return self.Type_Product + self.Name class Transaction(models.Model): TransactionId = models.IntegerField(primary_key=True) Doctor = models.ForeignKey(Doctor, related_name="transactions", on_delete=models.CASCADE) Manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE) Type_Product_1 = models.CharField(max_length=100, null=True, blank=True) Category_1 = models.CharField(max_length=100, null=True, blank=True) Name_1 = models.CharField(max_length=500, null=True, blank=True) Type_Product_2 = models.CharField(max_length=100, null=True, blank=True) Category_2 = models.CharField(max_length=100, null=True, blank=True) Name_2 = models.CharField(max_length=500, null=True, blank=True) Type_Product_3 = models.CharField(max_length=100, null=True, blank=True) Category_3 = models.CharField(max_length=100, null=True, blank=True) Name_3 = models.CharField(max_length=500, null=True, blank=True) Type_Product_4 = models.CharField(max_length=100, null=True, blank=True) Category_4 = models.CharField(max_length=100, null=True, blank=True) Name_4 = models.CharField(max_length=500, null=True, blank=True) Type_Product_5 = models.CharField(max_length=100, null=True, blank=True) Category_5 = models.CharField(max_length=100, null=True, blank=True) Name_5 = models.CharField(max_length=500, null=True, blank=True) transactionitems = models.ManyToManyField(TransactionItem) Pay_Amount = models.DecimalField(max_digits=12, decimal_places=2, null=True) Date = models.DateField(null=True) Payment = models.CharField(max_length=100, null=True) Nature_Payment = models.CharField(max_length=200, null=True) Contextual_Info = models.CharField(max_length=500, null=True) The models have all the data added besides for the many to many objects. In order to create the many to many relationships I am using Type_Product, Category, … -
Weird problem with Django, runserver error
I have been able to run the runserver django command without any problems. But when I Ctrl+c close it, a huge error pops up. I am not able to understand anything mentioned in that error. File "/home/adithproxy/Desktop/helloapp/manage.py", line 22, in <module> main() File "/home/adithproxy/Desktop/helloapp/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python3/dist-packages/django/core/management/base.py", line 336, in run_from_argv connections.close_all() File "/usr/lib/python3/dist-packages/django/db/utils.py", line 224, in close_all connection.close() File "/usr/lib/python3/dist-packages/django/db/backends/sqlite3/base.py", line 248, in close if not self.is_in_memory_db(): File "/usr/lib/python3/dist-packages/django/db/backends/sqlite3/base.py", line 367, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "/usr/lib/python3/dist-packages/django/db/backends/sqlite3/creation.py", line 12, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'PosixPath' is not iterable Traceback (most recent call last): File "/home/adithproxy/Desktop/helloapp/manage.py", line 22, in <module> main() File "/home/adithproxy/Desktop/helloapp/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python3/dist-packages/django/core/management/base.py", line 336, in run_from_argv connections.close_all() File "/usr/lib/python3/dist-packages/django/db/utils.py", line 224, in close_all connection.close() File "/usr/lib/python3/dist-packages/django/db/backends/sqlite3/base.py", line 248, in close if not self.is_in_memory_db(): File "/usr/lib/python3/dist-packages/django/db/backends/sqlite3/base.py", line 367, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "/usr/lib/python3/dist-packages/django/db/backends/sqlite3/creation.py", line 12, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'PosixPath' is … -
How to validate input in a field on webpage without reloading the webpage?
(I am a beginner in django and html) How can I weed out spam entries in a particular field while taking input from a user? Also, how to show a message to the user that the entered value is not accepted because it's a spam, without reloading the webpage. For eg., in the field shown in image, if the user enters a number or something like test123 or something else that's not a proper name, my webpage should show a message to the user without loading the webpage that the entered value is not valid. I am also okay with putting a button that says validate to validate this name field value. How can I achieve this using Django+html+jquery? -
Django Custom User Model is not using The model manager while creating normal users
I'm trying to create a user from the Django rest framework's ModelViewset. (However, I've also tried to do the same with regular Django's model form. In both cases, the CustomUser model is not using the create_user function from the Model manager. My codes are as follows: Model Manager class CustomUserManager(BaseUserManager): def create_user(self, email, phone, full_name, **other_fields): email = self.normalize_email(email) if not email: raise ValueError("User must have an email") if not full_name: raise ValueError("User must have a full name") if not phone: raise ValueError("User must have a phone number") user = self.model( email=self.normalize_email(email), phone=phone, full_name=full_name, is_active=True, ) other_fields.setdefault('is_active', True) user.set_password(phone) user.save(using=self._db) return user def create_superuser(self, email, phone, full_name, password=None, **other_fields): if not email: raise ValueError("User must have an email") if not password: raise ValueError("User must have a password") if not full_name: raise ValueError("User must have a full name") if not phone: raise ValueError("User must have a phone number") user = self.model( email=self.normalize_email(email), full_name = full_name, phone = phone ) user.set_password(password) # change password to hash other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) user.save(using=self._db) return user Model: class CustomUserModel(AbstractBaseUser, PermissionsMixin, AbstractModel): email = models.EmailField(unique=True) username = models.CharField( max_length=150, unique=True, null=True, blank=True) phone = PhoneNumberField(unique=True) full_name = models.CharField(max_length=50, null=True, blank=True) is_active = models.BooleanField(default=False) is_staff … -
The FastCGI process exited unexpectedly - (Django iis hosting)
I am following this tutorial to hosting my django application on windows IIS Manager. After following all steps from the tutorial I have got the following HTTP Error 500.0 - Internal Server Error Is there any way to solve the issue?? I didn't find any solution for this... I am using, Python==3.10.0 Django==3.2.8 wfastcgi==3.0.0 IIS 10.0.17763.1 -
Django Rest baixar arquivo do banco de dados
Ola, sou iniciante no Django REST e estou tendo problemas de buscar arquivos pela api. Gostaria de saber como buscar pela api, a url do arquivo no banco de dados, para mostrar no Postman models class User(models.Model): arquivo = models.FileField("arquivo", upload_to="uploads/user", null=True, blank=True) serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' ViewSet class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer filter_backends = (filters.DjangoFilterBackend,) filter_fields = '__all__' -
How to save mysql output in mysql row
I have tables , there is 4 column id,count,sallary,age i try to run this code every day SELECT sum(count) FROM students WHERE time >= now() - INTERVAL 1 DAY and output want to save other tables or column to show sum in Django. What is best way? -
Building wheel for reportlab (setup.py) ... error
I am trying to run a requirements.txt file that happens to have ReportLab as a dependency but I have not been successful. I have tried pip install reportlab but the version that is installed doesn't seem to work with the other dependencies. I have used pip install -r requirements.txt --no-cache as well as appending -vvv on that command but I still haven't been successful. Any help with this? -
Django dropdown filter in querylist
how can I list the query list with a dropdown filter? with button or dynamicly, thank u! views; def kibana(request): kibana_list = kibanalar.objects.all() paginator = Paginator(kibana_list, 1000000000000000) page = request.GET.get('page') try: kmembers = paginator.page(page) except PageNotAnInteger: kmembers = paginator.page(1) except EmptyPage: kmembers = paginator.page(paginator.num_pages) return render(request, 'kibanalar.html', {'kmembers': kmembers}) models.py; class kibanalar(models.Model): datacenter = models.TextField(max_length=100, null=True) dashboardtipi = models.TextField(max_length=100, null=True) isim = models.TextField(max_length=100, null=True) link = models.TextField(max_length=100, null=True) kullaniciadi = models.TextField(max_length=100, null=True) sifre = models.TextField(max_length=100, null=True) -
Catch decimal.ConversionSyntax django import export
I need to be able to display the error regarding invalid decimals and invalid foreign keys into a much more user-friendly way. Invalid decimal error: Invalid foreign key error: Display the error along with all other errors here: -
Related Field got invalid lookup: icontains with search_fields
I am trying to add a related field with a Many-to-Many relationship, but I am getting this error : Related Field got invalid lookup: icontains This is my View : class PostList(generics.ListCreateAPIView): """Blog post lists""" queryset = Post.objects.all() serializer_class = serializers.PostSerializer authentication_classes = (JWTAuthentication,) permission_classes = (PostsProtectOrReadOnly, IsMentorOnly) filter_backends = [filters.SearchFilter] search_fields = ['title', 'body', 'tags'] Then my models : class Post(TimeStampedModel, models.Model): """Post model.""" title = models.CharField(_('Title'), max_length=100, blank=False, null=False) # TODO: Add image upload. image = models.ImageField(_('Image'), upload_to='blog_images', null=True, max_length=900) body = models.TextField(_('Body'), blank=False) description = models.CharField(_('Description'), max_length=400, blank=True, null=True) slug = models.SlugField(default=uuid.uuid4(), unique=True, max_length=100) owner = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) bookmarks = models.ManyToManyField(User, related_name='bookmarks', default=None, blank=True) address_views = models.ManyToManyField(CustomIPAddress, related_name='address_views', default=None, blank=True) likes = models.ManyToManyField(User, related_name='likes', default=None, blank=True, ) then the tags model : class Tag(models.Model): """Tags model.""" name = models.CharField(max_length=100, blank=False, default='') owner = models.ForeignKey(User, related_name='tags_owner', on_delete=models.CASCADE) posts = models.ManyToManyField(Post, related_name='tags', blank=True) class Meta: verbose_name_plural = 'tags' -
XAMPP MySQL cannot start
Xampp mysql phpmyadmin was running perfectly a few days ago. But now it's has this problem. I have tried stop the mysql in service.msc, i have tried to chang the port. I have tried to run XAMPP as administrator. But it's still not work. Could if because of a django project i've just installed? if that so, how do i fix it? enter image description here -
AWS Beanstalk Deployment Failing Due to WSGIPath
I'm trying to deploy a Django application the AWS ElasticBeanstalk. However, my deployments are failing due to a possible error in WSGIPath. Here is my configuration in /.ebextensions: option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "conf.settings" "PYTHONPATH": "/var/app/current:$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: conf.wsgi:application NumProcesses: 1 NumThreads: 15 Here is the error that I encounter: /var/log/web.stdout.log ---------------------------------------- Oct 28 04:17:54 ip-172-31-9-159 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker Oct 28 04:17:54 ip-172-31-9-159 web: worker.init_process() Oct 28 04:17:54 ip-172-31-9-159 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/workers/gthread.py", line 92, in init_process Oct 28 04:17:54 ip-172-31-9-159 web: super().init_process() Oct 28 04:17:54 ip-172-31-9-159 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_process Oct 28 04:17:54 ip-172-31-9-159 web: self.load_wsgi() Oct 28 04:17:54 ip-172-31-9-159 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi Oct 28 04:17:54 ip-172-31-9-159 web: self.wsgi = self.app.wsgi() Oct 28 04:17:54 ip-172-31-9-159 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi Oct 28 04:17:54 ip-172-31-9-159 web: self.callable = self.load() Oct 28 04:17:54 ip-172-31-9-159 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load Oct 28 04:17:54 ip-172-31-9-159 web: return self.load_wsgiapp() Oct 28 04:17:54 ip-172-31-9-159 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp Oct 28 04:17:54 ip-172-31-9-159 web: return util.import_app(self.app_uri) Oct 28 04:17:54 ip-172-31-9-159 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/util.py", line 363, in import_app Oct 28 04:17:54 ip-172-31-9-159 web: raise ImportError(msg % (module.rsplit(".", 1)[0], obj)) Oct 28 04:17:54 … -
Django Asyncronous task running syncronously with asgiref
I'm receiving notification via API and I should return HTTP 200 before 500 milliseconds. I'm using asgiref library for it, everything runs ok but I think is not actualy running asyncronously. Main viev In this view I receive the notificacions. I set 2 Print points to check timming in the server log. @csrf_exempt @api_view(('POST',)) @renderer_classes((TemplateHTMLRenderer, JSONRenderer)) def IncommingMeliNotifications(request): print('--------------------------- Received ---------------------') notificacion = json.loads(request.body) call_resource = async_to_sync(CallResource(notificacion)) print('--------------------------- Answered ---------------------') return Response({}, template_name='assessments.html', status=status.HTTP_200_OK) Secondary view After receiving the notification I call the secondary view CallResource, which I expect to run asyncronusly. def CallResource(notificacion): do things inside.... print('--------------------------- Secondary view ---------------------') return 'ok' Log results When I check the log, I always get the prints in the following order: print('--------------------------- Received ---------------------') print('--------------------------- Secondary view ---------------------') print('--------------------------- Answered ---------------------') But I suppose that the Secondary viewshould be the last to print, as: print('--------------------------- Received ---------------------') print('--------------------------- Answered ---------------------') print('--------------------------- Secondary view ---------------------') What am I missing here? Any clues welcome. Thanks in advance. -
django query is slow, but my sql query is fast
I have a very simple vie in my django application def notProjectsView(request): context = { 'projects':notProject.objects.all(), 'title':'Not Projects | Dark White Studios' } return render(request, 'not-projects.html', context) When I removed the context it ran fast, but it's a simple query and shouldn't be so long, the database also doesn't have a lot of records, it has 1 project and in the template I query project.notProjectImage.all which could cause an n+1 issue but I removed that part to test it and it was still slow Django debug toobar shows a ~50ms sql query while the actual request in the time tab is over 15 seconds -
Atomic Database Transactions in Django
I want to have atomic transactions on all the requests in the Django app. There is the following decorator to add an atomic transaction for one request, @transaction.atomic def create_user(request): .... but then, in this case, I'll have to use this decorator for all the APIs. I tried doing this in settings.py: DATABASES = { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'blah', 'USER': 'postgres', 'PASSWORD': 'blah', 'HOST': '0.0.0.0', 'PORT': '5432', 'ATOMIC_REQUESTS': True } But adding ATOMIC_REQUESTS does not seem to work in some cases. Is there any way so that I can apply atomic transactions for all APIs? -
Get percentage by category in Django
I'm struggling with the ORM, I need to be able to get the percentage of the product(s) per category. A product has a foreign key of category. The ideal result would be: Category 1 = 20% Category 2 = 15.6% I was able to get the total per category but failed to get the percentage Product.objects.filter(category__isnull=False).annotate(percentage=Count("pk")).order_by("category__name") I might be able to solve this with Subquery but failed on multiple approaches. Any ideas?