Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django filter can't find a right solution
my models: class Order(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="order_user") first_name = models.CharField(_('first name'), max_length=50) last_name = models.CharField(_('last name'), max_length=50) email = models.EmailField(_('e-mail')) address = models.CharField(_('address'), max_length=250) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) # objects = models.Manager() # default manager ord_obj = ManagerOrder() # custom manager class OrderItem(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='order_items', on_delete=models.CASCADE) shop = models.ForeignKey(MyShop, related_name='shop_order', on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) # objects = models.Manager() # default manager items_obj = ManagerOrderItem() # custom manager my views: def shop_orders(request): order = Order.ord_obj.filter(items__shop=request.user.user_profile_shop) return render(request, 'account/paneli/shop/orders/shop_orders.html', {'order': order,}) in the template,it show the order of the shop but it shows the OrderItem of all the shops {% for order in order %} order.id #it ok {% for item in order %} {{ item.product }}# wrong shows the OrderItem of all the shops {% endfor %} {% endfor %} can you help me someone where i went wrong -
While testing django web app in using waitress, it serve on http://0.0.0.0:8000
While I use the url http://0.0.0.0:8000 in browser, it says "The site cannot be reached." How to solve this problem. Any one help me, please! my django project name is: testdj and I use command -> waitress-serve --port=8000 testdj.wsgi:application -
How to create a rest api with nested url in a DRY fashion?
I am trying to write a simple Geocache application. The backend access should work as follows: One Geocache Object contains general information (like creation date or difficulty level) but also several instructions, which have a fixed order (example instruction: Go first to coordinate lon/lat). The general URL structure is example.com/geocache/ List view for geocaches (get) example.com/geocache/<geocache_pk>/ Detail view for geocache (get/post/put/delete) (all instructions should be collectively displayed here but they cannot be manipulated here) example.com/geocache/<geocache_pk>/instruction/ Only to create new instructions (post) example.com/geocache/<geocache_pk>/instruction/<instruction_position/> Only for instruction manipulation/deletion (put/delete) I tried to accomplish this structure through custom actions with regular expressions in the url_path but I feel it is not DRY enough. I am learning Django only for a few days so I might be missing some sophisticated patterns. Please also let me know if the general approach makes sense to you. Thank you for your effort! I really appreciate any suggestions to get better. models.py from django.db import models from django.db.models import F from django.db.models.signals import pre_save, post_delete from django.dispatch import receiver from django.contrib.auth.models import User from django.utils.translation import gettext_lazy as _ class Geocache(models.Model): class DifficultyLevel(models.TextChoices): BEGINNER = 1, _('Beginner') INTERMEDIATE = 2, _('Intermediate') ADVANCED = 3, _('Advanced') user_created = models.ForeignKey(User, … -
DJANGO - Trying to set up a dependent dropdown list
As you can understand I'm new to cooking, but I can't find where my code is wrong. Struggling for full day now, replacing and renaming the different . Perhaps some fresch eyes will spot the misstake I've made. Something in my code generates none "issue areas". What I want to do. When you on a workorder select product so will it limit the issue areas you can define. -----models.py------ class Products(models.Model): m_product_short=models.CharField(unique=True,max_length=5) m_product_long=models.CharField(max_length=40) def __str__(self): return self.m_product_short class IssueAreas(models.Model): product=models.ForeignKey(Products, on_delete=models.SET_NULL, null=True) m_issue=models.CharField(max_length=50) def __str__(self): return self.m_issue class WorkOrder_main(models.Model): wo_machine_product = models.ForeignKey(Products, on_delete=models.SET_NULL, null=True) wo_issue_area = models.ForeignKey(IssueAreas,on_delete=models.SET_NULL, null=True) ----url.py----- urlpatterns = [ path("create/",views.WO_CreateView.as_view(), name="Create Order"), path('ajax/loadIssue/', views.loadIssueAreas, name='ajax_loadIssueAreas'), # AJAX ] ----views.py----- class WO_CreateView(CreateView): template_name = 'WorkOrderCreate.html' model = WorkOrder_main form_class = WorkOrder_Add2 # AJAX def loadIssueAreas(request): product_id = request.GET.get('wo_machine_product') issues = IssueAreas.objects.filter(product_id=product_id).all() return render(request, 'oa/IssueAreaDropDown.html', {'issues': issues}) ----forms.py----- class WorkOrder_Add2(forms.ModelForm): class Meta: model=WorkOrder_main fields= ' __all__ ' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['wo_issue_area'].queryset = IssueAreas.objects.none() if 'product' in self.data: try: product_id = int(self.data.get('product')) self.fields['wo_issue_area'].queryset =IssueAreas.objects.filter(product_id=product_id).order_by('id') except (ValueError, TypeError): pass elif self.instance.pk: self.fields['wo_issue_area'].queryset = self.instance.product.IssueAreas_set.order_by('id') ----WorkOrderCreate.html---- <!DOCTYPE html> <html lang="en"> <meta charset="UTF-8"> {% extends "Master.html" %} {% block title %}Create{% endblock %} {% block content %} <h1>Create Order</h1> <form … -
Is it possible to send data as a hyper-link?
I want to send data like this Here is my code if request.method == 'GET': context = [] context.append({ link':"<a href=\"www.google.com\">click me</a>", }) return Response(context, status=status.HTTP_200_OK) and this is the result -
django mssql password not being acknowledged
The official error is "argument of type 'NoneType' is not iterable" Doing some digging I notice that mssql sees 'PASSWORD' as None, even though it is defined in settings (os.environ.get('DBPW')) Doing os.environ.get('DBPW') in python3 manage.py shell gives me the correct password, and doing settings.DATABASES['default'] in shell shows the correct password as well, so I know it's some sort of glitch in mssql. Here are my settings: DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': 'tc_django_dev', 'USER': 'SA', 'PASSWORD': os.environ.get('DBPW'), 'HOST': 'localhost', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } Here is what (python) mssql says it has: conn_params: {'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'ENGINE': 'mssql', 'HOST': 'localhost', 'NAME': 'tc_django', 'OPTIONS': {'driver': 'ODBC Driver 17 for SQL Server'}, 'PASSWORD': None, 'PORT': '', 'TEST': {'CHARSET': None, 'COLLATION': None, 'MIGRATE': True, 'MIRROR': None, 'NAME': None}, 'TIME_ZONE': None, 'USER': 'SA'} Help. -
Different selection dropdown for different products using Django
I am building a webshop for a school project and would like to add a dropdown with color options for some products (catears), and for other products (quipu) I would like to provide the customer with two dropdowns and a text fiels where they can enter a name/work to make their order custom. So I'm thinking something like this in the html: <p class="mt-3">{{ product.description }}</p> <form class="form" action="{% url 'add_to_bag' product.id %}" method="POST"> {% csrf_token %} <div class="form-row"> {% if catears_has_colors %} {% include 'products/includes/catears_has_colors.html' %} {% elif qupiu_custom_form %} {% include 'products/includes/qupiu_custom_form.html' %} {% endif %} Quipu_custom_form looks like this, catears_has_colors is simular: <div class="quipu-form-control" name="quipu_color_choise" id="id_quipu_color_choise"> <p>Write the name/word you would like (max 12 letters), and pick what color and type of stone pearl you prefer</p> <div class="col-12 col-md-6"> <select class="form-control rounded-0 w-50"> <option value="pearl_white" selected>Pearl White</option> <option value="light_blue">Light Blue</option> </select> </div> <div class="col-12 col-md-6"> <select class="form-control rounded-0 w-50"> <option value="labradorite" selected>Labradorite</option> <option value="amethyst">Amethyst</option> </select> </div> <div class="col-12"> <input type="text" name="quipu_custom_name" id="id_quipu_custom_name" > </div> </div> And in the products/models.py I got these classes: class CatEarColor(models.Model): BLUE = 'BL' PINK = 'PN' CATEAR_COLOR = [ (BLUE, 'blue'), (PINK, 'pink'), ] catear_color = models.CharField( max_length=2, choices=CATEAR_COLOR, default=BLUE ) def … -
getting radio button value in views.py from template
how can i access of the selected button from my template in my views.py <form action="{% url 'user_vote' q.pk %}" method="POST"> {% csrf_token %} {% for choix in q.choice_set.all %} {% if forloop.counter == 1 %} <input type="radio" name="choix" id="{{ choix.pk }}" required/> <label for="{{ choix.pk }}"> {{ choix.choice_text }} - {{ choix.total }}</label> <br> {% else %} <input type="radio" name="choix" id="{{ choix.pk }}" value="{{ choix.pk }}"/> <label for="{{ choix.pk }}"> {{ choix.choice_text }} - {{ choix.total }}</label> <br> {% endif %} {% endfor %} <button type="submit" class="btn btn-primary">Votez</button> </form> views.py: @login_required def user_vote(request,question_id): question = get_object_or_404(Question,pk=question_id) if request.method == 'POST': vote =request.POST.get("choix") print(vote) #i am getting 'on' messages.success(request, "Votre vote a été crée." ) return HttpResponseRedirect(reverse('show_community',kwargs={'pk':question.communaute_id})) else: return redirect('news') my problem is i am not getting the value of the select radio button i am getting 'on' on the server side.i tried many answers from stackoverflow here but none helped me.thanks -
Reverse for 'X' not found. 'X' is not a valid view function or pattern name. Django Framework
I 'm new to Django concept I have 3 files for this issue. I have a urls.py in my project file call firt_website with the following code: """firt_website URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from pages import urls app_name = 'main' urlpatterns = [ path('', include('pages.urls', namespace='home')), path('portfolio/', include('pages.urls', namespace='portfolio')), path('experience/', include('pages.urls', namespace='experience')), path('education/', include('pages.urls', namespace='education')), ] I have the Navbar HTML that will be included in an index page HTML as {% extends 'navbar.html' %} : the files contains : <div class="u-custom-menu u-nav-container"> <ul class="u-custom-font u-font-titillium-web u-nav u-spacing-30 u-unstyled u-nav-1"><li class="u-nav-item"><a class="u-border-2 u-border-active-white u-border-hover-custom-color-2 u-border-no-left u-border-no-right u-border-no-top u-button-style u-nav-link u-text-active-white u-text-hover-custom-color-2 u-text-white" href="Acceuil.html" style="padding: 10px 0px; text-shadow: 0 0 8px rgba(128,128,128,1);">Home</a> </li><li class="u-nav-item"><a class="u-border-2 u-border-active-white u-border-hover-custom-color-2 u-border-no-left u-border-no-right u-border-no-top u-button-style … -
how to avoid assignment If one value is set on django model field?
I have a product model with 2 foreign keys to models percentDiscount and cashDiscount, I want to apply just one of these discounts on my unit price. So i defined a final_price property to get the final_price of item. but i want to apply one of these discount on item at the moment. There are 2 ways, 1) when one of discount set, do not let another to be set and set it as none. 2) do some thing in final price to set just one of these discount. Below is my code, I will be happy if you help me to make the best decision. class Product(models.Model): class Meta: verbose_name = 'محصول' verbose_name_plural = 'محصولات' ordering = ('created_at',) name = models.CharField(max_length=50) category = models.ForeignKey('product.Category', on_delete=models.CASCADE, related_name='products') brand = models.ForeignKey('product.Brand', on_delete=models.CASCADE, related_name='products') # labels such as bestseller, new, not available, etc ... label = models.CharField(choices=LABEL, max_length=1) image = models.ImageField(upload_to='product/static/product/images/', null=True, blank=True) description = models.TextField(max_length=1000, null=True, blank=True) is_original = models.BooleanField() inventory = models.PositiveIntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) unit_price = models.DecimalField(max_digits=8, decimal_places=2) number_sold = models.PositiveIntegerField() # discount code for this book cash_code = models.ForeignKey('cart.CashDiscount', null=True, on_delete=models.CASCADE, blank=True, related_name='related_products') percentage_code = models.ForeignKey('cart.PercentageDiscount', null=True, on_delete=models.CASCADE, related_name='related_products', blank=True) # for food … -
Django : File object is not Json serializable
I want to send back a file as a response to my post request but i get this error file object is not json serializable , so how do i send a file back as a response for my post request : @api_view(['GET', 'POST']) def Upload_list(request): if request.method == 'GET': queryset = Uploads.objects.all() uploads=queryset.filter(owner=request.user) serializer = UploadSerializer(uploads, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = UploadSerializer(data=request.data) if serializer.is_valid(): serializer.save(owner=request.user) respFile=list(File.objects.filter(id=str(File.objects.latest('created_at')))) return Response(respFile) #return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Running MYSQL command inside a shell script not working
I am trying to run a shell script with commands to run the Django Server. #!/bin/bash docker run -e MYSQL_ROOT_PASSWORD=root --name db_name -d mariadb docker exec -it container_name mysql -u root -proot -e "create database db_name CHARACTER SET UTF8; CREATE USER invuser@XXX.17.0.3 IDENTIFIED BY 'root1234$'; GRANT ALL PRIVILEGES ON db_name .* TO invuser@XXX.17.0.3 IDENTIFIED BY 'root1234$';" #mysql -u root -proot -e "create database db_name CHARACTER SET UTF8; CREATE USER invuser@XXX.17.0.3 IDENTIFIED BY 'root1234$'; GRANT ALL PRIVILEGES ON db_name .* TO invuser@XXX.17.0.3 IDENTIFIED BY 'root1234$'" echo "Docker image name will be $1" python3 manage.py makemigrations python3 manage.py migrate docker build . -t $1 docker run -d -p 8000:8000 $1 In this script, When I am trying to run : docker exec -it container_name mysql -u root -proot -e "create database db_name CHARACTER SET UTF8; CREATE USER invuser@XXX.17.0.3 IDENTIFIED BY 'root1234$'; GRANT ALL PRIVILEGES ON db_name .* TO invuser@XXX.17.0.3 IDENTIFIED BY 'root1234$';" I am getting this error : ERROR 2002 (HY000): Can't connect to local server through socket '/run/mysqld/mysqld.sock' (2) OR when I run : mysql -u root -proot -e "create database db_name CHARACTER SET UTF8; CREATE USER invuser@XXX.17.0.3 IDENTIFIED BY 'root1234$'; GRANT ALL PRIVILEGES ON db_name .* TO invuser@XXX.17.0.3 IDENTIFIED BY … -
django jsonresponse returns empty values
class HomeView(TemplateView): template_name = 'pbi_theme_app/index.html' def get(self, request): form = HomeForm() position = Legend.objects.filter(selection="Position") return render(request, self.template_name, {'form': form, 'sss': position}) def post(self, request): text = '' show = '' position = '' form = HomeForm(request.POST) if form.is_valid(): text = form.cleaned_data['post'] self.text = form.save() show = form.cleaned_data['show'] #position = Legend.objects.filter(selection="Position").values() position = form.cleaned_data['position'] return JsonResponse({'text': text, 'show': show, 'sss': position}) I am trying to push the response that I get from POST form to json, but the value in the dictionary is empty, the form doesn't save it somehow. {"text": "", "show": "", "sss": ""} It was working before, but then I've started encountering error that the variables like "text" were defined, so I've put there just an empty string, which now passes into the dictionary, not the forms' real data. Thank you. -
Attribute error, with exception value: safe
After adding to the model save function, attribute error occurs with exception value = 'self'. Code: from django.db import models from djmoney.models.fields import MoneyField from PIL import Image class Item(models.Model): title = models.CharField(max_length=150) price = MoneyField( decimal_places=2, default=0, default_currency='USD', max_digits=11, ) image = models.ImageField(upload_to='pictures', default='static/images/man.png') def save(self): super().save() img = Image.open(self.image.path) if img.height > 350 or img.width > 350: new_img = (350, 350) img.thumbnail(new_img) img.self(self.image.path) -
Using class in Python/Django testing to make code more reusable
I need some help with my testing architecture. My code works but it seems ugly for me. Could you take a look : The goal is to make the same tests for all my pages in Django : I wrote a unit testing.py from django.urls import reverse, resolve class SinglePageTest(object): str_reverse = '' adresse = '' template = None template_path = '' str_contain = '' def initialize(self): self.url = reverse(self.str_reverse) self.view = resolve(self.adresse) self.response = self.client.get(self.url) def test_status_200(self): self.assertEqual(self.response.status_code, 200) def test_templates_home(self): self.assertTemplateUsed(self.response, self.template_path) def test_contains_HTML(self): self.assertContains(self.response, self.str_contain) def test_url_resolve(self): self.assertEqual(self.view.func.__name__, self.template.as_view().__name__) When I need to test a page in test.py I do this : from django.test import TestCase, SimpleTestCase from DjangoTools.testing import SinglePageTest class RetrievePassword(SimpleTestCase, SinglePageTest): def setUp(self): self.str_reverse = 'retrieve-password' self.adresse = '/accounts/retrieve-password' self.template = RetrievePasswordView self.template_path = 'accounts/retrieve-password.html' self.str_contain = '<h1>🔑 Récupérer le <span class="clr-org">mot de passe</span></h1>' super(RetrievePassword, self).setUp() SinglePageTest.initialize(self) The problem is that PyCharm doesn't find the reference for a lot of method in testing.py and that's normal cause I'am using a basic object that doesn't contains these methods. My questions are : Is-it well to do like this ? Can I say that I'm using Mixins ? How to tell pycharm to find assertTemplateUsed, client.get … -
How to get only the base model instances from query?
Hopefully my question won't have been asked before. I've the following models in my Django app: from django.db import models class A(models.Model): some_attribute = models.SomeField() def some_method(self): do_stuff() # Note: not abstract class B(A): def some_other_method(self): do_other_stuff() Now, if I have one A and one B in the database, when I issue a A.objects.filter() call, I get the A and also the B instance (as expected). But what if I in fact only want the instances of A specifically? I don't see how to write is as an .exclude() instruction. Could filtering with type == "A" be the intended way? -
Get serializer fields in RelatedField serializer django rest
class ScreenCategorySerializer(serializers.ModelSerializer): screen = ScreenListingField(many=True, read_only=True) class Meta: model = ScreenCategory fields = ['id', 'title', 'screen', 'active', 'position'] class ScreenListingField(serializers.RelatedField): def to_representation(self, value): res = {} res['id'] = value.id res['title'] = value.title res['layout'] = value.layout res['project'] = value.project.id res['last_change'] = value.last_change res['width'] = value.width res['height'] = value.height res['background_color'] = value.background_color if value.constant_color is None: res['constant_color'] = None else: res['constant_color'] = value.constant_color.id res['styles'] = value.styles res['base'] = value.base return res I have the following serializer, inside the ScreenListingField I would like to get the id of the ScreenCategory. How can I get it? -
how to pass data from multiple checkboxes created in django template using for loop to views.py without using forms
This is my html form in which i have a text field for a word and i am running a for loop which created checkbox for the list of document a user has and displays it as form. <body> <form id="form" method = "POST"> {% csrf_token %} <fieldset id="User"> <legend>Your details:</legend> <p><label for="word">Enter your word</label> <input type="text" id="word" name="word"> </p> {% for doc in docs %} <p> <input type="checkbox" id="{{ doc.document_id }}" name="docid" value="{{ doc.path }}"> <label for="{{ doc.document_id }}"> {{ doc.document_name }} </label><br> </p> {% endfor%} <input type="submit" value="Submit" > </fieldset> </form> </body> In views.py I have below method which loads this html page def client_home(request): client_pr = Client_Profile.objects.get(user_id=request.user) events = Event.objects.filter(client_id=client_pr.pk) name = request.POST.get('word') id = request.POST.get('docid') print(name) print(id) docs = [] for eve in events: docs = Document.objects.filter(event_id=eve) context = {'events': events, 'docs': docs} return render(request, 'Elasticsearch/form.html', context) My question is as i am using a for loop create checkbox field based on number of documents a user has and when I try to print them in my Views.py file it is only priniting last document id whose checkbox is created and not all the documents. -
If and else don't save into None
I am a student who is learning Django. Although Views.py was created as follows, there is a problem that the else part of join_detail is not saved in the DB. There is no error and it is not saved at all. Which part is the problem? I attach the full code of views.py and some code that has a problem. def join_create(request, id): current_category = None designated = Designated.objects.all() designated_object = Designated.objects.filter(rep_price='True') value_p = Value.extra_cost element = Element.objects.all() value_object = Value.objects.all() categories = Category.objects.all() products = Product.objects.all() if not request.user.is_authenticated: return HttpResponseRedirect(reverse('zeronine:login')) if request.method == "POST": product = Product.objects.get(product_code=id) join = Join() join.product_code = product join.username = request.user join.save() if request.method == "POST": form = ElementForm(request.POST) if form.is_valid(): for value_code2 in request.POST.getlist('value_code2'): element = Element() element.designated_code = Designated.objects.get(product_code=id) element.value_code = get_object_or_404(Value, pk=value_code2) element.save() else: element = Element() element.designated_code = Designated.objects.get(product_code=id) element.value_code = None element.save() if request.method == "POST": form = JoinDetailForm(request.POST) if form.is_valid(): for quantity, price2, value_code2 in zip(request.POST.getlist('quantity'),request.POST.getlist('price2'),request.POST.getlist('value_code2')): join_detail = JoinDetail() join_detail.join_code = join join_detail.designated_code = Designated.objects.get(product_code=id) join_detail.value_code = get_object_or_404(Value, pk=value_code2) join_detail.quantity = quantity join_detail.price = price2 join_detail.save() else: for quantity, price2 in zip(request.POST.getlist('quantity'),request.POST.getlist('price2')): join_detail = JoinDetail() join_detail.join_code = join join_detail.designated_code = Designated.objects.get(product_code=id) join_detail.value_code = None join_detail.quantity = quantity … -
Template does not exist for django authentication views
Django newbie here. I am just trying to make a password change form using Django authentication system. I used my own views for login and logout functionality. I read the docs and for password change form as mentioned, I made a registration folder inside my templates directory and made a template html file named password_change_form.html , but when I go to the url http://127.0.0.1:8000/accounts/password_change , I keep getting the error TemplateDoesNotExist at /accounts/login/ . Here is my app structure: and my urls.py file: from django.urls import path,include from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('',views.home_page,name='home_page'), path('register',views.registration_view,name='registration_view'), path('login',views.login_view,name='login_view'), path('logout',views.logout_view,name='logout_view'), path('accounts/',include('django.contrib.auth.urls')), ] What and why is this happening? Please help. I would appreciate it. -
django admin gives error when trying to access a certain model
I'm making a web page that for the purposes of this question, we can say it has 2 models. a User model and an Order model. Users log in and order what they want. the Order model has a foreign key referencing the User model. and ifI try to order something, specifically if I try to give the userID field of the Order model some value, it works just fine, or at least seems like it. Then when I try to look at the list of orders in the admin page I get the following Error: ValueError at /admin/dashboard/order/ invalid literal for int() with base 10: b'22 11:28:34.566846' and this is the whole traceback: Environment: Request Method: GET Request URL: http://localhost:8000/admin/dashboard/order/ Django Version: 3.2.5 Python Version: 3.9.6 Installed Applications: ['mainpage', 'regpage', 'loginpage', 'dashboard', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\Mohsen\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Mohsen\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Mohsen\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\options.py", line 616, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\Mohsen\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\Mohsen\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response … -
Django filtering on DateTimeField extremely slow
Environment AWS RDS t3.micro (2 vCPUs, 1GiB RAM) PostgreSQL 11.10 I have more than 15 million records of Note, the model of which is like: class Note(models.Model): ... post_date = models.DateTimeField() ... FYI, Note has 35+ fields, some of which are ManyToManyField and ForeignKey fields. Problem start_time = time.time() queryset = Note.objects.filter( # post_date=datetime.now() - timedelta(days=6), post_date__year=2021, post_date__month__gt=7, )[:100] tmp = list(queryset) print("Time elapsed: ", time.time() - start_time) The code above takes just 0.68 seconds, but if I uncomment # postTs=datetime.now() - timedelta(days=6), the time increases to 55.53 seconds. To mitigate this issue I'm considering converting the DateTimeField to PositiveIntegerField for storing timestamp values instead. Before taking that step, is there anything else that I can try? Why is this happening? -
Django: Problem deleting many-to-many database objects when the are connected with a through-table
Django produces an error that I cannot delete a composer object that used to be related to a spotifyartist object through a custom through table. My Django app is called 'music' and I'm using mysql/mariadb as the database The error Django produces when deleting a composer object is: IntegrityError at /admin/music/composer/(1451, 'Cannot delete or update a parent row: a foreign key constraint fails (bladmuziek.music_composer_spot_artist, CONSTRAINT music_composer_spot__composer_id_4d30a8de_fk_music_com FOREIGN KEY (composer_id) REFERENCES music_composer (id))') Even after I delete the entry in the through-table for the composer + Spotify artist pair, and there is no obvious connection (to me) any more between the two model objects, I still cannot delete a (previously connected) composer or Spotify artist object. I cannot figure out how I seem to violate the constraint that the error message talks about. I guess I don't fully understand the error message, and do not know for sure if it has to do with the constraint that I added in the through model or it if is some other constraint. Any suggestions on how to fully understand the error message and delete the Django object are appreciated. The relevant snippets of my code are the composer model, the spotifyartist model, and … -
order by with field that is not in group by fields django orm
final_submission: the submission which has the maximum score. I want query which gives me a list of final submissions for each problem and participant that is sorted with submitted time. Submission.objects.all().values('participant_id', 'problem_id').annotate(Max('score')).order_by('-submitted_time') above query does not work. I don't know how to order by with a field that is not in group by fields -
Django logger file setup failure
I am trying to set up the logger but getting the following error on my production env. Same settings are working on my dev env, can someone please point out the issue. Following are my settings