Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am making POST request from flutter app to Django-Rest user and getting null response
I'm a novice at this. I have been making POST requests from my flutter app to Django-Rest user and getting a null response on vendor name as copy pasted below. Other parts of the the json body are posting normally except for the user that the POST request is directed to. I want to be able to send the order from the flutter app to the particular user that posts the stock product. When I post I am able to send all the details such as name and number,but the vendor name gives that null response. I have tried googling but I don't understand what is wrong with the code this is the json response: { "vendor": null, "name": "Test", "number": "072345678", "address": "Linc street", "size": "3kgs", "note": "4th floor" }, `` The Post request in Flutter: Future<Order> createOrder(vendor, String name, String number, String address, String size, String note) async { final String apiUrl = 'http://10.0.2.2:8000/Order/'; final response = await http.post(apiUrl, body:{ vendor: vendor, "name": name, "number": number, "address": address, "size": size, "note": note }); if(response.statusCode == 201){ final String responseString = response.body; return orderFromJson(responseString); }else{ return null; } } and Order orderFromJson(String str) => Order.fromJson(json.decode(str)); String orderToJson(Order data) => … -
how do I break up long words in my Django project?
so I have a username on my site that's overflowing out of the content box as you can see here so I thought h1, h2, h3, h4, h5, h6 { color: #44444 overflow-wrap: break-word;}. would help but that it didn't the code for the profile page is as follows all CSS for the profile page works except for the overflow. if anyone could help me I would appreciate it :) -
Django application - singleton data
I have to configure my Django application. It has several fields, which can vary from time to time and have an impact on all models. It can be modified via Django settings file, but I wish it would be possible to change them in Django admin panel. Is it possible? I do not want to declare a model, which can have a lot of instances, cause it would be a hack. -
Django rest framework API with filter
Models.py Categories: class Category_product(models.Model): category_name = models.CharField(max_length=200, unique=True) def __str__(self): return self.category_name Products: class Warehouse(models.Model): category_product = models.ForeignKey( Category_product, on_delete=models.CASCADE) product_name = models.CharField(max_length=200, unique=True) condition = models.BooleanField(default=False) amount = models.IntegerField() barcode = models.BigIntegerField() f_price = models.CharField(max_length=255, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.product_name urls.py path('products-list/', views.WarehouseList.as_view()), Views.py class WarehouseList(generics.ListCreateAPIView): queryset = Warehouse.objects.all() serializer_class = WarehouseSerializer I want to get products by exact category For example: I have product category { "id": 1 "category_name": "Electronics" } If I send GET request to api/products-list/?cat=1 I want to get products which have this category -
Store first name of user using foreign key on User model django
right now I'm working with a blogging system which I am making without using an admin site of django. So, I have to create a blog post models and views functions that store the blog data to database manually.In that I have used User login with custom user models and a foreign key for store logged user's first name in BlogData database from User model. My problem is that I cant directly connect to user's first name by views.Is there any way to do it. Here is my code, Models.py (BlogData) from django.db import models from login.models import User # Create your models here. class BlogData(models.Model): blogger_name = models.ForeignKey(User,on_delete=models.CASCADE,related_name='blogger_name') publish_date = models.DateTimeField(auto_now=True) blog_title = models.TextField() blog_subtitle = models.TextField() blog_body = models.TextField() blog_baseimg = models.ImageField(upload_to='pics',null=True) def __str__(self): return self.blog_title Views.py from django.shortcuts import render from .models import languages,BlogData def submit_post(request): if request.method == 'POST': blg_tt = request.POST['blog_title'] blg_stt = request.POST['blog_subtitle'] blg_cnt = request.POST['blog_content'] blg_img = request.POST['blog_img'] data = BlogData.objects.create(blog_title=blg_tt,blog_subtitle=blg_stt,blog_body=blg_cnt,blog_baseimg=blg_img) data.save() return render(request,"index.html") Models.py (Custom User Model) from django.db import models from django.contrib.auth.models import AbstractUser,BaseUserManager # Create your models here. class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self,email,password,**kwargs): email = self.normalize_email(email=email) user = self.model(email=email) user.set_password(password) user.save(using = self._db) return user def create_user(self,email,password = … -
Django menu Tree foreach
This is my models in Django: from django.db import models # Create your models here. statusChoice = ((1, 'Show'), (2, 'Hide')) class newCatagory(models.Model): cat_name = models.CharField(max_length = 255) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank = True) created_at = models.DateTimeField(auto_now_add=True) status = models.SmallIntegerField(choices = statusChoice, null=True) def __str__(self): return "%s, --%s" % (self.parent, self.cat_name) class products(models.Model): pro_name = models.CharField(max_length = 255, null =True) sub_cat_id = models.ForeignKey(newCatagory, on_delete=models.CASCADE, null=True, blank = True) pro_image = models.ImageField(null = True) pro_price = models.FloatField(null = True) description = models.TextField(null = True) status = models.SmallIntegerField(choices = statusChoice, null=True) created_at = models.DateTimeField(auto_now_add=False, null=True) def __str__(self): return self.pro_name i am creating models like above. But i don't know how to show my catagory to my view. How can i do that This is my templates html: <li><a href="#">{{This is catagory}}</a> <ul class="sub-menu"> <li><a href="#">{{this is subcatagory}}</a></li> </ul> </li> I am trying to use for loop but don't know how to use, please help -
How to use placeholders outside django-CMS?
I'm trying to implement the documentation on django-cms on How to use placeholders outside the CMS It seems possible to define a field in a model app external to the CMS which will behave like the djangocms-text-ckeditor But I can't get this 'templatetag' to work {% extends 'base.html' %} {% load cms_tags %} {% block content %} <h1>Title page info</h1> {% render_placeholder object.short_text "640" %} {% endblock content %} Here my info.models.py from django.db import models from cms.models.fields import PlaceholderField class MsgDet(models.Model): title = models.CharField(max_length=255) short_text = PlaceholderField('content') I've create a small django-cms project following the django-cms tutorail using django CMS installer. The source code is on GitHub under OpenHBP/PlaceholderField. I've added a simple info app to the cms and I try to display "MsgDet.short_text" fields inside a "CKEditor like" plugin. A double-click on the CMS home page opens a CKeditor window. I would like to achieve the same result on my info page! I know this can be achieved by using RichTextField from ckeditor but I would like to use "PlaceHolderFiled" in order to have access to djangoCMS plugins: picture/image or file. Note that I've also tried with django-ckeditor-filebrowser-filer but the project seems deprecated and pdf upload does not … -
Serving Django and React from a single Docker container
I have build a web app using Django backend (Django REST Framework) and React Frontend. However, the two apps aren't separate, the Django backend is serving he React frontend directly through URL routing. For that reason, if I want to dockerize the app, I can't put the frontend and backend into separate containers. The reason I want to keep the two apps integrated like this is because one small part of the frontend is being served by Django because I want to use Django's easy-to-use user authentication models instead of doing all of that on the frontend. I know this is bad practice, but is it possible to get both the required dependencies for the frontend and backend and then run both in one docker container, and if so how would I go about doing it? (I have done research on this and have only found resources on serving Django and React from two separate containers). -
Django annotate + SUM how to get all entries
My models class Machine(models.Model): machineName = models.CharField(verbose_name="Machine Name", max_length=20, blank=False, null=False) class SalesReport(models.Model): machine = models.ForeignKey(Machine, on_delete=models.CASCADE, null=False, blank=False) deviceDate = models.CharField(max_length=200, null=True, blank=True) serverDate = models.DateTimeField(auto_now_add=True) I have 3 machines, I wanted to get the total sales from each machines for the last 7 days. my query is from django.db.models import Sum, Value as V from django.db.models.functions import Coalesce SalesReport.objects.values("serverDate__date", "machine__machineName").annotate( ... sales=Coalesce(Sum("totalPrice"),V(0))).filter( ... serverDate__gte=week_start, ... serverDate__lte=week_end) Which gives the following result, [{'serverDate__date': datetime.date(2020, 7, 22), 'machine__machineName': 'machine__1', 'sales': 15.0}, {'serverDate__date': datetime.date(2020, 7, 28), 'machine__machineName': 'machine__1', 'sales': 145.0}, {'serverDate__date': datetime.date(2020, 7, 28), 'machine__machineName': 'machine__2', 'sales': 270.0}, {'serverDate__date': datetime.date(2020, 7, 28), 'machine__machineName': 'machine__3', 'sales': 255.0}] What i am trying to get is [{'serverDate__date': datetime.date(2020, 7, 22), 'machine__machineName': 'machine__1', 'sales': 15.0}, {'serverDate__date': datetime.date(2020, 7, 22), 'machine__machineName': 'machine__2', 'sales': 0.0}, {'serverDate__date': datetime.date(2020, 7, 22), 'machine__machineName': 'machine__3', 'sales': 0.0}, {'serverDate__date': datetime.date(2020, 7, 28), 'machine__machineName': 'machine__1', 'sales': 145.0}, {'serverDate__date': datetime.date(2020, 7, 28), 'machine__machineName': 'machine__2', 'sales': 270.0}, {'serverDate__date': datetime.date(2020, 7, 28), 'machine__machineName': 'machine__3', 'sales': 255.0}] I am trying to do it with Coalesce, but i'm getting it wrong . *I'm using mysql as back end. a db specific query is also fine . -
How can I update a specific key on a HStoreField in django?
I have a Django model with a HStoreField and I'm trying to update a specific key on the data in this field. I'm trying not to load the model into memory as there's a fair bit of data and it would be for a lot of object instances. I have my Result object which has 'data' field and I'm trying to update an 'existingkey', I've tried: Result.objects.update(data__existingkey='new_value') But I just get FieldDoesNotExist: ResultsContainer has no field named 'data__existingkey' I thought this would work as Result.objects.filter(data__existingkey='value') works fine. Any suggestions would be appreciated many thanks -
Is Casbin a better choice to create CRUD Users in Django/Pymongo?
I'm using a MongoDb database and I would like to use PyCasbin to manage the permissions of every routing for each user,Is there a better plan than Casbin to create a CRUD dashboard? If not, how to create simple CRUD users with PyCasbin in Pymongo and Django? I pasted PyCasbin sample in mongoengine as below: # adapter.py import casbin from casbin import persist from mongoengine import Document from mongoengine import connect from mongoengine.fields import IntField, StringField class CasbinRule(Document): ''' CasbinRule model ''' __tablename__ = "casbin_rule" ptype = StringField(required=True, max_length=255) v0 = StringField(max_length=255) v1 = StringField(max_length=255) v2 = StringField(max_length=255) v3 = StringField(max_length=255) def __str__(self): text = self.ptype if self.v0: text = text+', '+self.v0 if self.v1: text = text+', '+self.v1 if self.v2: text = text+', '+self.v2 if self.v3: text = text+', '+self.v3 return text meta = { 'indexes': [ {'fields': ('ptype', 'v0', 'v1', 'v2'), 'unique': True} ] } def __repr__(self): return '<CasbinRule :"{}">'.format(str(self)) class Adapter(persist.Adapter): """the interface for Casbin adapters.""" def __init__(self,dbname,host): connect(db=dbname,host=host) def load_policy(self, model): ''' implementing add Interface for casbin \n load all policy rules from mongodb \n ''' lines = CasbinRule.objects() for line in lines: persist.load_policy_line(str(line),model) # c_middleware.py class CMiddleware: """ Cmiddleware. """ def __init__(self, get_response): self.get_response = get_response … -
How to handle django returning Nonetype has no len()
I'm getting this Nonetype error. I'm stuck at it all day. First i was getting MultiDictError after changing it to filetitle = request.POST.get('bob') contentitle = request.POST.get('pop') It seems to work and now this error. views.py: def add(request): filetitle = request.POST.get('bob') contentitle = request.POST.get('pop') return render(request, "add/add.html"),{ "entries":util.save_entry(filetitle,contentitle) } utills.py def save_entry(title, content): """ Saves an encyclopedia entry, given its title and Markdown content. If an existing entry with the same title already exists, it is replaced. """ filename = f"entries/{title}.md" if default_storage.exists(filename): default_storage.delete(filename) default_storage.save(filename, ContentFile(content)) add.html {% block body %} <h1>Create New Page</h1> <form action="encyclopedia:add" method="post"> {%csrf_token%} <input name="bob" type="text" placeholder="Enter the Markdown content " id="abz"> <textarea name="pop" rows="20" cols="25" value="content"></textarea> <input type="submit" value="submit" /> </form> {% endblock %} error: Internal Server Error: /add Traceback (most recent call last): File "/home/knox/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/knox/.local/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/knox/.local/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/knox/django/wiki/encyclopedia/views.py", line 44, in add "entries":util.save_entry(filetitle,contentitle) File "/home/knox/django/wiki/encyclopedia/util.py", line 28, in save_entry default_storage.save(filename, ContentFile(content)) File "/home/knox/.local/lib/python3.8/site-packages/django/core/files/base.py", line 128, in __init__ self.size = len(content) TypeError: object of type 'NoneType' has no len() I tried several things but none of them seems … -
rendering different buttons dynamically in the same page based on different unique conditions django
I am working on an education project that needs to get different buttons to display based on a certain status and a unit code tied to it. In my HTML view, it has multiple education topics for the user to click on "Start" to learn on the particular topic and it would change to "Continue" after they have started. The "Start" would have a "Completed" status tied to it, and for "Continue" it has a "Progressing" status. Each education topics have their own unique unit code such as "UTLP1", "UTLP2", "FXUCP1". Each of it is a unique entity on their own, therefore both status and unique code must be true or false for it to change its state, as all of the records that the user-generated are stored under a single table. HTML view of it {% if check_lesson_lec_progress %} <input type="text" name="lesson_topic_uc" value="UTLP1" hidden/> <button type="submit" class="btn btn-outline-salmon w-25" name="lesson_form_submit" value="progressing_uc_ut">Continue</button> {% else %} <input type="text" name="lesson_topic_uc" value="UTLP1" hidden/> <button type="submit" class="btn btn-outline-salmon w-25" name="lesson_form_submit" value="start_uc_ut">Start</button> {% endif %} Things that I have tried: I tried working with for loops within the template itself, however, when I loop through the records in my table "Lesson_Record" it will return the … -
django caching with pagination in django rest framework
i have a simple api with a simple caching mechanism for testing and learning caching in django, views.py class PlaceListApi(APIView): """ for getting all places """ pagination_class = PaginationWithoutCount() def get(self, request): place_type = "tourist" place_type_fa = "گردشگری" try: # self.pagination_class.page_size =2 query = (Q(place_type=place_type) | Q(place_type_fa=place_type_fa) | Q(place_type_en=place_type)) cache_key = "placeslist_cache" page = cache.get(cache_key) if page is None: print("no cache found for this view get") data = Places.objects.filter(query).only('id', 'name', 'picture') page = self.pagination_class.paginate_queryset(data, request) serialized_page = CityPlacesSerializers(page, many=True) cache.set(cache_key, serialized_page, 60 * 15) return self.pagination_class.get_paginated_data(serialized_page.data) print("after drf") return self.pagination_class.get_paginated_data(page.data) CityPlacesSerializers: class CityPlacesSerializers(ModelSerializer): # placethumbnail = serializers.ImageField(source = "picture") class Meta: model = Places fields = ('id', 'picture', 'name') and PaginationWithoutCount: class PaginationWithoutCount(PageNumberPagination): def get_paginated_data(self, data, error=None): return self.get_paginated_response(data, error) def get_paginated_response(self, data, error=None): return Response(OrderedDict([ ('next', self.get_next_link()), ('previous', self.get_previous_link()), ('results', data), ('error', error) ])) when i first start server with runserver command, there is no problem and everything work as expected, but when i kill the server and restart it, server raise below exception: 'PaginationWithoutCount' object has no attribute 'page' and this comes from else part where **if page is None: ** is False, what is the problem? because of the exception text i think it is not from … -
Creating a webform using Django that queries my own API, how can I protect it?
I am creating a website where there is no user authentication, anyone can use this website. However, there is a form on this website that users will fill out and submit, it will then query an API in Django and return the data. I am very new at Django, so my understanding is if I program it like a normal form, then anyone can go to Developer Console in their browser and monitor the network traffic and see my API request and therefore can just use the API link themselves without needing to use my website at all. This API is to populate data for my own website only, is there anyway I can protect this? In other words, just allow my website to be able to use this api and deny/reject any other request from any other domain? -
Django Import Export, how to import specific sheet in excel?
What is the correct way to import specific sheet of excel by using Django-Import-Export Module?? or if possible. all the sheets in a workbook one by one... I referred their documentation and it was not much helpful https://django-import-export.readthedocs.io/en/latest/ the same way I would like to export data into multiple sheets in one workbook... how do achieve it?? -
how to add button value to django form field when button pressed
i have a django form with fields name, mobile and token. In html form i have buttons of number and i need to add the value of the button to the django forms token field when the number button is clicked. -
__init__() takes 1 positional argument but 2 were given django email activation
please help so solve my problem, when i open the activation link in email, then it will show init() takes 1 positional argument but 2 were given, help this is my signup views def signup(request): if request.method == 'POST': user_form = UserCreationForm(request.POST) profile_form = ProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save(commit=False) profile = profile_form.save(commit=False) user.is_active = False user.save() profile.save() uidb64 = urlsafe_base64_encode(force_bytes(user.pk)) domain = get_current_site(request).domain link=reverse('activate', kwargs={ 'uidb64': uidb64, 'token': token_generator.make_token(user)}) activate_url = 'http://'+domain+link email_body = 'Hallo '+user.username + 'Tolong gunakan link ini untuk verifikasi akun anda\n' +activate_url email_subject = 'Aktivasi Akun Anda' email = EmailMessage( email_subject, email_body, 'noreply@kantorkecamatanbintanutara.com', [profile.email], ) email.send(fail_silently=False) return redirect('/pengurusan/signin') else: return render(request, 'pengurusan/register.html', { 'user_form': user_form, 'profile_form': profile_form }) this is my verification view class VerificationView(View): def get(self, request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) if not token_generator.check_token(self, user, token): return redirect('pengurusan/signup'+'?message'+'User already activated') if user.is_active: return redirect('pengurusan/signin') user.is_active = True user.save() messages.success(request, 'Account activated successfully') return redirect('pengurusan/signup') except Exception as ex: pass return redirect('pengurusan/signin') this is my utils.py from django.contrib.auth.tokens import PasswordResetTokenGenerator from six import text_type class AppTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return (text_type(user.is_active)+text_type(user.pk)+text_type(timestamp)) token_generator = AppTokenGenerator() -
how to upload profile image to user_auth seperately using OnetoOneField() in python django?
CAMROID |--accounts_app | |--admin.py | |--models.py | |--urls.py | |--views.py | |--camroid_app | |--admin.py | |--models.py | |--urls.py | |--views.py | |--camroid_project | |--settings.py | |--urls.py | |--media | |--ProfileImg | |--static | |--css | |--js | |--fonts | |--images | |--templates |--base.html |--category.html |--index.html |--myspace.html |--register.html I have a sign up form from where a user can register and his details is uploaded to user_auth table and in addition to that there is another model UserProfile which contains profile_img = Imagefield() has a OnetoOneField relation to user_auth table and a user can only upload his profile image when he sign in. So a user is not uploading image while he register and can only upload profile image from myspace.html. accounts_app handles all accounts related functionality like register and sign in and camroid_app handles the actual content of the site [index.html, myspace.html] here is myspace.html page. As you can see i'm using two seperate form one for uploading profile pic and another for updating details of user form for updating details will be an easy task but for uploading profile pic while working with OnetoOneField is where i need help. As i don't know how it works. I have already … -
Django - annotate on multiple fields and load relevant objects
Let's say I have the following models class Author(models.Model): name = models.CharField(max_length=25) ... class Publisher(models.Model): name = models.CharField(max_length=25) ... class Book(models.Model): author = models.ForeignKey(Author) publisher = models.ForeignKey(Publisher) ... For some reason, I want to query books and group results by the author and publisher, so: books = Book.objects.values('author', 'publisher').annotate('sth'=Avg('sth_else')) with the results looking like: <BookQuerySet [{'author': 2, 'publisher': 1, 'sth': 1.0}]> Is it possible to load the whole Author and Publisher objects and not just their related ids? -
local Docker container shows blank screen running with gunicorn
I am trying to run a Docker container locally, via the command: docker run --rm -d mellon:latest The gunicorn command which is executing is: gunicorn -b 0.0.0.0:8000 mellon.wsgi (more specifically in the Dockerfile): ... EXPOSE 8000 CMD python3 manage.py makemigrations && \ python3 manage.py migrate && \ gunicorn -b 0.0.0.0:8000 mellon.wsgi Everything in the terminal seems fine, this is the end of what I see: ... [2020-07-28 14:52:33 +0000] [10] [INFO] Starting gunicorn 20.0.4 [2020-07-28 14:52:33 +0000] [10] [INFO] Listening at: http://0.0.0.0:8000 (10) [2020-07-28 14:52:33 +0000] [10] [INFO] Using worker: sync [2020-07-28 14:52:33 +0000] [12] [INFO] Booting worker with pid: 12 So I then go to http://localhost:8000/ yet I just see a completely blank screen with the title and favicon of the project in the tab (see below). This isn't an issue with caching, as I have tried it in a few browsers and the favicon and title appear there too. And upon using 'inspect element' on the page, it shows the contents of the index.html file of my Vue.js project there (located in mellon/frontend/dist). It isn't a problem with my project as running the front-end server (npm run serve) and the back-end server (python3 manage.py runserver) as I usually … -
django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable
This project was working fine until I used environ to make SECRET_KEY and DEBUG as environment variable using environ. After I am getting this error:- The output is: (env) E:\ecommercedj>python manage.py runserver Traceback (most recent call last): File "E:\ecommercedj\env\lib\site-packages\environ\environ.py", line 273, in get_value value = self.ENVIRON[var] File "c:\users\matruchhaya\appdata\local\programs\python\python38-32\lib\os.py", line 675, in __getitem__ raise KeyError(key) from None KeyError: 'SECRET_KEY' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "E:\ecommercedj\env\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "E:\ecommercedj\env\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "E:\ecommercedj\env\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "E:\ecommercedj\env\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "E:\ecommercedj\env\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "E:\ecommercedj\env\lib\site-packages\django\core\management\commands\runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "E:\ecommercedj\env\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__ self._setup(name) File "E:\ecommercedj\env\lib\site-packages\django\conf\__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "E:\ecommercedj\env\lib\site-packages\django\conf\__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "c:\users\matruchhaya\appdata\local\programs\python\python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in … -
how to display count and sum on your website? postgresql, django
I am making a dashboard with django and postgresql, but I am having trouble with the sum and count select functions from sql. home.html <h5 class="card-title">{{total_monney}}</h5> views.py def home(request): d = Dashboard() total_monney = d.getTotalMonney() return render(request, 'home.html', {'total_monney': total_monney}) app.py class Dashboard: def getTotalMonney(self): sql = "SELECT SUM(product_price) FROM products" sqldata = () c = cursor('dashboard', sql, sqldata) result = c.connect() return result the result is that it displays this on the page, how do i only get the "33200"? [RealDictRow([('sum', 33200)])] Everthing works when i dont use the sum and count and just the select, so i dont know if i have todo something diffrent when i use these functions. I get the same result with count too -
Django pagination resets
I am building an application that lists certain records from a database. The database is quite large and I am building a pagination to show a specific number of rows. Currently I have set a default value for the paginate_by. Here is the class that I am using. class HomePageView(ListView): model = Syslog template_name = 'home.html' context_object_name = 'all_logs'; paginate_by = 10 def get_paginate_by(self, queryset): return self.request.GET.get("paginate_by", self.paginate_by) I have implemented and a feature that allows clients to change the pagination levels like so: <form action="" method="get"> <select name="paginate_by" onchange='this.form.submit()'> <option>1</option> <option>2</option> <option>3</option> <option>4</option> </select> </form> When the home page is loaded with the default value the number of pages show correctly. When a user submit another paginate_by value the number of pages change accordingly. The problem is that when the pagination parameter is changed and a user click on let's say 2nd page the paginate_by resets to the default. Regards, Jordan -
How can I convert the value of a DurationField to its number of microseconds in a QuerySet?
Suppose I have two models: Computer and DailyUsage. DailyUsage has a DurationField named usage_duration. On a QuerySet of Computers, I want to annotate the average daily usage in minutes. Each additional minute the computer has been used on average per day, the computer's "importance" increases. I have seen examples* of people using ExpressionWrapper to convert a DurationField to its BigIntegerField representation, but attempting this: average_in_duration_annotated = Computer.objects.annotate( avg=Avg("daily_usages__usage_duration", filter=Q(daily_usages__date__gte=one_month_ago)) ) average_in_minutes_annotated = average_annotated.annotate( avg_in_minutes=ExpressionWrapper(F("avg"), output_field=BigIntegerField()) / Value(10e6 * 60) ) ... results in: {TypeError}int() argument must be a string, a bytes-like object or a number, not 'datetime.timedelta' when the QuerySet is evaluated. Another example that fails the same way: Computer.objects.annotate( total_usage_minutes_microseconds=Sum("daily_usages__usage_duration", output_field=BigIntegerField()) ) How can I convert the value of a DurationField to its number of microseconds in a QuerySet? * Aggregate in django with duration field