Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ManyToManyField referencing self: Rendering to template
Below is the code for a project I'm working on. As you can see in the view, I'm running a query for objects in the Risk model that are associated with the primary key in the Url. The problem is that I can't access the attributes of the object being queried. Model class Risk(models.Model): risk_title = models.CharField(max_length=60) root_causes = models.ManyToManyField('self', through='Roots', symmetrical=False, related_name='root_cause') class Roots(models.Model): causal_risk = models.ForeignKey(Risk, related_name='causes', on_delete=models.CASCADE) effected_risk = models.ForeignKey(Risk, related_name='effected_risk', on_delete=models.CASCADE) View: def view_risk(request, id): try: risk = Risk.objects.get(pk=id) except Risk.DoesNotExist: raise Http404("Risk does not exist") roots = Roots.objects.filter(effected_risk=id) args = { 'risk': risk, 'roots': roots, } Template: {% for root in roots %} {{ root }} {% endfor %} Running the above code returns this: Roots object (2) Roots object (3) This should be expected, as these are the entries I've made to the model through the admin interface. However, when I run: {% for root in roots %} {{ root.risk_title }} {% endfor %} The screen is left blank. TLDR Passing the query from the intermediary table to the template works, but the template can't access the object attributes. How can I run the above query and then access the objects in the template? … -
Zero-width space makes HTML link unclickable
I'm creating a link to a page based on the name the user gave that page. However, the link is unclickable if the name is a zero-width space. How can I stop users from giving pages unclickable names? I'd like to allow Unicode characters if possible. The names are being entered into the database through a Django form, and the HTML link is being built in jQuery. Django complains if the name is a regular space, but accepts a zero-width space. var linkText1 = 'foo', linkText2 = '\u200b'; $('#ex1') .append($('<a>') .text(linkText1) .attr('href', 'javascript:alert("clicked.")')); $('#ex2') .append($('<a>') .text(linkText2) .attr('href', 'javascript:alert("clicked.")')); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p id="ex1">Example 1 </p> <p id="ex2">Example 2 </p> -
Copy all fields of a class derived from an abstract model (Django)
I have two models A and B of the same structure derived from the same abstract model: class CommonInfo(models.Model): name = models.CharField(max_length=100) # ... # more fields class Meta: abstract = True class A(CommonInfo): pass class B(CommonInfo): pass Now having an object of class A, I want to create an object of class B with the same values of fields. What is the proper Django way to copy all fields of one object to the other? The only way I know is to enumerate all fields (by the way, how to do it?) of an object and store them in the other object. But is there an easier way? -
crispy forms tabs non English
I am relative new to coding. My problem is that although my crispy form works fine, I want to write the tabs and label forms in Greek. When I do that inside the Tab crispy forms can't see to recognize the Greek alphabet. On tabs just changes the tab without displaying the content. On label (input) just hide the input, rendering only the English characters. class ExampleForm(ModelForm): helper = FormHelper() helper.form_method = 'POST' helper.layout = Layout( TabHolder( Tab('A', 'name', #in Greek 'ονομα' doesn't being rendered# 'surname', 'birthdate', 'school_id'), Tab('B', 'fathers_name', 'fathers_surname', 'fathers_origin'), ), ) helper.layout.append(Submit('submit', 'Submit')) class Meta: model = Example fields = ['name' , 'surname' , 'birthdate', 'school_id' , 'fathers_name', 'fathers_surname', 'fathers_origin'] enter image description here enter image description here -
Django TemplateDoesNotExist at /admin/login/ message although admin is installed
Seem to be sufferring from a brain freeze and can't the following working. I have a Django Saleor application and trying to get the default Django admin interface working here, but getting a TemplateDoesNotExist at /admin/login/ error. The debug part says this: Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /var/www/html/applications/py-saleortakeaway/templates/admin/login.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python3.5/dist-packages/django/contrib/sitemaps/templates/admin/login.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python3.5/dist-packages/django/contrib/auth/templates/admin/login.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python3.5/dist-packages/django/contrib/postgres/templates/admin/login.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python3.5/dist-packages/django/forms/templates/admin/login.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python3.5/dist-packages/versatileimagefield/templates/admin/login.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python3.5/dist-packages/bootstrap4/templates/admin/login.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python3.5/dist-packages/django_prices/templates/admin/login.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python3.5/dist-packages/graphene_django/templates/admin/login.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python3.5/dist-packages/mptt/templates/admin/login.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python3.5/dist-packages/payments/templates/admin/login.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python3.5/dist-packages/django_filters/templates/admin/login.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python3.5/dist-packages/impersonate/templates/admin/login.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python3.5/dist-packages/debug_toolbar/templates/admin/login.html (Source does not exist) This is what I have in settings.py under templates: TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(PROJECT_ROOT, 'templates')], 'OPTIONS': { 'debug': DEBUG, 'context_processors': context_processors, 'loaders': loaders, 'string_if_invalid': '<< MISSING VARIABLE "%s" >>' if DEBUG else ''}}] Django admin is installed in 'installed' apps and the url is mapped to /admin. Any help is really appreciated. -
No such file or directory when trying to collect static files on Heroku
I’m trying to add a static directory of files, to contain javascript, css, and the like) to my Django app that I’m deploying on Heroku. The storage is being done with AWS S3 and I know this part is working because before trying to add this static directory, command heroku run python manage.py collectstatic worked just fine, putting all the admin site’s assets in my AWS S3 bucket. Basically I added a directory called ‘static’ at the same level as my project’s main application, which is called ‘core’. I was hoping when I ran collectstatic, the files in this directory would similarly be placed in my AWS S3 bucket, under ‘static’. But this is what I get when I try to deploy the app on Heroku... (primedminds-FA7a2hIW) bash-3.2$ git push heroku master Counting objects: 2, done. Delta compression using up to 4 threads. Compressing objects: 100% (2/2), done. Writing objects: 100% (2/2), 236 bytes | 236.00 KiB/s, done. Total 2 (delta 1), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! The latest version of Python 3.6 is python-3.6.6 (you are using python-3.6.5, which is unsupported). remote: ! We … -
shared django project structure
This is what the structure of my project is. This question will ignore the 'lib' directory: project app data -> migrations, models, __init__.py prodsite -> settings.py, urls.py, wsgi.py, __init__.py testsite -> same as above lib data -> migrations, models, __init__.py prodsite -> settings.py, urls.py, wsgi.py, __init__.py, common models testsite -> same as above tools manage.py I want to be able to run: python tools/manage.py app.prodsite (makemigrations/migrate) app It was not hard to modify manage.py so that it adds the root directory to the system path, sets the django environment variable to 'app.prodsite', and deletes that argument from sys.argv, before continuing on with what manage.py normally does. I could not manage to get rid of the last parameter without causing errors: #!/usr/bin/env python import os import sys import inspect def main(): sys.path.append(os.getcwd()) # allow reative to cwd, not just module.py. if "DJANGO_SETTINGS_MODULE" not in os.environ: if len(sys.argv) < 3: print("Error in command: {}".format(" ".join(sys.argv))) print("manage.py should be called like:\r\n" "manage.py <app> <operation>.") return os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{}.settings".format(sys.argv[1])) del sys.argv[1] try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a … -
How to make the input param optional in Django?
The is my serializer.py and I want to make image as an optional field which means either there's an uploaded image or null. But even though I set up required false for image, when sending the POST request it will still ask for image and gives the error of no im class UserSerializer(serializers.ModelSerializer): Class Meta: model = User field = ('name', 'division', 'image',) extra_kwargs = {'image': {'required': False}} def create(self, validated_data): newUser = User.objects.create( name = validated_data['name'], division = validated_data['division'] image = validated_data['image'] ) return newUser; Any ideas? -
AWS Django Multiple Errors in logs apps.populate(settings.INSTALLED_APPS)
I am new to AWS and cannot make sense of this error. I am using Django 2.1, python 3.6 and aws elasticbean stalk. I am not sure what other information I can provide to help but will add any info if needed. [:error] [pid 28878] django.setup(set_prefix=False) [:error] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup [:error] apps.populate(settings.INSTALLED_APPS) [:error] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/apps/registry.py", line 81, in populate [:error] raise RuntimeError("populate() isn't reentrant") [:error] RuntimeError: populate() isn't reentrant [:error] mod_wsgi (pid=28878): Target WSGI script '/opt/python/current/app/weddingProject/wsgi.py' cannot be loaded as Python module. [:error] mod_wsgi (pid=28878): Exception occurred processing WSGI script '/opt/python/current/app/weddingProject/wsgi.py'. [:error] Traceback (most recent call last): [:error] File "/opt/python/current/app/weddingProject/wsgi.py", line 16, in <module> [:error] application = get_wsgi_application() [:error] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application I have tried searching for similar errors but no luck. -
Django middleware to 'do nothing' if certain criteria are met
I am trying to figure out how to create authentication middleware in python/django. Here is an example: def middleware_function(request): if not user.is_admin: return redirect('login') else: pass def secure_view(request): user = request.usera middleware_function(request) print ("ok, you've passed security") return render(request, 'secure_view.html') is the above a 'valid' way to do this? In that, it will re-direct if conditions aren't meant, but pass if things are ok? -
Share funtions between several projects
i have two projects very similars, and they have severals functions in common, i wanna use those common functions for both, How can I do that? each project has its own database and particular functions, I just want to have the common functions in one place and, and when I modify them, they are modified for both projects -
Unable to update the Existing row in the Models.py
i am facing the issue while updating the Models in the DB, following are the details of the same: I am entering the values to the empty models as Humidity to 15.44, if Humidity is not existed then it will create the row and value will be 15.44 Image consisting of 15.44 as new value Suppose i want to send the values of Humidity as 20.44, in this case if the humidity is already existed then the values should get updated i.e. 20.44 in place of old 15.44. Humidity value updated with existing one Now when i send the humidity value as (20.44,11.11) single entry this values should be updatede in place of 20.44 but instead of this it is creating the new row as entire value of Humidity and not updating the existing one. New values/row created for humidity PFB the code i am using for the above task. Kindly help me if any one knows about this. try: entitycurrentvalue = EntityCoreCurrentValue.objects.get(entityid = EntityCore.objects.get(aEntityId=pk), name = entityAttribute['name']) DatastreamCount = float(entitycurrentvalue.Datacount) Data_avg_value = float(entitycurrentvalue.average_value) current_avg_value = ((Data_avg_value*DatastreamCount)+float(entityAttribute['value']))/(DatastreamCount+1) entitycurrentvalue.value = float(entityAttribute['value']) entitycurrentvalue.type = entityAttribute['type'] entitycurrentvalue.units = entityAttribute['units'] entitycurrentvalue.average_value = current_avg_value entitycurrentvalue.Datacount = DatastreamCount+1 entitycurrentvalue.rangeMin = rangemin entitycurrentvalue.rangeMax = rangemax if entitycurrentvalue.ObservedMin … -
Selenium tests are not able to interact with any of the elements
So I know that when I have DEBUG in my Django settings set to False, Selenium fails to have access to the static files, resulting in something looking like: this However, when I run my Selenium tests regardless they are able to interact with the DOM and select items from the dropdown! The test code I have is currently from selenium.webdriver import Chrome from selenium.webdriver.support.ui import Select from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from urllib.parse import urljoin import time driver = webdriver.Chrome() driver.get("localhost:8000/") time.sleep(3) driver.find_element_by_id('select-dance').click() select = Select(driver.find_element_by_xpath('//*[@id="select-dance"]')) select.select_by_value('1') driver.find_element_by_id('select-date-range').click() select = Select(driver.find_element_by_xpath('//*[@id="select-date-range"]')) select.select_by_value('1') driver.find_element_by_id('location').click() When I set DEBUG to True, the page renders how I want it to because it has access to the static files. But whenever I try to run the tests I always get the error selenium.common.exceptions.ElementNotVisibleException: Message: element not interactable What the search bar looks like with all of the static files working This seems to happen for any element I refer to. For some reason, when I try to click on the dropdown directly, it always highlights this input and the select tag always seems to be 'hidden', so I wonder if that may be causing the error See here Thank you … -
Django: web app And mobile app: which authentication system to choose: Jwt vs session cookie
I have Django project: Web App: I will be creating a web app where Django serves the html pages. Mobile App: Here Django acts as backend and Android acts as Frontend. Django api end points supply the data I am thinking to use JWT for both. But I am not sure how JWT can be managed in web APP. Suppose some one opens the web app in two tabs. He logs out in one of the tab. If its session cookies, then the other tab will ask for login if one tries to perform any authorized task. Here how to do this JWT. Assume i am loggged into site in firefox and chrome simultaneously If I expire the JWt token to logout then both chrome and firefox sessions will be logged out. But I want to logout only on chrome or firefox and keep the other live. -
Django filter all querysets based on requestor
Is there a way with a Manager or another method that would allow me to filter all querysets on some field based on the current requestor so that I don't have to explicitly do it everytime? -
Django+Nginx+Gunicorn : [error] 2194#2194: *15 upstream prematurely closed connection while reading response header from upstream
I have an API that i made using Django 2.1, DRF, Gunicorn, Nginx, and Tensorflow. I am running this on a Droplet with Ubuntu 18.04 x64 and 1 GB of memory. The API is configured so that it only allows POST method to invoke the API. When sending a request, the API will expect a zip file and response a string. When i first use this on my local machine, nothing went wrong. However, when i move it to the cloud and use nginx and gunicorn to serve the API, i receive the following error from the nginx's error.log [error] 1186#1186: *9 upstream prematurely closed connection while reading response header from upstream, client: CLIENT_IP_ADDRESS, server: HOST_IP_ADDRESS, request: "POST /api/beta/some-app/ HTTP/1.1", upstream: "http://unix:/home/user-name/django-api/django.sock:/api/beta/some-app/", host: "HOST_IP_ADDRESS". After exploring many questions regarding this error, i decided to include the following logging in my django app's settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'verbose': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, 'simple': { 'format': '{levelname} {message}', 'style': '{', }, }, 'handlers': { 'fileDebug': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': "/var/log/debug_django.log", }, 'fileError': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': "/var/log/debug_django.log", }, 'fileCritical': { 'level': 'CRITICAL', 'class': 'logging.FileHandler', 'filename': … -
django python form to submit, delete row from database and refresh page
I am newbie in Django and I would appreciate if someone can help me about this problem. I have a database in backend with 100 rows of users information. Name, surname, phone number. The database is visible on Home page template and if you choose one of this names you can donate something to this person. When you click on submit button will lead you to new ajax window where you input your data and then submit. Then I got your message on email. My questions is how to do at the same time to confirm (submit) and delete row from database (person from database) and then to refresh page ? Meaning, when you submit form then function should delete person from Home page at once and have to refresh page so you can see another person ? Here is the code. I would appreciate any help. Thanks to all. views.py def about(request): context = { 'num_toys': '1', } return render(request, 'about.html') # , context=context def couses(request): db_queryset = Children.objects.all() context = {'child': db_queryset} return render(request, 'couses.html', context=context) class ChildrenListView(ListView): model = Children context_object_name = 'child' class ChildrenCreateView(CreateView): model = Children form_class = ChildrenForm success_url = reverse_lazy('children_changelist') class ChildrenUpdateView(UpdateView): model … -
geodjango return geojson from raw SQL
have this django view: I am aware I can use this to serialize a postgres table to geojson def mun_datasets(request): mun = serialize('geojson', Municipalities.objects.all()) return HttpResponse(mun, content_type='json') however I have a very complex query which needs to be in raw SQL so I am trying to figure out how to return geojson from a raw SQL query (the query below is very simple but the actual query is complex so I just want to know how to return geojson from any sql query to apply the concept to harder queries) def mun_datasets(request): cur = conn.cursor() qry='''select json_object_agg(namelsad,geom) from reporter_municipalities''' cur.execute(qry) row=cur.fetchone() mun = serialize('geojson', row) return HttpResponse(mun, content_type='json') this gives me an error on my mun_dataurl AttributeError at /mun_data/ 'dict' object has no attribute '_meta' Request Method: GET Request URL: http://127.0.0.1:8000/mun_data/ Django Version: 1.11 Exception Type: AttributeError Exception Value: 'dict' object has no attribute '_meta' Exception Location: /usr/local/lib/python3.6/dist-packages/django/contrib/gis/serializers/geojson.py in start_object, line 38 Python Executable: /usr/bin/python3 Python Version: 3.6.5 Python Path: ['/home/ralph/Desktop/geo', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/ralph/.local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Fri, 12 Oct 2018 14:00:44 +0000 -
Django: NameError after creating a model
I am having a strange error when trying to create model instances for a homepage. I am running a script from the django python shell containing: def populate_homepage(): home = HomePage.objects.create(name="Seeker Test") navbar_logo = "seeker_theme/img/seekicon.png", entry_names = ["Home", "Aboot", "Capabilities", "The Team", "Contact"] nav_bar = NavBar.objects.create(name="navbar", home_page=home, logo="seeker_theme/img/seeker.png") for name in entry_names: print(name) Entry.objects.create(nav_bar=nav_bar, primary=False, link="#" + name.lower(), text=name) It appears as though whenever I create a model, such as when I define nav_bar, all variables declared in the function scope disappear (entry_names, navbar_logo), and I get an error. Is there any strangeness happening behind the scenes in Django that would make this happen? Does python leave the scope of populate_homepage? And is there a workaround? This doesn't happen when I declare variables in a global scope outside of the function, but I would like everything to be contained in the populate_homepage method. -
Change price field according to exchange rate django
is there anyway to change price field dynamically according to the days exchange rate of dollar? in django?? Example: class Sales(models.Model): price = models.DecimalField() """ other codes goes in here """ -
Django: Pass arguments in View and display on the page
Say, I've 2 views in views.py: Fetching_information_view Processing_view In Fetching_information_view I am fetching information which I am displaying to the user in the tabular format on the "home.html" page. That's all okay. Now, I get a CSV URL for each row as well. I don't want that when the user clicks on the CSV URL it should open the CSV, instead when the user clicks on it then it should go to the Processing_view and served on a different HTML page, say "process.html". CSV URL: "/some_bucket/some_csv_file.csv?AWSAccessKeyId=some_id&Expires=1234&Signature=some_signature" Desired URL: "http://example.com/process.html?file=some_bucket/some_csv_file.csv?AWSAccessKeyId=some_id&Expires=1234&Signature=some_signature Now, how can I call Processing_view from Fetching_information_view view and send the file information, which process in the backend and display results on process.html This is the table I am showing on the homepage: If you need any particular code snippet, I will try to give that too. -
Using Django ModelForm for one-to-many relationships
I'm trying to extend the Django (version 2.0) tutorial so that it uses ModelForm to create a question with a least one or two choices. I have two models Question and Choice which have a one-to-many relationship. What do I need to do to my model, form, views, and template to generate a field(s) for choice? I've seen a few posts suggesting Inline but that seems like it's only for admin pages. polls/models.py from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) polls/forms.py from django.forms import ModelForm from .models import Choice, Question class QuestionForm(ModelForm): class Meta: model = Question fields = ['question_text', 'pub_date', 'choice'] polls/views.py from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from django.utils import timezone from django.views import generic from .forms import QuestionForm from .models import Choice, Question def create_question(request): if request.method == 'POST': form = QuestionForm(request.POST) if form.is_valid(): question_text = form.cleaned_data['question_text'] pub_date = form.cleaned_data['pub_date'] question = Question(question_text=question_text, pub_date=pub_date) question.save() return HttpResponseRedirect(reverse('polls:index')) else: form = QuestionForm() return render(request, 'polls/create-question.html', {'form': form}) polls/create-question.html {% extends 'polls/base.html' %} {% block scripts %}{% endblock scripts %} {% block content %} … -
Run python application separately on each computer
I have a basic django application that runs ifconfig and displays the logs. The app is running from my laptop and all the other laptops connected to the same WiFi network are able to access this application. However, on running the application on other computers, I am getting the same logs that I was getting from my own laptop,ie, I am getting the ip address of my own laptop. Is there a way in which I can get the django app to run individually for each computer? -
TypeError: get_available_name() got an unexpected keyword argument 'max_length'
Here is a form that used can accept image upload. I changed somewhere so now it will say TypeError: get_available_name() got an unexpected keyword argument 'max_length' when I upload a image. I have searched for some solutions but I did not override any original function. Some of the answer says that set max_length=None, but I did not find where to set so. Can I save my code and make it accept pictures again? Thanks. Here is the view.py part def post_page(req,post_id): if req.method=="POST": check_result = checkrecaptcha(req.POST.get('g-recaptcha-response')) if check_result: inp = SendPost(req.POST,req.FILES) if inp.is_valid(): inpp = inp.clean() post = Post() post.content=inpp.get("content") post.save() rt=inpp.get('replied_to') if inpp.get("image"): post.image=req.FILES.get("image") if inpp.get("anon")!="anon": if req.user.is_authenticated: post.post_by=req.user else: return HttpResponse("need to login") post.save() return HttpResponseRedirect("/b/"+str(post_id)+"/"+"#"+str(post.id)) else: return HttpResponse("Be a good guy2.") else: return HttpResponse("Be a good guy1.") And here is the form.py part class SendPost(forms.Form): content = MarkdownxFormField(max_length=50000) replied_to = forms.IntegerField(required=False) image = forms.ImageField(required=False) anon = forms.CharField(required=False) And it says Internal Server Error: /b/1/ Traceback (most recent call last): File "C:\Users\catmo\PycharmProjects\mooncake\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\catmo\PycharmProjects\mooncake\venv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\catmo\PycharmProjects\mooncake\venv\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\catmo\PycharmProjects\mooncake\comma\views.py", line 47, in post_page post.save() File … -
Sort on decimal annotation does not work as expected
I can't understand this: >>> qset = Produit.objects.annotate( Prix_au_kg=Case(When(Poids__gt=0, then=(F('Prix') * 1000) / F('Poids')), default=Decimal(0), output_field=models.DecimalField())) >>> qset.order_by('Prix_au_kg').values_list('Prix_au_kg', flat=True) <QuerySet [Decimal('0'), Decimal('11.500000'), Decimal('112.235294'), Decimal('115.666667'), Decimal('118.888889'), Decimal('13.900000'), Decimal('15.727273'), Decimal('17.142857'),... It seems to be ascii ordering and not numeric as expected. What I am doing wrong ?