Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Customise django-activity-stream Action’s content
I’m using it for the first time and it just took a few minutes to set it up and running. However, I wanted to have below pattern for the final notification: [Date/time of comment][User Role][Username] commented on [Target]. However, I can only see this fixed syntax: action.send(User, verb='commented on', target=myObject) I can’t figure out how to customize it. -
how to set parameter in json in django?
I am newbie to dJango and javascript. I am trying to pass the variable into the parameter in my function so that the function is called using the variable. Below are codes. view.py def plot_graph(request,column): data = Data.objects.all() \ .extra(select={'data': connections[Data.objects.db].ops.date_trunc_sql('data', column)}) \ .values(column) return JsonResponse(list(data),safe=False) urls.py urlpatterns = [ url(r'^form/$', views.Form), url(r'^api/plot_graph/(?P<column>[\w-]+)', views.plot_graph, name='plot_graph'), ] form.html var c = {{column_json | safe}} d3.json("{% url "plot_graph" column=c %}", function(error, data) { data.forEach(function(d){ d.c5 = d.c5; }); What I want to do is that variable c is passed into the d3.json so that function plot_graph is used according to the variable c. However, below code gives me an error saying that Reverse for 'plot_graph' with keyword arguments '{'column': ''}' not found. 1 pattern(s) tried: ['index/api/plot_graph/(?P<column>[\\w-]+)'] How to resolve this issue? -
when set gid, uwsgi aborted
below was my uwsgi.ini file: [uwsgi] module = myblog.wsgi #socket = 127.0.0.1:8000 chdir = /opt/python3/myblog buffer-size = 32768 home = /root/.pyenv/versions/3.7.1/envs/blog/ env = DJANGO_SETTINGS_MODULE=myblog.settings socket = /opt/python3/myblog/myblog.sock pidfile2 = /var/run/uwsgi/uwsgi.pid daemonize2 = /var/log/uwsgi/uwsgi.log log-format = %(addr) - %(user) [%(ltime)] "%(method) %(uri) %(proto)" %(status) %(size) "%(referer)" "%(uagent)" process = 4 threads = 2 uid = 1000 gid = 1000 master = true chmod-socket = 664 chown-socket = nginx:nginx # clear envirnment to exit vacuum = true when I set the uid and gid, and I tried to start uwsgi, it abortd. The error info was below. uWSGI running as root, you can use --uid/--gid/--chroot options setgid() to 1000 setuid() to 1000 Python version: 3.7.1 (default, Dec 18 2018, 07:21:59) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] !!! Python Home is not a directory: /root/.pyenv/versions/3.7.1/envs/blog/ !!! Set PythonHome to /root/.pyenv/versions/3.7.1/envs/blog/ Fatal Python error: initfsencoding: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' Current thread 0x00007fc575d01840 (most recent call first): Aborted but if I only set the uid and annotate gid. It works fine. I don't know why. It's really make me confused. -
Django filter sub elements in single query
I have a django DRF project tracking students in classes at a school. There are teachers, students, administration, and school_classes. Not all students are verified, but administration should see all students while teachers should only see verified students. It's simple enough to make a queryset so when teachers query for students, they only get back verified students. But the problem comes when a teacher queries a class and goes to access school_class.students. Here it will list out all the students, whether or not they are verified. How can I have the students list filtered in the same query that fetches the class? -
How does this work? {now:%Y/%m/%Y%m%d%H%M%S}{ext}"
I am reading Django Cookbook 2 and I came across an image upload form that doesn't work as expected. When the user uploads an image it names the image as the date and time at that moment in time. What I can't figure out is when the form saves, it doesn't actually render to have numbers in it and stays with the %Y/%m characters. return f"profile/{now:%Y/%m/%Y%m%d%H%M%S}{ext}" Secondly, why is there an "f", because it keeps throwing an error if I don't remove it. Views.py from django.utils.timezome inport now as timezone_now def upload_to(instance, filename): now = timezone_now() base, ext = os.path.splitext(filename) ext = ext.lower() return f"profile/{now:%Y/%m/%Y%m%d%H%M%S}{ext}" -
Django Image Uploading Via ModelForm Error 400 Bad Request, While Using Channels and ASGI
i am creating a Django Chatting application, using Django Channels but if i want to upload file or Image ajax or http then django return error 400 (Bad Request) also Django Default Admin not Uploading File. When i upload a file using Admin App i also found error 400, please help with that if i remove Channels library then its all working fine, Server only Give error 400 while ASGI, with WSGI server everything Working Fine Django Channels ASGI File Uploading (Profile Image) i have tries to solve, but no solution found Thanks -
Middleware not executed by Django
I am trying to include a middleware in a Django project, but it seems the middleware is not being executed by Django. The idea is to impersonate another user account when having app-administrator privileges. The MIDDLEWARE section of my settings.py file looks like this: 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', 'mird_project.monitor.middleware.impersonateMiddleware.ImpersonateMiddleware', ] The middleware class looks like this: from .models import Usuario class ImpersonateMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_request(self, request): us_obj = Usuario.objects.all().filter(id_usuario=request.user.username).first() tipo = us_obj.tipo.id_tipo if tipo == "AD" and "__impersonate" in request.GET: request.session['impersonate_id'] = request.GET["__impersonate"] elif "__unimpersonate" in request.GET: del request.session['impersonate_id'] if tipo == "AD" and 'impersonate_id' in request.session: request.user = Usuario.objects.get(id_usuario=request.session['impersonate_id']) return None I inserted an assert False, request inside the process_request method so that it would abort execution with an exception and show me what request contained. It never even got executed, so I assume the middleware never gets executed. It doesn't throw any kind of error and the impersonation mechanism just displays the same administrator user in the site. Any ideas why the middleware isn't being called? -
Django celery trigger manage.py cmd @periodic_task
i want to run a manage.py cmd from celery as a periodic task every x Minutes but every time i try to accomplish that as show below i get the following error: [2019-01-17 01:36:00,006: INFO/MainProcess] Received task: Delete unused media file(s)[3dd2b93b-e32a-4736-8b24-028b9ad8da35] [2019-01-17 01:36:00,007: WARNING/ForkPoolWorker-3] Scanning for unused media files [2019-01-17 01:36:00,008: WARNING/ForkPoolWorker-3] Unknown command: 'cleanup_unused_media --noinput --remove-empty-dirs' [2019-01-17 01:36:00,008: INFO/ForkPoolWorker-3] Task Delete unused media file(s)[3dd2b93b-e32a-4736-8b24-028b9ad8da35] succeeded in 0.0008139749998008483s: None @periodic_task(run_every=(crontab(minute='*/90')), name="Delete unused media file(s)", ignore_result=True) def delete_unused_media(): try: print("Scanning for unused media files") management.call_command('cleanup_unused_media --noinput --remove-empty-dirs') return "success, old media files have been deleted" except Exception as e: print(e) that management cmd comes from the following project: https://github.com/akolpakov/django-unused-media is my management call simply wrong or whats the deal? thanks in advance -
Celery with Redis broker in Django: tasks successfully execute, but too many persistent Redis keys and connections remain
Our Python server (Django 1.11.17) uses Celery 4.2.1 with Redis as the broker (the pip redis package we're using is 3.0.1). The Django app is deployed to Heroku, and the Celery broker was set up using Heroku's Redis Cloud add-on. The Celery tasks we have should definitely complete within a minute (median completion task is ~100 ms), but in Heroku's provided Redis viewer (powered by Redis Labs), we're seeing that Redis keys and connections are persisting for much, much longer than that (minutes and hours). Otherwise, tasks are being executed correctly. What can be happening that's causing these persisting keys and connections? How can we ensure that they are cleared when Celery tasks conclude? Here's a Redis Labs screenshot of this happening (all tasks should have completed, so we'd expect zero keys and zero connections): -
How to get data from a HTML table into DJango
I'm relatively new to web development so I'm not sure that I'm taking the correct route with this. I have a web app for home buyers to submit their information (address and such). With such a purchase, you can have multiple buyers (such as you could have with a business). I've included a table and some text boxes where when filled out, a new buyer is added as a row in the table using java script. I'm not sure exactly how to get this information back into DJango, although I have read where it might involve AJAX calls. Does anyone have any pointers? Thank you. -
Impossible to run the gunicorn because of the import error
I have had a django==2.1 project with virualenv. Then to solve some package problems I created another virtualenv for my project and activated it. However whenever I run gunicorn --bind 0.0.0.0:8000 myproject.wsgi:application I am receiving the following problem. Traceback (most recent call last): File "/home/root/uzagro_4/agrosenv/lib/python3.5/site- packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/home/root/uzagro_4/agrosenv/lib/python3.5/site- packages/gunicorn/workers/base.py", line 129, in init_process self.load_wsgi() File "/home/root/uzagro_4/agrosenv/lib/python3.5/site- packages/gunicorn/workers/base.py", line 138, in load_wsgi self.wsgi = self.app.wsgi() File "/home/root/uzagro_4/agrosenv/lib/python3.5/site- packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/root/uzagro_4/agrosenv/lib/python3.5/site- packages/gunicorn/app/wsgiapp.py", line 52, in load return self.load_wsgiapp() File "/home/root/uzagro_4/agrosenv/lib/python3.5/site- packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp return util.import_app(self.app_uri) File "/home/root/uzagro_4/agrosenv/lib/python3.5/site- packages/gunicorn/util.py", line 350, in import_app __import__(module) ImportError: No module named 'myproject' [2019-01-17 04:16:14 +0500] [21107] [INFO] Worker exiting (pid: 21107) [2019-01-17 04:16:14 +0500] [21104] [INFO] Shutting down: Master [2019-01-17 04:16:14 +0500] [21104] [INFO] Reason: Worker failed to boot. I have no idea how to solve this problem. This is my gunicorn.service file: [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=nginx WorkingDirectory=/home/root/uzagro_4 ExecStart=/home/root/uzagro_4/agrosenv/bin/gunicorn --workers 3 --bind unix:/home/root/uzagro_4/myproject.sock uzagro_4.wsgi:application [Install] WantedBy=multi-user.target And the nginx.conf file: server { listen 80; server_name agros.uz www.agros.uz; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/root/uzagro_4/; } location / { proxy_set_header Host $http_host; proxy_set_header … -
Django Form field not appearing
I am receiving a This field is required error using a form view that django is generating. I have a Scan model that looks like: class Scan(models.Model): device = models.ForeignKey(Device, null=True, on_delete=models.SET_NULL) created_at = models.DateTimeField('Created', auto_now=True) data = models.FileField(upload_to='uploads/') def __str__(self): return str("{}-{}".format(self.device, self.created_at)) I have a CreateView defined: class ScanCreate(LoginRequiredMixin, CreateView): model = Scan fields = '__all__' My url route is urlpatterns = [ ... path('scan/create/', views.ScanCreate.as_view(), name='scan-create'), ... ] and finally a scan_form.html template {% block content %} <form action="" method="post"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Submit"> </form> {% endblock %} On submitting the form, I get the 'This field is required.' error and the request fails: I note that the created_at field does not appear in the form and I believe the error is related to this missing field. Should this field not appear populated within the create view? -
Django filter based on joined model
Let's say I have the following design database table A track has a song and a song has a singer. I would like the track allows filtering based on singer name too. So, I need the track model extract the singer name. I got stuck with the filters. I receive the following error message: File ".../lib/python3.6/site-packages/django_filters/filterset.py", line 352, in get_filters "%s" % ', '.join(undefined) TypeError: 'Meta.fields' contains fields that are not defined on this FilterSet: singer I have heard from this to use __ but I have no idea how to apply that. Here is the code class TrackSerializer(MyModelSerializer): singer = serializers.SerializerMethodField() def get_singer(self, track): # Is there any shortcut? song = Song.objects.get(id=track.song_id) if song is not None: return Channel.objects.get(id=song.singer_id).name else: return '' class TrackFilterSet(MyFilterSet): singer = CharFilter(method='singer_filter') song = RefineModelChoiceFilter( queryset=Song.objects.all(), refine_choices=lambda qs, keywords, request: qs.filter(name__icontains=keywords) ) def singer_filter(self, queryset, name, value): # print('queryset:', TrackSerializer(queryset, many=True)) return queryset.filter(**{ name: value, # ??????????? }) class Meta: model = Track fields = ( 'singer', 'song', ) class TrackViewSet(MyViewSet): queryset = Track.objects.all() serializer_class = TrackSerializer filterset_fields = ('singer', 'song') def filter_refine_choices_singer(self, qs, keywords, request): return qs.filter(name__icontains=keywords) def filter_refine_choices_song(self, qs, keywords, request): return qs.filter(name__icontains=keywords) -
Django rest framework retrieving lists in serializers
Take the following example into account. I have two models, one Author and one Article. They look like so: # author.py from django.db import models class Author(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) def __str__(self): return self.first_name # article.py from django.db import models from authors.models import Author class Article(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) text = models.TextField() def __str__(self): return self.text My serializers look like so: from rest_framework import serializers from .models import Article from authors.serializers import AuthorSerializer class ArticleSerializer(serializers.ModelSerializer): author = AuthorSerializer() class Meta: model = Article fields = '__all__' from rest_framework import serializers from .models import Author class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = '__all__' Now, if I wish to get articles from my API, that's simple. Getting articles attaches the author and that's all well and good -- but how do I get the inverse? For instance, if I want to get authors with the latest 5 articles that they have written? So the intended output would be something like: { "first_name": "Sethen", "last_name": "Maleno", "articles": [ { "text": "some article" }, { "text": "another article" } ] } -
Sending image and JSON simultaneously
I want to pass JSON object and image at the same time from react to my django rest api. I've tried some solutions from this forum and tutorials but nothing worked in my case. Previously I have been using JSON.stringify on state fields and that worked but i couldn't pass image and now i ended up on something like this. postData.js let formData = new FormData(); const { title, description, image, ingredient, step } = this.state; formData.append('image', image); formData.append('title', title); formData.append('description', description); formData.append('ingredient', ingredient); formData.append('step', step); let conf = { method: 'post', body: formData, headers: new Headers({ 'Content-Type': 'multipart/form-data', 'Accept': 'application/json' }) }; fetch('http://127.0.0.1:8000/api/', conf) .then(res => { this.props.history.push('/'); }) .catch(err=>{console.log(err)}) serializers.py class RecipeSerializer(serializers.ModelSerializer): ingredient = IngredientSerializer(many=True, required=False) step = StepSerializer(many=True, required=False) class Meta: model=models.Recipe fields=('id', 'title', 'description', 'image', 'ingredient', 'step', ) def create(self, validated_data): ingredient_data = validated_data.pop('ingredient') step_data = validated_data.pop('step') recipe = models.Recipe.objects.create(**validated_data) for ingredient in ingredient_data: models.Ingredient.objects.create(recipe=recipe, **ingredient) for step in step_data: models.Step.objects.create(recipe=recipe, **step) return recipe views.py class ListRecipes(generics.ListCreateAPIView): queryset = Recipe.objects.all() serializer_class = RecipeSerializer class DetailRecipe(generics.RetrieveUpdateDestroyAPIView): queryset = Recipe.objects.all() serializer_class = RecipeSerializer I always get POST http://127.0.0.1:8000/api/ 400 (Bad Request) error. -
'auth.User' has been swapped for
I'm following the official Django documentation : https://docs.djangoproject.com/en/2.1/topics/auth/customizing/#substituting-a-custom-user-model My Django version is 2.1. The goal is to extend the default auth.User Django Model. I have exactly the same code that is in the example. I got an app, "user", and my AUTH_USER_MODEL in settings.py is "user.User". But I get this error : AttributeError: Manager isn't available; 'auth.User' has been swapped for 'user.User' I can't find informations... Thank you ! -
django double left join + django rest framework serializers
I have these models: class Item(models.Model): name = models.CharField(max_length=100) class Group(models.Model): name = models.CharField(max_length=100) class ItemGroup(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) Means an item can be in multiple groups. I want to query all items, and for each item return his groups as a nested list (or an empty list if the item does not appear in a group). This is what I would do with sql: SELECT item.id, item.name, group.name FROM items LEFT JOIN item_group ON item.id = item_group.id LEFT JOIN group ON group.id = item_group.group_id (I might add an ORDER BY too, for paging, but nevermind for now). This query would give me every item X number of groups the item is connected too, and at least one row for an item that does not appear in any group (with group set to null). Then, I'll need to convert it to a nested list manually. The question: 1. How to do the same joins with django ORM? This is the closest question I've found: django left join But the answer isn't actually a left join, but a prefetch_related, which I want to avoid. 2. If I would create a nested dict of models like this: … -
Django HyperlinkedSerializer slug instead of PK for field
Dog model has a field "cat' class Dog(models.Model): ... cat = models.ForeignKey(Cat) ... Cat rest_views work fine. Dog rest_views work fine if I remove the 'cat' field from fields class CatSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Cat # Replace ID with SLUG in urls lookup_field = 'slug' fields = ('url', 'slug') extra_kwargs = { 'url': {'lookup_field': 'slug'} } class DogSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Dog fields = ('url', 'slug', 'cat') lookup_field = 'slug' extra_kwargs = { 'url': {'lookup_field': 'slug'} } class CatViewSet(viewsets.ModelViewSet): def get_serializer_context(self): context = super().get_serializer_context() context['slug'] = self.kwargs.get('slug') return context queryset = Cat.objects.all() serializer_class = CatSerializer lookup_field = 'slug' class DogViewSet(viewsets.ModelViewSet): queryset = Dog.objects.all() lookup_field = 'slug' serializer_class = DogSerializer router = routers.DefaultRouter() router.register(r'cats', rest_views.CatViewSet) router.register(r'dogs', rest_views.DogViewSet) The error I get when I add the cat in dog serializer fields: Could not resolve URL for hyperlinked relationship using view name "cat-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. -
Scrollable vertical menu jumps to top after clicking on a link
Good evening community, I have a problem related to a vertical menu that is scrollable when there are more items in the menu than the page can take vertically. If I scroll down to an item that is not displayed on the screen when I'm at the top of the menu and I click this item to get to the respective page, the page will get loaded but the menu jumps back to the top, so that the item i just clicked is not displayed on the screen again. But I want that the part of the menu with the item is shown when the new page is loaded and not the top of the menu. I'm developing my site with python and django and using bootstrap for frontend, if that helps with my problem. I will add some pictures to visualize my problem. Sadly i can't post pictures directly yet. Starting Position 1 <- This is the top of the menu with the page 'Einführung' loaded Scrolled Position 2 <- This is the scrolled position and I want to click the 'Print-Funktion'-link Top Position 3 <- This is the menu after I clicked on the link (top position) Scrolled … -
How to use Basic HTTP Django Authorization middleware?
I don't understand the django middleware snippet here: https://djangosnippets.org/snippets/1304/ I have incorporated the middleware correctly, and upon visiting my site, I can manually enter in the username and password and authenticate with the decorator. My problem is that I don't know how to send a request from Postman/curl to authenticate. I have included an "Authorization" header in my Postman request, but I don't know how to format the values. For example: "Authorization: user password" def __call__(self, request): if 'HTTP_AUTHORIZATION' not in request.META: return self._unauthed() else: authentication = request.META['HTTP_AUTHORIZATION'] (auth_method, auth) = authentication.split(' ', 1) if 'basic' != auth_method.lower(): return self._unauthed() auth = base64.b64decode(auth.strip()).decode('utf-8') username, password = auth.split(':', 1) if ( username == settings.BASICAUTH_USERNAME and password == settings.BASICAUTH_PASSWORD ): return self.get_response(request) return self._unauthed() -
Signal django to run a task
I made a management command that populates one of my models from a csv file. I need to do this update quite frequently and the csv files have tens of thousands of lines. Sometimes it can take over 10 minutes to finish populating. I want to add a feature that lets me upload the csv file through the website directly and after the file is uploaded, django should run that command, or at least the logic from it, and populate the db. How would I go about this? I want to be able to leave the page after I upload the file and receive an e-mail when the task is finished. -
How do I include intermediary Models in my Django Rest Framework API
I am in the process of learning about the Django Rest Framework at the moment and I stumbled unto a tricky part that I can't seem to get working in our project. Our project is a fictional webshop where you can put dog babies in your cart and order them. Our Frontend is communicating with the backend via Django Rest Framework. The three main models that we have are Users, Orders and Puppies. Because every order has a list of puppies and every puppy has its own amount we needed an intermediary model for the two as a simple ManyToManyField apparently can't handle extra columns. This makes things much more complicated (at least for someone who is new to Django). How can I reflect the relationship in the serializers and the views and how do I have to form the JSON Object that is sent from the frontend? also: Where would I calculate the total price of an order? Do I need the OrderDetail view even if I don't want to edit or get one specific order or is the DetailList view enough? There is a question on here which is solving a similar problem: Include intermediary (through model) in … -
Editing a .JSON file from the Django Admin Panel using Models
I'm setting up the admin panel for Django to allow easy editing of a .json file with names and information. The problem is that the file isn't static and it's not modified by just me but also by code running in the background that modifies and adds new values. Sometimes these values can be incorrect so I'm trying to get it so i can manually edit them using the admin panel from Django. Example JSON file: { "101": { "First_Name": "Ida", "Last_Name": "Wilkins", "Age": "42", }, "102": { "First_Name": "Tony", "Last_Name": "Davis", "Age": "34", } } I've already tried using serialize but I only really managed to get it loaded into the admin panel and not out of it it also didn't really look this was a good way to do it. I also can't really find any information on how to do this and if it's even possible. -
Group models by field similarity in Django/PostgreSQL
Let's say I have a Person model: from django.db import models class Person(models.Model): name = models.CharField(max_length=256) Instances of this model have been populated from an existing data source, and I would now like to merge similar People together by name. It is trivial to find the names similar to a given name ("Bob", here): Person.objects.all() # Annotate each item with its unaccented similarity ranking with the given name .annotate(similarity=TrigramSimilarity("name__unaccent", "Bob")) # And filter out anything below the given threshold .filter(similarity__gt=0.9) This will generate (something close to) the following: SELECT "person"."id", "person"."name", SIMILARITY("cases_person"."name", 'Bob') AS "similarity" FROM "cases_person" WHERE SIMILARITY("cases_person"."name", 'Bob') > 0.9 But, what I want are groupings of similar people. This can be done in Python with some modifications to the above: from django.contrib.postgres.search import TrigramSimilarity from .models import Person people = Person.objects.all() threshold = 0.9 people_ids_to_merge = [] processed = set() for name in people.values_list("name", flat=True): similar_people = ( # We must exclude any people that have already been processed, because # this means they are already in people_ids_to_merge. If we didn't # exclude them here, we would get duplicates in people_ids_to_merge people.exclude(id__in=processed) # Annotate each item with its unaccented similarity ranking with the current name .annotate(similarity=TrigramSimilarity("name__unaccent", name)) … -
Django won't accept a decimal as a decimalfield
I have a an api endpoint that receives some data (a decimal in string form). It then needs to multiply it by something from the db, which is a DecimalField, and save the result into another DecimalField (via a model serialiser). I've tried the following (request.data["hours"] is a string, hourly_rate is a decimal from a DecimalField) total = request.data["hours"] * hourly_rate - fails, multiplying string by Decimal total = Decimal(request.data["hours"]) * hourly_rate - fails total = (Decimal(request.data["hours"]) * hourly_rate - fails).to_eng_string() - fails In all but the first, 'fails' means the following error: {'total': [ErrorDetail(string='A valid number is required.', code='invalid')]} I would have expected it to accept a Decimal, and I've read that it should accept a string, but apparently not...