Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django serializer field with more than one type
I need to create a field that is either a CharField or a list of char fields. Pseudo code: class MySerializer(Serializer): my_field = CharField() | ListField(child=CharField()) ... I also need it to be properly recognised by DRF Spectacular so that the API docs state it can be either of those two field types. How can I achieve this? -
Why does pagination in django half working?
I tried to implement pagination in django using ajax. But for some reason my pagination is half working. That is, the buttons work, but nothing happens when you go to another page. I understand the problem is in the ajax code views.py: class ProjectDetail(DetailView): model = PortfolioStructure template_name = 'WebPortfolioApp/details.html' slug_url_kwarg = 'proj_slug' context_object_name = 'project' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["other_blog_posts"] = Comment.objects.all().order_by('id') paginator = Paginator(context["other_blog_posts"], 3) page_two = self.request.GET.get("other-page") try: context["other_blog_posts"] = paginator.page(page_two) except PageNotAnInteger: context["other_blog_posts"] = paginator.page(1) except EmptyPage: context["other_blog_posts"] = paginator.page(paginator.num_pages) stuff = get_object_or_404(PortfolioStructure, slug=self.kwargs['proj_slug']) total_likes = stuff.total_likes() liked = False if stuff.likes.filter(id=self.request.user.id).exists(): liked = True context['total_likes'] = total_likes context['liked'] = liked return context pagination-two.html: <div class="container mt-5"> <nav id="pagination-two"> <ul class="pagination justify-content-center"> {% if other_blog_posts.has_previous %} <li class="page-item"> <a class="page-link" href="{{ request.path }}?other-page={{ other_blog_posts.previous_page_number }}"><</a> </li> {% else %} <li class="page-item disabled"> <a class="page-link" href="#" tabindex="1" aria-disabled="true"><</a> </li> {% endif %} {% for i in other_blog_posts.paginator.page_range %} {% if other_blog_posts.number == i %} <li class="page-item active"> <a class="page-link" href="{{ request.path }}?other-page={{ i }}">{{ i }}</a> </li> {% else %} <li class="page-item"> <a class="page-link" href="{{ request.path }}?other-page={{ i }}">{{ i }}</a> </li> {% endif %} {% endfor %} {% if other_blog_posts.has_next %} <li class="page-item"> <a … -
Why is django not detecting this import path of my custom middleware
I tried adding the middleware at the end of the list of middlewares in the settings.py file of the project. I double-checked the inclusion of my app in the list of installed apps in the same file. The directory of the installed app works for other parts of my project. I also tried doing an import of the middleware class that I've made inside of init.py (tried both the project's init file and the app's init file) The error I get is "ModuleNotFoundError: No module named 'front.middleware'" Directory: settings.py: """ Django settings for CloseUp project. Generated by 'django-admin startproject' using Django 4.1.7. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "django-insecure-i$rv^2g_phigb-!655)qp5_btr8+gw8xr_v)d-#5kw)$*u3mnj" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ "front", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", ] MIDDLEWARE = … -
React app creating cart but not getting cart from django backend
Gooday everyone I'm working on an ecommerce project and I'm trying to build the cart for the unauthenticated users. Instead of using user id to identify the cart I decided to use session id to identify users currently accessing the server. It works perfectly in the backend but there is a problem in the frontend. creating the cart works but when I try to get my cart using the react frontend it returns an empty list. models.py #for the cart from django.db import models from books.models import Book from django.contrib.auth import get_user_model from django.dispatch import receiver from django.db.models.signals import post_save User = get_user_model() class TimeStampedModel(models.Model): created = models.DateTimeField(db_index=True, auto_now_add=True) modified = models.DateTimeField(auto_now=True) class Meta: abstract=True class Cart(TimeStampedModel): total = models.DecimalField(max_digits=10, decimal_places=2, default=0, blank=True, null=True) session_id = models.CharField(max_length=100, blank=True) class CartItem(TimeStampedModel): cart = models.ForeignKey(Cart, related_name='cart_items', on_delete=models.CASCADE) product = models.ForeignKey(Book, related_name='cart_products', on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return self.product.__str__() Now I'll add my views.py file from django.shortcuts import get_object_or_404 from rest_framework.generics import ListCreateAPIView, CreateAPIView, ListAPIView, RetrieveUpdateDestroyAPIView, RetrieveAPIView from .serializers import CartItemSerializers, CartItemUpdateSerializers from rest_framework import permissions, status from rest_framework.response import Response from rest_framework.exceptions import NotAcceptable, ValidationError, PermissionDenied from .models import Cart, CartItem from books.models import Book from rest_framework.views import APIView import uuid … -
ModuleNotFoundError: No module named 'settings' for any django project
I have been studying Django for some time and have been working on a project. Everything was fine until yesterday when I was studying a new topic, saved the project and shut down my PC. There were no errors or anything. Today, when I tried to run my project using the command "py manage.py runserver", I received an error "ModuleNotFoundError: No module named 'settings'". I spent enough time trying to solve this problem and assumed that the error was in my project. I couldn't solve it and decided to create a completely new project in a new virtual environment. To my surprise, the same error occurred in this completely new project as well. I thought that I might be doing something wrong, so I repeated the project creation on my laptop, and everything worked as expected with no errors. I tried reinstalling PyCharm and Python, but it didn't help. I don't think I can continue using Django on this PC anymore... I don't know what data may be needed to solve this problem, so I will provide at least something. These are the data from the project that was just created. Project structure Installed modules Full error: During handling of … -
why django can't see javascript?
Django does not see javascript and css file, I don't know what is wrong and how to fix it This is my code JavaScript in html file: <style> .like-container{ width: 100px; height: auto; margin-bottom: 10px; } .like-container button{ background: none; border: none; } i{ font-size: 22px; cursor: pointer; } </style> <div class="like-container"> <p class="num-of-likes" id ="num">{{post.likes.count}}</p> {% if msg %} <i class="fa-solid fa-heart"></i> {% else %} <i class="fa-regular fa-heart"></i> {% endif %} <small>like</small> </div> </div> <script> function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); let btn = document.querySelector("i") let num_of_likes = document.getElementById("num") let post_id = "{{post.id}}" btn.addEventListener("click", likePost) function likePost(e){ let url = "{% url 'like' %}" const data = {id:post_id} fetch(url, { method: 'POST', headers: {"Content-Type": "application/json", 'X-CSRFToken': csrftoken }, body : JSON.stringify(data) }) .then(res => res.json()) .then(data => { console.log(data) if(data["check"] == 1){ btn.classList.remove("fa-regular") btn.classList.add('fa-solid') } else … -
Can we use sqlite3 for django in production azure
i have developed a django app in my local pc using sqlite3 server and after hosting it on azure app service. Every time i push new version it overwrite database and static files what should be the best and free fix for this. Expecting solution and suggestions -
Getting this error 'QuerySet' object has no attribute 'pk' when passing queryset instance in Serializer with many=True
I have a view that is responsible for bulk updating objects, since DRF doesn't provide any generic view for that I proceed with this approach. In docs they are passing many=True and a queryset of objects in the serializer. this is from docs queryset = Book.objects.all() serializer = BookSerializer(queryset, many=True) serializer.data # [ # {'id': 0, 'title': 'The electric kool-aid acid test', 'author': 'Tom Wolfe'}, # {'id': 1, 'title': 'If this is a man', 'author': 'Primo Levi'}, # {'id': 2, 'title': 'The wind-up bird chronicle', 'author': 'Haruki Murakami'} # ] So decided to do something like that, here is my view.py file class PostListBulkUpdateApiView(GenericAPIView): serializer_class = PostListUpdateSerializer permission_classes = [permissions.IsAuthenticated, HasPostChangePermission, HasPostReadPermission, HasObjectDeletePermission] def get_serializer(self, *args, **kwargs): if isinstance(kwargs.get('data', {}), list): kwargs['many'] = True return super().get_serializer(*args, **kwargs) def get_queryset(self, ids=None): if ids: return Post.objects.filter(id__in=ids) return Post.objects.all() def put(self, request, *args, **kwargs): return self.update(request) def patch(self, request, *args, **kwargs): return self.update(request) def update(self, request, *args, **kwargs): ids = set() for data in request.data: id = data.get('id', None) if id is not None: ids.add(id) instance = self.get_queryset(ids=ids) serializer = PostListUpdateSerializer(instance=instance, data=request.data, partial=True, many=True) if serializer.is_valid(raise_exception=True): return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) but it give me 'QuerySet' object has no attribute 'pk' error … -
View 'UPDATE' statements in Django Debug Toolbar (SQL panel)
I am using Django Debug Toolbar with my project. I am looking to view all SQL statements that are made by the app. Currently, only SELECT statements are shown. Is there a way to enable UPDATE and other statements? -
How to insert values into a form from another table?
I have two tables. A first table contains a list of offices and a second table contains a list of cartridges. When I create the cartridge, it's required to write the office. But it is necessary that in the form of creating a cartridge in the office selection there should be a list from the Offices. How to do it? For example, there is the list: Offices ID name 1 A11 2 A11-1 3 A12 4 A13 5 A13-2 My code: Models.py class Office(models.Model): name = models.CharField('name', max_length=255) def get_absolute_url(self): return reverse('office_list') class CartridgeList(models.Model): office = models.CharField('office', max_length=255) uniquenumber = models.CharField('unique number', max_length=255) status = models.CharField('status', max_length=255) def get_absolute_url(self): return reverse('cartridge_list') forms.py class CartridgeListForm(forms.ModelForm): class Meta: model = CartridgeList fields = ('office', 'uniquenumber', 'status') widgets = { # Now I write the office here, but it's required to have a ready list from Office Model (A11, A11-1, A12, A13, A13-2) 'office': forms.TextInput(attrs={'class': 'form-control'}), 'uniquenumber': forms.TextInput(attrs={'class': 'form-control'}), 'status': forms.TextInput(attrs={'class': 'form-control'}), } Views.py: class AddCartridgeListView(CreateView): model = CartridgeList form_class = CartridgeListForm template_name = 'add_cartridge.html' -
Populate Django Model with for-loop
I have a model Task which I want to populate with a for loop. In a list I have the tasks that should be passed into the model. My model has actually more than three tasks (Below I have shown only three). The list will also have varying number of entries. The list can also have only one task. tasks = ['first task', 'second task', 'third task'] class Task(models.Model): ad = models.OneToOneField(Ad, on_delete=models.CASCADE, primary_key=True, blank=True, null=False) task1 = models.CharField(max_length=256, blank=True, null=True) task2 = models.CharField(max_length=256, blank=True, null=True) task3 = models.CharField(max_length=256, blank=True, null=True) def __str__(self): return f'Tasks for {self.ad}' My approach looks like this: task_obj = Task.objects.create( ad = ad ) for idx, t in enumerate(tasks): task_obj.f'task{idx+1}' = t Basically this part f'task{idx+1}' should not be a string, but the actual variable of the model. Is this even possible? Or does an other way exist I am not aware of? -
Implement search bar in django
I want to implement two things: User page from URL: If I enter a URL like '.../username', I am taken to that page provided it exists. For that I mapped 'str:username' to user_profile view. Then I will perform a query and display the page dynamically. This part is working fine. Next is implementing a search bar where I will enter a username and submit to call the same function passing the input value as the argument to that view function. I tried various method like {% url 'user_profile' username=username %}. Used various if else conditions but still I am unable to make it. -
jQuery remote validate not working with django url
when i submit form, adno field (number) not validate excluding empty my template.html <input name="adno" id="id_adno" type="number" class="form-control" placeholder="" required> jquery validate remote adno: { remote: { url: "{% url 'is_adno_valid' %}", type: "post", data: { field_value: function () { return $("#my_field").val(); }, csrfmiddlewaretoken: "{{ csrf_token }}" } } }, views.py and urls.py def is_adno_valid(request): adno = int(request.POST.get('adno')) return JsonResponse({'status':adno==1111}) urls.py path('is_adno_valid',views.is_adno_valid, name='is_adno_valid'), when i try to submit form with adno field as empty, red border of error showing. but whe enter any number it not showing error. ie, remote not working -
wagtail localize serving second language under first language in URL, pages not found
Using wagtail localize I am getting a weird URL structure: http://127.0.0.1:8000/en/ [ home ] as expected, when going to http://127.0.0.1:8000. However, if I try to go to http://127.0.0.1:8000/cn/ suddenly the English locale is appended in front somehow. Resulting in http://127.0.0.1:8000/en/cn/ or http://127.0.0.1:8000/en/cn/about/ When I try to correct the URL to the expected http://127.0.0.1:8000/cn/about/ 'en' gets appended in front again for no obvious reason and the page cannot be found. The same happens when I click "live view" in admin. Error message Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/en/cn/ Raised by: wagtail.views.serve Using the URLconf defined in website.urls, Django tried these URL patterns, in this order: en/ django-admin/ en/ admin/ en/ documents/ en/ search/ [name='search'] en/ _util/authenticate_with_password/<int:page_view_restriction_id>/<int:page_id>/ [name='wagtailcore_authenticate_with_password'] en/ _util/login/ [name='wagtailcore_login'] en/ ^((?:[\w-]+/)*)$ [name='wagtail_serve'] The current path, en/cn/, matched the last one. urls.py #This is as per the documentation. from django.conf import settings from django.urls import include, path from django.contrib import admin from django.conf.urls.i18n import i18n_patterns from wagtail.admin import urls as wagtailadmin_urls from wagtail import urls as wagtail_urls from wagtail.documents import urls as wagtaildocs_urls from search import views as search_views urlpatterns = \[ path("django-admin/", admin.site.urls), path("admin/", include(wagtailadmin_urls)), path("documents/", include(wagtaildocs_urls)), \] urlpatterns += i18n_patterns( path('search/', search_views.search, name='search'), path("", include(wagtail_urls)), … -
Error "timescaledb" extension is not up-to-date
CREATE DATABASE waiting for server to shut down....2023-03-25 09:45:00.498 UTC [35] LOG: received fast shutdown request 2023-03-25 09:45:00.501 UTC [35] LOG: aborting any active transactions 2023-03-25 09:45:00.501 UTC [52] LOG: terminating TimescaleDB job scheduler due to administrator command 2023-03-25 09:45:00.501 UTC [42] LOG: terminating TimescaleDB background worker launcher due to administrator command 2023-03-25 09:45:00.501 UTC [52] FATAL: terminating connection due to administrator command 2023-03-25 09:45:00.501 UTC [42] FATAL: terminating connection due to administrator command 2023-03-25 09:45:00.501 UTC [52] LOG: terminating TimescaleDB job scheduler due to administrator command 2023-03-25 09:45:00.503 UTC [35] LOG: background worker "TimescaleDB Background Worker Launcher" (PID 42) exited with exit code 1 2023-03-25 09:45:00.503 UTC [35] LOG: background worker "logical replication launcher" (PID 43) exited with exit code 1 2023-03-25 09:45:00.503 UTC [35] LOG: background worker "TimescaleDB Background Worker Scheduler" (PID 52) exited with exit code 1 2023-03-25 09:45:00.503 UTC [37] LOG: shutting down 2023-03-25 09:45:00.578 UTC [35] LOG: database system is shut down done server stopped PostgreSQL init process complete; ready for start up. 2023-03-25 09:45:00.639 UTC [1] LOG: starting PostgreSQL 13.2 on x86_64-pc-linux-musl, compiled by gcc (Alpine 10.2.1_pre1) 10.2.1 20201203, 64-bit 2023-03-25 09:45:00.639 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 2023-03-25 09:45:00.639 … -
Why make_aware is changing the original time in Django?
I have a edge device acting as a Django backend server, which is on premises, in settings.py file the time zone support is active, so when i receive some datetimes from ML API, the time values are correct exactly the way they are supposed to, After receiving when i try to save the datetime in a django model, i use following way to parse the datetimes timestamps = list(predictions['ts'].values()) timestamps = [ datetime.strptime(t, "%Y-%m-%d %H:%M:%S") for t in timestamps ] the above statements raise warnings on saving which is following /usr/local/lib/python3.9/site-packages/django/db/models/fields/init.py:1564: RuntimeWarning: DateTimeField Writeback.ts received a naive datetime (2023-03-17 07:45:00) while time zone support is active. As I have warnings phobia so to remove them I tried to make them aware of time zone using the function make_aware timestamps = [ make_aware(t) for t in timestamps ] Now after this time values are changed for example if original datetime was "2023-03-17 06:45:00" then after make_aware it changes to "2023-03-17 10:45:00" My question is do I really need time zone support? is it mandatory in my case? what if I disable the time zone support? can I still parse the datetime using make_aware but without changing the time string? I did … -
How can I make cloned select2 fields working?
I have two select2 fields that are working as dynamic search engine inside a form. I need to clone this form so the user can add multiple entries and filtering inside these two fields that are working as search engine. HTML: <div class="form-group"> <label>{% trans "Departure Aerodrome" %}</label> <select class="form-control adep" name="adep" id="adep"> {% if not base_airport %} <option disable="">{% trans "Choose one Airport" %}</option> {% else %} <option value="{{base_airport.icao_code}}">{{base_airport.icao_code}} - {{base_airport.name}} </option> {% endif %} </select> </div> <div class="form-group"> <label>{% trans "Arrival Aerodrome" %}</label> <select class="form-control ades" name="ades" id="ades"> {% if not base_airport %} <option disable="">{% trans "Choose one Airport" %}</option> {% else %} <option value="{{base_airport.icao_code}}">{{base_airport.icao_code}} - {{base_airport.name}} </option> {% endif %} </select> </div> <div class="col"> <button class="btn btn-primary" id="addFlightBtn">{% trans "Add New Flight" %}</button> </div> My form is inside a forloop, so there can be 1 item as many other items. So I initialize the select fields with this function: $(document).ready(function () { searchAirports(".adep", "adep-"); searchAirports(".ades", "ades-"); }); function searchAirports(className, idName) { $(className).each(function (index) { var id = idName + index; $(this).attr("id", id); $("#" + id).select2({ ajax: { url: "/flight/search_airports", dataType: "json", data: function (params) { return { search_value: params.term, // search term }; }, processResults: function (data) … -
Add search field when add Answer in Django admin panel
I have Answer model in this field i have answer_dependens_on model class Answer(models.Model): question_id = models.ForeignKey( "app.Question", on_delete=models.CASCADE, related_name='answers') answer_title = models.CharField(max_length=100, null=True, blank=True) answer_weight = models.DecimalField(max_digits=9, decimal_places=4, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) answer_dependens_on = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) class Meta: verbose_name = 'Answer' verbose_name_plural = 'Answers' def __str__(self): return "answer={}; question={}".format(self.answer_title, self.question_id) i whant add search in this field -
Why Error when running code for show similar post with taggit in django 3?
I'm currently learning django by following the book Django by example from antonio mele and have reached the stage of how to display the same post using tags. I feel that I have followed the contents of the book well, but still stuck here Error in web browser It happened with the code I made like this: coding in models.py from django.db import models # Create your models here. from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from taggit.managers import TaggableManager class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager,self).get_queryset()\ .filter(status='published') class Post(models.Model) : STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published') ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date= 'publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name= 'blog_post') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() published = PublishedManager() tags = TaggableManager() class Meta : ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args = [self.publish.year, self.publish.month, self.publish.day, self.slug]) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __str__(self): return f'Comment by {self.name} on … -
getting database error on form validation in djongo
i have create a custom user model in django using djongo driver and whenever i tries to add a user with same name or email is show this error but i want to show them error on form i also have a post model which uses the user model class as foreign key so whenever i try to add post with user i ``` class User(AbstractBaseUser, PermissionsMixin): userna='' username = models.CharField( _("username"), max_length=150, unique=True, help_text=_( "Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only." ), validators=[UnicodeUsernameValidator], error_messages={ "unique": _("A user with that username already exists."), }, primary_key=True ) email = models.EmailField( _("email address"), max_length=150, unique=True, error_messages={ "unique": _("A user with that email address already exists."), }, ) first_name = models.CharField(_("first name"), max_length=150, blank=False) last_name = models.CharField(_("last name"), max_length=150, blank=False) date_of_birth=models.DateField(_("date of birth"),blank=False) country=models.CharField(_("country"),max_length=250,blank=False) state=models.CharField(_("state"),max_length=250,blank=False) city=models.CharField(_("city"),max_length=250,blank=False) gender=models.CharField(max_length=10,choices=GENDER_CHOICES,default="Male") profile_photo=models.ImageField(upload_to= upload_to) is_staff = models.BooleanField( _("staff status"), default=False, help_text=_("Designates whether the user can log into this admin site."), ) is_active = models.BooleanField( _("active"), default=True, help_text=_( "Designates whether this user should be treated as active. " "Unselect this instead of deleting accounts." ), ) date_joined = models.DateTimeField(_("date joined"), default=timezone.now) objects = UserManager() EMAIL_FIELD = "email" USERNAME_FIELD = "email" REQUIRED_FIELDS = ['username', 'first_name', 'last_name','date_of_birth','country','state','city','gender'] ``` … -
How to debug a django python custom command in emacs?
How can I debug the closepoll.py buffer in emacs? While every other python script just needs C-c C-c nobody seems to know how to do it with django. I've asked this question with maybe too much detail and a bounty here as well without success. -
How to calculate the remaining number of goods?
I have a table where the receipt of printer paper to the warehouse and their distribution are recorded. How to find the remaining amount of printer paper? For example, there is a table: RedordID Amount Status 000001 30 arrived 000002 2 send 000003 1 send 000004 3 send 000005 10 arrived 000006 1 send It means that the result sholud be 33 (add "arrived" and subtract "send": +30-2-1-3+10-1=33). How to do it? My code: Models.py class PaperReport(models.Model): office = models.CharField('Office', max_length=255) amount = models.CharField('Number', max_length=255) status = models.CharField('Status', max_length=255) dateaction = models.DateField('Date of action') def get_absolute_url(self): return reverse('paper_list') Views.py class PaperReportView(ListView): model = PaperReport template_name = 'paper_list.html' ordering = ['dateaction'] paper_list.html <div> <h2>Number of printer paper in stock: <!-- {{calculation must be there and the result is 33}} --> </h2> <h2>Info about paper</h2> {% for case in object_list %} <div> <p>{{case.dateaction}} for {{case.office}}: {{case.amount}} pieces were {{case.status}}</p> </div> {% endfor %} </div> -
How to filter data by two fields in django model?
Here is queryset and I want to filter by two django fields. #models.py class ExmapleModel(models.Model): first_field = models.IntegerFiled() second_field = models.IntegerField() and here views #views.py class ExampleApiView(ListAPIView): queryset = ExmapleModel.objects.all() serializer_class = ExmapleModelrSerializer permission_classes = (AllowAny,) def get_queryset(self): qs = super().get_queryset() ... if condition: return qs.filter(lambda item: item.first_field < item.second_field) return qs I tried to filter like this, but of course it doesn't work qs.filter(lambda item: item.first_field < item.second_field) -
Set Order of Python Module Reference
Scenario: I am creating a Django python service and trying to run through celery. I have setup python3.7, virtual env, installed requirements successfully and created dependency infrastructure. When I try to run the service, I am getting an error: module 'aspose.email' has no attribute 'message_from_bytes' Root cause is: One dependency library kombu is using this import File "/home/siddhesh/codebase/pstconverter-node/myenv2/lib/python3.7/site-packages/kombu/asynchronous/aws/connection.py", line 3, in <module> from email import message_from_bytes Ideally, the email module should be imported from /usr/lib/python3.7/ and not from aspose library which is inside site-packages Question: How can I tell python to first search for this module from inside the python built-in lib instead of site-packages? In short, how can I set the ordering of lookup. My sys.path result: ['', '/usr/lib/python3.7', '/usr/lib/python37.zip', '/usr/lib/python3.7/lib-dynload', '/home/siddhesh/codebase/pstconverter-node/myenv2/lib/python3.7/site-packages'] -
Django ORM Facing issue in Group By in 3 levels of table
Models: Employee - name, email CuttingJob - employee (ForeignKey), count OrderCuttingDetail - product_name, amount I want to show the employee wise cutting count and it’s amount. employees = Employee.objects.annotate( total_cutting_job_count=Sum(‘cutting_jobs__count’), total_cutting_job_amount=ExpressionWrapper(F(‘total_cutting_job_count’) * F(‘cutting_jobs__order_cutting_detail__amount’), output_field=DecimalField()), ).all() But while running this query, employees are duplicated. Need to group the records based on employee’s name. Kindly suggest a solution for this. I want to show the total amount based on employee wise. Kindly provide a solution for this.