Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python manage.py migrate --fake-initial errors on initial migration
I have a new Django app pointing to an existing django database and so I want to skip some initial migrations. However, even running fake-initial still tries to run the initial migrations: raise InconsistentMigrationHistory( django.db.migrations.exceptions.InconsistentMigrationHistory: Migration donate.0001_initial is applied before its dependency campaign.0003_remove_medicalcenter_npi_num_and_more on database 'default'. What's the point of python manage.py migrate --fake-initial then?? -
Used code found here for django site for encryption. But I don't get any data
I am calling a module I wrote in python to generate some data that I need to pass to a user. When I call that module it works fine, except when I run it via the django framework. When I run it under django I get an error that the data set is empty. I checked the variables and there is indeed data there, however, when I try to get the first block of data it yields an empty data set: block_size 16 cipher <Crypto.Cipher._mode_cbc.CbcMode object at 0x7f0cd9dff940> data ['\x13\x91Õ\x13Ïßû!-\x02&[èWÒ\x8e'] enc b'\x13\x91\xd5\x13\xcf\xdf\xfb!-\x02&[\xe8W\xd2\x8e' self <btc_leak_app.scripts.mymodule.AESCipher object at 0x7f0cd9dbc910> to_decrypt b'' Here is the code in question: class AESCipher(object): def __init__(self, key): self.bs = AES.block_size self.key = hashlib.sha256(key.encode()).digest() def encrypt(self, raw): raw = self._pad(raw) iv = Random.new().read(AES.block_size) cipher = AES.new(self.key, AES.MODE_CBC, iv) return base64.b64encode(bytes(iv.decode("latin-1") +";;;;"+ cipher.encrypt(raw.encode()).decode("latin-1"), "latin-1")) def decrypt(self, enc): enc = base64.b64decode(enc).decode("latin-1") data = enc.split(";;;;") iv = data[0].encode("latin-1") enc = data[1].encode("latin-1") cipher = AES.new(self.key, AES.MODE_CBC, iv) to_decrypt = enc[AES.block_size:] return self._unpad(cipher.decrypt(to_decrypt)).decode('latin-1') def _pad(self, s): return str(s, "utf-8") + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs) @staticmethod def _unpad(s): print("unpad", s) return s[:-ord(s[len(s)-1:])] Lastly, I'm going to link where I got the code from -
Can my django website run other scripts that interact with the same database?
I am wanting to run another script (from within the django app?) that can parse some text files to put values into the mysql database my django website uses. Then a webpage loads it would grab those values and display them. I am not sure the right way to go about this, ideally I can just create a python script that runs as a cron job and does standard mysql stuff to get and change the data in the same table the django app reads, or is there a more django way to do this? from within the django app? I am not sure how to run scripts 'on the side' or 'like a cron job' from within django. -
Performance issues when using Solr, Django-Haystack, and standard Django filter query
I am working with Solr via Django-Haystack to refine a basic Django queryset by text-searching a large data table. My primary database is postgresql. I have approximately 3 million rows of Record objects and 13 million rows of Info objects. These will both grow over time, so I'm using Solr to index the description field. I am running into significant performance issues when I try to work with the Solr results in Django. Here are the models (abbreviated): class Record: name = models.CharField() class Info: record = models.ForeignKey(Record...) description = models.CharField() I'm starting with a queryset of all Records. The goal is to filter it down using a text query against descriptions in the Info model. queryset = Record.objects.all() When I query Solr, using Django-Haystack, I can get a list of Info objects pk's that match the query string: sqset = SearchQuerySet().filter(text=query_string).values_list('pk', flat=True) sqset can be 500+ items in length. So when I attempt to use it in a standard query using __in in Django, I end up executing a massive SQL query with hundreds of ORs: queryset = queryset.filter(info__id__in=sqset) Django Debug Toolbar tells me the SQL is performant (approx 60ms on average). The Solr portion of the query also … -
Django authenticationform and active users
If I change a current user's status to inactive, they are not able to login. This is expected. However, the error message they receive is to enter in a proper username and password. I expect that they should get the inactive login message. I am subclassing the authentication form: class CustomAuthenticationForm(AuthenticationForm): """Sub-class authentication form to remove whitespace""" def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') username = ''.join(username.split()) password = " ".join(password.split()) if username is not None and password: self.user_cache = authenticate( self.request, username=username, password=password) print("tried again") if self.user_cache is None: print("self cache") raise self.get_invalid_login_error() else: print("self confirm") self.confirm_login_allowed(self.user_cache) return self.cleaned_data When I try to log in as a user that has a username and password but it now inactive, the tried again and self cache get printed to the console. Since the user is inactive I would expect the self confirm statement to be printed to the console, and this would lead to the confirm_login_allowed function and the correct ValidationError. For what its worth, I am subsclassing this form because I had some users that could not login using their Android phone - their web browser was inserting whitespace. My CustomAuthenticationForm removes this whitespace. -
Validating the current state of a model using DRF?
Our application allows users to specify which fields are required for a particular model. This model also has a status field. There can be different requirements based on the status. For example, status = foo and status = bar will require a different set of fields to be set. The challenge is how to validate that these fields have been set. If we simply had to validate that the required fields were set when creating a new instance, we could set required=True at runtime. However, because it's based on the status, we need to be able to validate an arbitrary model instance against a list of required fields and verify that those fields are set. As an example, suppose we are patching an existing model instance. Even if we know what the required fields are, patching by design does not support required=True. The patch may change a field to be empty, so we need to validate how the model looks after the patch is applied. One idea is to serialize the model instance, then have a function that takes the serialized dict and the list of required fields, and checks each one by hand. This approach is straightforward, but I'd … -
Heroku Free Database Issues
if I use the free version of Heroku where can i find the database, cause in Resources -> add-ons there is nothing I need to get a database to use it on a local server -
Would Postgres data base break if I change a model field name? (heroku)
Feels like a silly question, but I cannot seem to find an answer. I have a number of changes that I need to migrate. Amongst those changes, I have a model field name that has been changed. On local, Django worked out the model field just changed name (simply asked confirmation that old field = new field). I know Postgres and Heroku sometimes behave differently. I left the code below, it's quite simple but the possibility to lose the database worries me. Below is what the local migration look like on local class Migration(migrations.Migration): dependencies = [ ('main', '0085_modelname_timeframe'), ] operations = [ migrations.RenameField( model_name='modelename', old_name='timestamp', new_name='created_at', ), ] and this is the model.py class ModelName(models.Model): user = models.ForeignKey(UserProfile, blank=True, null=True, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) Does Heroku work out field name changes easily, or is it something to avoid? -
Form field on front end that allows for decimal input while storing integer value in database
While using Django Forms I have no solution for converting a decimal number to an integer. Use case: input field on a HTML form generated by Django should allow for decimals. The database will only allow for integers. As Django builds the form using javascript for this is not so straightforward. I found Django creating a custom model field but with so many new tools around with Django haven't been able to get it working. Has anybody an advice of how to get this done with a custom model field? Thanks, Gert --- update --- currently everything works as it should. Though I'm re-writing this app in Django form another framework. In that framework I used JavaScript to tackle converting decimals to integers. I'd prefer just to have integer or text values in the database as using the date in different systems might give me problems if I start to use decimals. What I currently have: models.py ----------- from django.db import models from django.urls import reverse from datetime import date CHOICES_PERSONEN = ( (1, "1"), (2, "2"), ) class Nota(models.Model): name = models.CharField(max_length=255) d_s = models.PositiveSmallIntegerField( choices = CHOICES_PERSONEN, default = 2, ) # amount = models.IntegerField(null=True, blank=True) amount = … -
Can I pass dynamic variables to placeholders that are defined in the msgstr, but not in the msgid in Django i18n?
In Django I have a .po file that contains translations in this format: msgid "delete-comment-description" msgstr "Are you sure you want to delete this comment?" There are also translations that require a dynamic value: msgid "hello-user-title" msgstr "Hello, %(user)s. I hope you are fine." How can I pass the variable user to use hello-user-title in a template? I've tried things like: {% blocktranslate with user="my_username" %} hello-user-title {% endblocktranslate %} and {% translate "hello-user-title" user="my_username" %} But both are not working. The reason the msgid is more of a variable name is because this application is partly in React and partly in Django. React is leading for most frontend parts, but some parts are generated by Django templates. I18n was already enabled for React and all translations are managed using a SaaS (Lokalise). Lokalise is also the source of Django's .po files, as I want this service to be the central point of managing translations. This is also relevant to reduce work. Both "delete-comment-description" and "hello-user-title" are also used (and already translated) for react. Translation naming is different between Django's approach and other approaches like the i18n-next approach we use for React. In short: it is not an option for … -
Struggling to get celery worker to run locally
I am running Django 1.8 and Celery 3.1 (not up to me, please refer from comments). I'm trying to get celery to work locally just as it would on production, asynchronously. In one of my Django views I'm sending a potentially long-running task to celery: long_running_task.delay(*args) Which I am defining as a shared_task: @shared_task def long_running_task(*args): # does stuff return { 'success': not error, 'error': error } Then I am having the client polling periodically with ajax requests and depending on response.status act accordingly (show error to the user, refresh relevant parts of the page, etc). @require_GET @login_required def long_runniing_task_poll(request): task_id = request.GET.get('task') if not task_id: return JsonResponse({'error': unicode(_("'Missing task_id parameter.'"))}, status=400) task = long_running_task.AsyncResult(task_id) return JsonResponse({'status': task.status, 'result': task.get()} However, the actual task doesn't seem to be run by celery at all. This is what I get when -------------- celery@DESKTOP-TPGU0DO v3.1.25 (Cipater) ---- **** ----- --- * *** * -- Windows-10-10.0.22621 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: mysite:0x42b7c88 - ** ---------- .> transport: django://localhost// - ** ---------- .> results: - *** --- * --- .> concurrency: 3 (prefork) -- ******* ---- --- ***** ----- [queues] -------------- .> celery exchange=celery(direct) key=celery This … -
How to filter an object based on string from another view
I'm displaying a list of drinks in a template. The drinks model has a many-to-many field with tags that group drinks together. I now want to filter the list of drinks based on this tag. I've made the tag model like this: class Tag(models.Model): drink_tag = models.CharField(max_length=255, blank=False) def __str__(self): return f"{self.drink_tag}" def get_tag_link(self): return reverse('rhumSite:drinkDetailTag',kwargs={'tag':self.drink_tag}) This way, each tag has a link to a page that will display all the drins with said tag. In my URLS.py file the path looks like this: path('cocktails/<str:tag>/',DrinksFilteredListView.as_view(template_name='rhumSite/drinks.html'),name='drinkDetailTag'), When I click on a tag the url is indeed cocktails/tagname so that works well. I now want my listview to take that tag and display all drinks from the drinks model with this tag. My view looks like this: class DrinksFilteredListView(ListView): model = DrinkRecipe context_object_name = 'drinks' def get_queryset(self): return DrinkRecipe.objects.filter(drink_tag__drinkrecipe=self.kwargs['tag']) def get_context_data(self, **kwargs): context= super(DrinksListView, self).get_context_data(**kwargs) context['tags'] = Tag.objects.all() context['tastes'] = TagTaste.objects.all() context['bottles'] = Bottle.objects.all() return context I know I have to use get_queryset(self): but I still struggle with getting the query right. The current code leads to an error in get_context_data: super(type, obj): obj must be an instance or subtype of type specifying this line: context= super(DrinksListView, self).get_context_data(**kwargs) This also prevents me … -
Unable to design login page in HTML for django
I have created a login page using HTML as Django templates. Somehow the box sizes and shapes are not equal. I have tried so hard to make it beautiful but unable to do so. I am new in HTML and Django. I need help how to do this. Need to add more style with good visual. My code is given below: <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> body { font-family: Arial, Helvetica, sans-serif; } * { box-sizing: border-box; } /* style the container */ .container { position: relative; border-radius: 5px; background-color: #f2f2f2; padding: 20px 0 30px 0; } /* style inputs and link buttons */ input, .btn { width: 100%; padding: 12px; border: none; border-radius: 4px; margin: 5px 0; opacity: 0.85; display: inline-block; font-size: 17px; line-height: 0.85 px; text-decoration: none; /* remove underline from anchors */ } input:hover, .btn:hover { opacity: 1; } /* add appropriate colors to fb, twitter and google buttons */ .fb { background-color: #3B5998; color: white; } .twitter { background-color: #55ACEE; color: white; text-align: center; } /* style the submit button */ input[type=submit] { background-color: #55ACEE; color: white; cursor: pointer; } input[type=submit]:hover { background-color: #55ACEE; } /* Two-column layout */ .col { … -
Django Password Expiry
If HR add a user with first_name, last_name, email, username, and password. after setting the password the password must only access for 5 minutes, after the time period the password is not usable for login purpose. Does anyone know how to solve this problem in django -
AttributeError: 'Project' object has no attribute 'remark_set'
I am new to django, was following a tutorial and trying to use 'model_set.all()' but I don't understand the error. I tried changing it to 'project_content_type.remark_set.all()' (thinking it's an error with the related name. Error: response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\lavis\Desktop\aai\env\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\lavis\Desktop\aai\base\views.py", line 80, in project project = project.remark_set.all() ^^^^^^^^^^^^^^^^^^ AttributeError: 'Project' object has no attribute 'remark_set' models.py class Project(models.Model): host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) #p_id = name = models.CharField(max_length=200) location = models.ForeignKey(Location, on_delete=models.SET_NULL, null=True) totalamount = models.IntegerField(null=True, blank=True) payments_todate = models.IntegerField(null=True,blank=True) description = models.TextField(null=True,blank = True) updated = models.DateTimeField(auto_now = True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-updated','-created'] def __str__(self): return self.name class Remark(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) project = models.ForeignKey(Project,related_name='project_content_type', on_delete=models.CASCADE) body = models.TextField() updated = models.DateTimeField(auto_now = True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.body[0:50] views.py def project(request, pk): project = Project.objects.get(id=pk) remark_made = project.remark_set.all() context = {'project':project, 'remark_made':remark_made} return render(request, 'base/project.html',context) -
Are there some elegant ways to partially save a huge form on Django?
This is more of a conceptual question rather than specifically a technical one. I have a Model that has like 20-30 entries on the database, there are 5-6 required fields and currently I'm driving my Form class from ModelForm. We have designed a somewhat elegant UI at Front-End in our template that takes these fields step by step so we don't overwhelm the user with a giant fieldset on a single response. Now the problem is our Required Model fields are scattered through these steps (Single-Page Accordion UI) and we are trying to save the actual data on a step by step basis so the end user will be able to continue filling the form from the last checkpoint later on. How do we approach this situation, considering the Model also has a UUID that will be Not Editable, So I'm assuming I can't just use some temporary tables in between the process, or can I? -
Django: cors different subdomain host development
I am on a project with django version 3.2.8. the site is hosted on example.com, we plan to register a subdomain host work.example.com to dump all work stuff in. the main reason is that work.example.com would make CORS apply, which some dangerous request is not accessiable even when authenticated when you are on work.example.com the company currently host the web on a rented server, we do not want interupting the running server for development and it is really a lot of work to boot another server. sorry that I have little knowledge on this aspect, I realize that there is little relative resouces and doubt if it’s practical at all. I want a developing environment to test the sub domain url routing and views. I have tried: (on a MacOS Montery 12.6 Intel Core i9) sudo nano /etc/hosts # add this to the end 127.0.0.1 example.com 127.0.0.1 work.example.com # save and close the file and refresh DNS sudo dscacheutil -flushcache then I refresh browser cache started django server, 127:0:0:0 Still works but example.com This site can't be reached, seems example.com still did not point to my localhost. I wonder if it is possible to develpe this subdomain host functionality with … -
How to configure Nginx reverse proxy in Docker
I'm trying to configure Nginx as reverse proxy for my docker container but doesn't work with local subdomains. docker-compose.yml: services: nginx: container_name: tmc_nginx_ctnr ... ports: - '80:80' - '443:443' authentication: container_name: tmc_authentication_ctnr hostname: authentication.localhost ... command: python manage.py runserver 0.0.0.0:8000 ports: - '8002:8000' authentication.conf: server { listen 80; server_name authentication.localhost; location / { proxy_pass http://authentication:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } } Inside Nginx container I run these command: $ curl http://authentication.local:8000 curl: (6) Could not resolve host: authentication.local $ curl http://authentication:8000 <!DOCTYPE html> ... Any idea how to fix it ? -
Django: Access the entire pk_set of pre_add and pre_remove of M2M Signal
I have two models Group and Child as defined below, The Group has a M2M relation to the Child. When the m2m field children in the Group model is changed then all the add events and remove events are separated into different action class Child(models.Model): name = models.CharField(max_length=100) req_categories = ArrayField(models.CharField(choices=Categories.choices, max_length=100)) class Group(models.Model): name = models.CharField(max_length=100) categories = ArrayField(models.CharField(choices=Categories.choices, max_length=100)) children = models.ManyToManyField(Child, blank=True) I want a way to access the pk_set of pre_add and pre_remove at a single place to perform some validation currently I have a validation rule that says atleast N number of children should exist so if I place the validation on pre_remove for an action where i removed some child and added some child then the validation error will be thrown even though the upcoming pre_add action will take care of the contraint @receiver(m2m_changed, sender=Group.children.through) def child_models_changed(sender, instance, action, **kwargs): if action == "pre_add": do validation .... if action == "pre_remove": do validation .... -
My Django is suddenly showing KeyError when I add a new document
My API used to work perfectly whoever now whenever I add a new document I get KeyError message (It didn't do that before and I haven't change anything on my python code :(...) the message is something as follows: KeyError at /domain/ 'jXLTurf56ECMhhbNJB9w' Request Method: POST Request URL: my url Django Version: 4.1.5 Exception Type: KeyError Exception Value: 'jXLTurf56ECMhhbNJB9w' Exception Location: /app/My_API/views.py, line 632, in post Raised during: My_API.views.My_RS_ModelBased Python Executable: Python Version: 3.10.9 I tried deleting whatever new document I added and it started working again -
Where does "AttributeError: 'VendorAlias' object has no attribute 'find_spec'" come from?
I'm currently trying to update a larger codebase from Python 3.8 to Python 3.11. I use pyenv to manage my Python versions and poetry to manage my dependencies: pyenv local 3.11.3 poetry update When I run pytest I immediately get: python -m pytest -n 1 Traceback (most recent call last): File "<frozen importlib._bootstrap>", line 1074, in _find_spec AttributeError: 'VendorAlias' object has no attribute 'find_spec' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/martin/.cache/pypoetry/virtualenvs/web-backend-4tJQ0X3K-py3.11/lib/python3.11/site-packages/django/utils/module_loading.py", line 58, in autodiscover_modules import_module("%s.%s" % (app_config.name, module_to_search)) File "/home/martin/.pyenv/versions/3.11.1/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1140, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 1076, in _find_spec File "<frozen importlib._bootstrap>", line 1049, in _find_spec_legacy ImportWarning: VendorAlias.find_spec() not found; falling back to find_module() During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<frozen importlib._bootstrap>", line 1074, in _find_spec AttributeError: 'VendorAlias' object has no attribute 'find_spec' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "/home/martin/.cache/pypoetry/virtualenvs/web-backend-4tJQ0X3K-py3.11/lib/python3.11/site-packages/pytest/__main__.py", … -
I am getting a TypeError that my Django ChoiceField's choices are unhashable Type: 'list'
I'm new to Django. I use formset and form via TabularInline. First, I'll show you my forms.py code. DISCONN_BLANK = ((None, '---disconnect---'),) CONN_BLANK = ((None, '---connect---'),) class MyFormSet(BaseInlineFormSet): def get_form_kwargs(self, index): kwargs = super(MyFormSet, self).get_form_kwargs(index) kwargs.update({'parent': self.instance}) return kwargs class MyForm(select2_modelform(Conninfo)): class Meta: model = Conninfo fields = ['mgr_id', ] parent_value = None def __init__(self, *args, **kwargs): instance = kwargs.pop('parent') if instance: self.parent_value = instance print('MyFrom __init__ parent_value {}'.format(self.parent_value)) super(MyForm, self).__init__(*args, **kwargs) conn_queryset = tuple(Conninfo.objects.filter(client_id=self.parent_value).values('mgr_id').values_list('mgr_id', 'mgr_id')) disconn_queryset = tuple(Devicemanager.objects.exclude(mgr_id__in=Conninfo.objects.all().values('mgr_id')).values_list('mgr_id', 'mgr_id')) mgr_id_widget = select2_modelform(Conninfo)().fields['mgr_id'].widget choices = DISCONN_BLANK + tuple(disconn_queryset) + CONN_BLANK + tuple(conn_queryset) print(choices) print(type(choices)) self.fields['mgr_id'] = forms.ChoiceField(choices=choices, widget=mgr_id_widget) Does it seem very complicated..? The point is the conn_queryset and disconn_queryset and choices parts. The type of choices is tuple, and when I try to print ((None, '---disconnect---'), (('id1', 'id1'), ('id2', 'id2'), ... ('id10', 'id10'), ( None, '---connect---'), ('id14', 'id14'), ('id15', 'id15')) It comes in the form of a tuple. But what about the results? TypeError at unhashable type: 'list' where is the list? Isn't list {}? I really don't know. And the strange thing is that if you take the last code out of the init function from conn_queryset, it will be executed. Of course, it doesn't give me the … -
Django: Can I use Subquery with more than one database?
I have two 2 tables in different databases. # Database A class Category(models.Model): name = models.CharField(max_length=100) # Database B class Hero(models.Model): # ... name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) benevolence_factor = models.PositiveSmallIntegerField( help_text="How benevolent this hero is?", default=50 ) Can I use Subquery like this: hero_qs = Hero.objects.filter( category=OuterRef("pk") ).order_by("-benevolence_factor") Category.objects.all().annotate( most_benevolent_hero=Subquery( hero_qs.values('name')[:1] ) ) Actually, I found this: https://books.agiliq.com/projects/django-orm-cookbook/en/latest/subquery.html but no example with different databases. -
On using Multipartparser or formparser classes Swagger documentation won't load, the error - "cannot instantiate nested serializer as Parameter"
I am using a nested serializer as shown below - class Documents_ManagerSerializer(serializers.ModelSerializer): class Meta: model = Documents_Manager fields = ['id', 'doc_type', 'doc_name'] class IndexDetailsCreateSerializer(serializers.ModelSerializer): methodology_file = Documents_ManagerSerializer() Factsheet_file = Documents_ManagerSerializer() Indexvalues_file = Documents_ManagerSerializer() class Meta: model = IndexDetails fields = ['id', 'Tab_id', 'Name' ,'methodology_file','Factsheet_file','Indexvalues_file'] I am using parser classes = Multipartparser and formparser to upload files in swagger documentation, following is my views code - @method_decorator(name='create', decorator=IndexDetailsSwagger.create()) @method_decorator(name='partial_update', decorator=IndexDetailsSwagger.update()) class IndexDetailsView(viewsets.ModelViewSet): parser_classes = (MultiPartParser, FormParser) queryset = IndexDetails.objects.filter(Valid=True).all() serializer_class = IndexDetailsSerializer http_method_names = ['get', 'post', 'patch'] def get_serializer_class(self): if self.action in ["create"]: return IndexDetailsCreateSerializer elif self.action in ["partial_update"]: return IndexDetailsPatchSerializer else: return self.serializer_class def retrieve(self, request, *args, **kwargs): try: instance = self.get_object() return super().retrieve(request, *args, **kwargs) except: return Response({"message": "Instance doesnot exists"}, status=status.HTTP_404_NOT_FOUND) def partial_update(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) try: self.get_object() except: return Response({"message": "Instance doesnot exists"}, status=status.HTTP_404_NOT_FOUND) if serializer.is_valid(): if len(serializer.data.keys()) < 2: return Response({"message": "please provide somedata to update"}, status=status.HTTP_400_BAD_REQUEST) else: super().partial_update(request, *args, **kwargs) return Response({"message": "Data updated Successfully"}, status=status.HTTP_200_OK) else: return Response({"message": serilizer_validation(serializer)}, status=status.HTTP_400_BAD_REQUEST) def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({"message": "data created successfully"}, status=status.HTTP_201_CREATED) else: return Response({"message": serilizer_validation(serializer)}, status=status.HTTP_400_BAD_REQUEST) and following is the swagger auto schema code - … -
Django ORM aggregate tax sum
I have a Django project. There are Store model and Analytics model. I want to calculate taxes sum for each store. Is it possible to aggregate it by Django ORM in one request to DB? Without any loop by stores list? I don't want smth like this: for store in stores: taxes_sum = store.sales_sum*store.tax/100 I want smth like this: taxes_sum = StoreAnalytics.objects.filter(store__user=self.request.user).aggregate( sales_sum=Sum(F("accruals_sum"))*Sum(F("tax"))/100) but each store has its own tax percent (6%, 15%, 20%....) class Store(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) name = models.CharField(max_length=128, blank=True, default="", verbose_name="Name") class StoreAnalytics(models.Model): store = models.ForeignKey(Store, on_delete=models.CASCADE, null=True, related_name="store_id") sales_sum = models.DecimalField( max_digits=10, decimal_places=2, default=Decimal(0), verbose_name="Sales") tax = models.IntegerField( default=6, validators=[MaxValueValidator(20), MinValueValidator(0)], verbose_name="Tax %" ) Is there any methods to calculate taxes sum?