Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Gunicorn will only work as root user, else throws "ModuleNotFoundError"
Im working on a production server deployed on an AWS EC2 instance. The project is made with django, and its running on nginx + gunicorn After a few trials, I got everything working, however, when I added the --user nginx flag, the app stopped working. When run as a service, the service initialices properly, but then on any request it will throw an error 500. When run directly from command line, it does not even start. The command, which is the same on the gunicorn.service file as the one I run from cli is: /usr/local/bin/gunicorn --preload --user nginx --chdir /home/ec2-user/api/ project.wsgi:application --bind 0:8000 --workers=3 --timeout=120 --error-logfile /var/log/gunicorn/error.log --access-logfile /var/log/gunicorn/access.log --reload On either case, the stack traces as follows: [2023-04-14 20:35:19 +0000] [5429] [INFO] Worker exiting (pid: 5429) [2023-04-14 20:35:19 +0000] [5430] [INFO] Booting worker with pid: 5430 [2023-04-14 20:35:19 +0000] [5430] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/usr/local/lib/python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/usr/local/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/local/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/local/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/usr/local/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File … -
How to use assert in Python production source code?
We are looking at self-developed libraries shared between multiple Django projects or components of the same project, not the published open-source libraries. Question: We wonder whether it is OK to use assert to validate the variable's values. We didn't find online articles in this topic, so if yes, how do we do it? More information: An example of our idea: We are considering the example below that verifies the input logic equals to either and or or. And the design seems better than using a else clause assuming the value must be the other one. if logic == 'and': main_Q = main_Q & filter_Q elif logic == 'or': main_Q = main_Q | filter_Q else: assert False, "Invalid value of `logic`, it needs to be either `and` or `or`." Or: if logic == 'and': main_Q = main_Q & filter_Q else: assert logic == 'or' main_Q = main_Q | filter_Q We found usages of assert in the published open-source libraries. By doing a grep "assert" -v "test" to search in the site-packages directory, we found multiple assert statements in the functional source code, not for testing, in the libraries of amqp, argparse, billiard, celery, dateutil, decorator, distlib, etc. However, using assert seems … -
Accessing authorization header in django APIView
I have a Django APIView that requires authentication before the data can be fetched. The user token making the request is sent from a react front-end. The program works using a function view, but the returned data is formatted in a way I don't like. Something like [{"model":"product.product", "key":2, "fields":[{"name": "product one"} ... and so on]}] even including the model's name. For that reason, I reverted to using an APIView. Unfortunately, with APIView, it doesn't work at all, giving the error "Given token not valid for any token type". I'm convinced the problem is with the way I'm accessing the authorization header in the case of the APIView because if I remove the authorization part, the code works. That suggests to me that there must be a different way of accessing header information in APIView. May I ask: (1) If anyone has an idea of the right way to access the request header when using APIView. (2) The right response class to use in order to have a proper object like {id: 1, name:"product one", price: 100) etc returned in the case of a function view. By the way, I'm using the google firebase authentication mechanism. Below are the two … -
The endpoint is throwing me a KeyError when I try to update it
Pardon me, I'm developing an app using Django REST Framework and when I try to update an user this happen It throw me this error: centros = validated_data.pop('centros') KeyError: 'centros' I'll share my code: This is my model class Usuario(AbstractBaseUser): organizacion = models.CharField(verbose_name='Organización', blank=True, null=True, max_length=250) departamento = models.CharField(verbose_name='Departamento', blank=True, null=True, max_length=250) centros = models.ManyToManyField(Centro, verbose_name='Centro o Unidad', blank=True, related_name='centros_usuario') telefono = models.CharField(max_length=100, verbose_name='Teléfono', blank=True, null=True) rut = models.CharField(max_length=100, verbose_name='RUT', blank=True, null=True) profesion = models.CharField(max_length=150, verbose_name='Profesión', blank=True, null=True) cargo = models.CharField(max_length=150, verbose_name='Cargo', blank=True, null=True) nacionalidad = models.CharField(max_length=100, verbose_name='Nacionalidad', blank=True, null=True) sexo = models.CharField(max_length=10, choices=SEXO_CHOICES ,verbose_name='Sexo', blank=True, null=True) fecha_nacimiento = models.DateField(auto_now=False, auto_now_add=False,verbose_name='Fecha de nacimiento', blank=True, null=True) imagen_perfil = models.ImageField(upload_to='perfil/', verbose_name='Imágen de Perfil', max_length=255, blank=True, null=True) cv = models.FileField(verbose_name='CV', upload_to='cv_usuarios/', blank=True, null=True) direccion = models.CharField(max_length=250, blank=True, null=True, verbose_name='Dirección') perfil = models.PositiveSmallIntegerField( null=False, blank=False, default=2, choices=PERFIL_CHOICES, verbose_name='Perfil') is_active = models.BooleanField( verbose_name='active', default=True, help_text=( 'Designates whether this user shoud be treated as active. ' 'Unselect this instead of deleting accounts. ' ) ) estado = models.CharField(verbose_name='Estado usuario', default='INHABILITADO', choices=ESTADO_CHOICES, max_length=13) is_staff = models.BooleanField( verbose_name='staff status', default=False, help_text=( 'Designates whether the user can log into this admin site. ' ) ) is_superuser = models.BooleanField( verbose_name='superuser status', default=False, help_text=( 'Designates whether this user is a Superuser. … -
Django render() got an unexpected keyword argument 'renderer' - 2.1 issue
I updated my django version from 2.0 to 2.1 and keep getting this type error, from previous questions i know i need to add the renderer=None argument but I've tried it and there still seem to be issues. So my question is do i need to add renderer=None to the super call in my render function as well? For e.g. I have: class AdminThumbnailWidget(forms.ClearableFileInput): template_with_initial = '%(initial)s %(clear_template)s%(input_text)s: %(input)s' url_markup_template = '<a href="%(image_url)s" target="_blank"><img src="%(thumbnail_url)s"/></a>' template_with_clear = '<p class="image-input-clear">%(clear)s<label for="%(clear_checkbox_id)s">%(clear_checkbox_label)s</label></p>' def __init__(self, *args, **kwargs): self.thumbnail_width = kwargs.pop("thumbnail_width", 200) self.thumbnail_height = kwargs.pop("thumbnail_height", 200) super(AdminThumbnailWidget, self).__init__(*args, **kwargs) def render(self, name, value, attrs=None, renderer=None): substitutions = { 'initial_text': self.initial_text, 'input_text': self.input_text, 'clear_template': '', 'clear_checkbox_label': self.clear_checkbox_label, } template = '%(input)s' substitutions['input'] = super(FileInput, self).render(name, value, attrs) if value and hasattr(value, "url"): template = self.template_with_initial thumbnail_url = get_thumbnail(value, self.thumbnail_width, self.thumbnail_height, proc="crop", upscale=1, quality=95) url_data = { "image_url": value.url, "thumbnail_url": thumbnail_url } substitutions['initial'] = self.url_markup_template % url_data if not self.is_required: checkbox_name = self.clear_checkbox_name(name) checkbox_id = self.clear_checkbox_id(checkbox_name) substitutions['clear_checkbox_name'] = conditional_escape(checkbox_name) substitutions['clear_checkbox_id'] = conditional_escape(checkbox_id) substitutions['clear'] = CheckboxInput().render(checkbox_name, False,attrs={'id': checkbox_id}) substitutions['clear_template'] = self.template_with_clear % substitutions return mark_safe(template % substitutions) -
Django formset only saving initial formset. JS not updating values when adding new formsets
As the title says, whenever I fill out a form and then fill out the formset, if I add more than the initial formset, nothing is saved but the form and the initial formset. When I inspect the <td> elements while I select the add-empty-travel-form plus-circle button, the values of the <td>'s are not being incremented. I'll show the code to hopefully paint the picture. MODELS - Itinerary points to TravelRequest class TravelRequest(models.Model): name = models.CharField(max_length=255, blank=False) docs = models.BooleanField(blank=True, null=False) instructions = models.TextField(max_length = 2000, blank=True, null=True) date_created = models.DateTimeField("Date created",auto_now_add=True) date_updated = models.DateTimeField("Date updated",auto_now_add=True) created_by = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True) class TravelFile(models.Model): travel = models.ForeignKey(TravelRequest, on_delete=models.CASCADE) file = models.FileField( upload_to='documents/travel', blank=True, null=True) @property def file_name(self): url = self.file.url file_name = str(url).replace("/media/documents/travel/", "") return file_name def __str__(self): return self.file.url class Itinerary(models.Model): air = models.BooleanField(default=False, blank=True) car = models.BooleanField(default=False, blank=True) hotel = models.BooleanField(default=False, blank=True) dp= models.CharField(max_length=255, blank=False) dst = models.CharField(max_length=255, blank=False) doa = models.DateTimeField() dod = models.DateTimeField() travel_req = models.ForeignKey(TravelRequest, blank=True, null=True, on_delete=models.SET_NULL, related_name='travel_req') VIEWS - all the necessary imports are included def travel_request_create(request): form = TravelRequestForm(data=request.POST or None, files=request.FILES or None) ItineraryFormSet = formset_factory(ItineraryForm, extra=1) travel_formset = ItineraryFormSet(data=request.POST or None, prefix='travel') if request.method == 'POST': if 'travel-TOTAL_FORMS' in request.POST: … -
Django manage.py ModuleNotFoundError with Pants
First time poster, so let me know if I need to provide more info! I have a Django project of the following structure: a/b/c/d/ ├── e │ ├── BUILD.pants │ ├── myapp │ │ ├── BUILD.pants │ │ ├── migrations │ │ ├── models.py │ │ ├── ... │ │ └── tests │ ├── BUILD.pants │ ├── settings.py │ ├── ... │ └── wsgi.py ├── BUILD.pants ├── ... └── manage.py The Django app can be run using manage.py runserver perfectly fine, but it uses relative and app-level imports which causes Pants and Pyright issues within my repo. I want to set it up on Pants anyways, so I have switched all my relative imports to absolute imports (which breaks it running via Django directly). This is my BUILD.pants at a/b/c/d: python_sources() pex_binary( name="manage", entry_point="manage.py", dependencies=["a/b/c/d/e"], restartable=True, ) Running manage.py through Pants, instead of starting the app, produces the following: ./pants run a/b/c/d:manage -- runserver --noreload Traceback (most recent call last): File "/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main return _run_code(code, main_globals, None, File "/usr/lib/python3.8/runpy.py", line 87, in _run_code exec(code, run_globals) File "/home/artificialask/.pex/unzipped_pexes/900cb0387e270fc2eadde5a3883453a34b9a796e/__main__.py", line 103, in <module> bootstrap_pex(__entry_point__, execute=__execute__, venv_dir=__venv_dir__) File "/home/artificialask/.pex/unzipped_pexes/900cb0387e270fc2eadde5a3883453a34b9a796e/.bootstrap/pex/pex_bootstrapper.py", line 599, in bootstrap_pex pex.PEX(entry_point).execute() File "/home/artificialask/.pex/unzipped_pexes/900cb0387e270fc2eadde5a3883453a34b9a796e/.bootstrap/pex/pex.py", line 551, in execute … -
Multiply table td's by amount in input with ability to keep using the original value
I have a drinks recipe tool I'm making in Django. I would like the ability to calculate the needed ingredients per serve. For this I have made an input that allows for numbers. I now want to multiply the ingredient amounts with the selected amount of servings. Can I store the original value somehow and alway use that? What would be a good way to approach this? My html looks like this: <table class='cocktail_ingredients my-5'> <tr> <th> <h2> INGREDIENTS </h2> </th> <th> <h2> ML </h2> </th> </tr> {% for ingredient in drink.get_ingredients %} <tr> <td> {% if ingredient.ingredient_rum %} {{ingredient.ingredient_rum}} {% else %} {{ingredient.ingredient_name}} {% endif %}</td> <td id='amount'> {{ingredient.ingredient_amount}}</td> </tr> {% endfor %} </table> The JS & JQuery i wrote looks like this. I have no experience with JQuery so far so I hope it makes sense what I've done so far. $(document).ready(function() { var serveAmount = document.getElementById('serves'); serveAmount.addEventListener('keyup', function() { if (!$('#serves').val()) { return false; } else { $('.amount').each( function() { var amount = parseInt($(this).text()); var serves = $('#serves').val(); new_amount = amount * serves $(this).text($(this).text().replace($(this).text(), new_amount)) }); }; }); }); edit: rendered HTML: <table class='cocktail_ingredients my-5'> <tr> <th> <h2> INGREDIENTS </h2> </th> <th> <h2> ML </h2> </th> </tr> … -
how to show selected popup in django template
I've Created one table with datatables and used django template for getting data. At the last column of table I've added information icon and added popover on hover. I'm getting the different data in console. because the popover content div(id=showContent) I've created in HTML. Here is HTML Code: <div class="col-md-12 grid-margin"> <div class="card"> <div class="card-body"> <div class="table-responsive"> <table class="table dataTable" id="fuelData"> <thead class="thead-light"> <tr> <th>OPCO</th> <th>Country</th> <th>Region</th> <th>Currency</th> <th>Business Segment</th> <th>UOM</th> </tr> </thead> <tbody> {% for d in UOM%} {% for i in d%} <tr> <td> {{i.opco_name}}</td> <td> {{i.region_id__name}}</td> <td> {{i.region_id__country__name}}</td> <td> {{i.currency_id__name}}</td> <td> {{i.business_segment__name}}</td> <td><i class="fa fa-info-circle" data-toggle="popover"></i> <div id="showContent" style="display: none;" hidden><b>Fuel Unit: </b>{{i.fuel_unit}}, <br/> Weight Unit: {{i.weight_unit}},<br/> Volume Unit: {{i.volume_unit}},<br/> Distance Unit: {{i.distance_unit}}</div> </td> </tr> {% endfor %} {% endfor %} </tbody> </table> </div> </div> </div> </div> And I am Showing that div in popover content by javascript. Here is Javascript Code: $(document).ready(function(){ $('[data-toggle="popover"]').popover( { trigger: "hover" , placement: 'top', title: 'Unit Of Measurements', content: $("#showContent").show(), } ); }); but its showing only first row popover data in all rows popover. I want to show different data on every popover. How can I show the particular row data on the icon hover? Thanks In Advance!! -
Heroku dynos H12, all requests timing out
Dynos completely fail (timeouts) every other day Hi all, I've been having this issue with Heroku for months now. I have a python/django app, using the 2X dynos (2 of them). I have 8 workers per dyno Every other day, there will be a huge spike in the response times and it will last for 30 mins to a few hours. All web requests will fail (503s) and Heroku will just tell me its an H12 (request timeout). On normal times, my p95 for requests are under a second and theres no spikes. Heres what I've tried: Autoscaling dynos with Judoscale Provisioning a new/faster database Finding out what queries are slow and optimizing them Restarting dynos when this happens Nothing seems to work. Most of the time it just goes away after a while, other times i have to shut the entire app down for a while and restart it. I havent noticed any change in traffic to the website either. The number of users stays consistent every day. On times where there is a spike of user activity, the dynos are actually fine. I have tried everything on my side and I'm starting to suspect this is a heroku-specific … -
django if value equals enum show field
For my django project I try to show a button if a field is equal to an enum value. I loop over lights and based on the state I want to show a button. My enum: class DeviceState(Enum): UNKNOWN = 1 STAND_BY = 2 ON = 3 OFF = 4 My light: class Light: def __init__(self, id, name, state: DeviceState = DeviceState.UNKNOWN): self.id = id self.name = name self.state: DeviceState = state My relevant template part: {% for light in lights %} <tr> <td>{{ light.name }}</td> <td>{{ light.state }}</td> <td> {% if light.state == 3 %} <button type="button" class="btn btn-dark">Lights off</button>< {% endif %} {% if light.state == "DeviceState.OFF" %} <button type="button" class="btn btn-success">Lights on</button> {% endif %} </td> </tr> {% endfor %} I tried multiple variations of: {% if light.state == 3 %} e.g. == "3" == DeviceState.OFF == 3 == "DeviceState.OFF" == "OFF" Of which none seem to work. How should I hide/show elements if a properties value equals a specific enum value? note ( i know I can use en elif instead of two else, but just for testing im trying to focus on getting one working. -
Django inline data save but i use for loop that way data overwrite save what to do?
Django inline data save overwrite MCX i tried to save multiple data. This is my main model (parent model) class DebitClient(SysFields): debit_client_id = models.CharField(max_length=50, primary_key=True, db_column='DEBIT_CLIENT_ID', verbose_name='Debit Client Id') from_date = models.DateField(db_column="FROM_DATE", verbose_name="From Date") i use here save method def save(self, force_insert=False, force_update=False): if not self.debit_client_id: formatted_date = self.from_date.strftime('%d%m%Y') self.debit_client_id = f'BB{formatted_date}' super(DebitClient, self).save(force_insert, force_update) from AtsERP.atserp_base.atserp_models.atserp_basemodels.atserp_accounting_models.basemodel_ledger.atserp_bm_client_ledger import \ ClientLedgerTransactionDetailed from AtsERP.atserp_base.atserp_models.atserp_basemodels.atserp_settings_models.basemodel_organization.ats_bm_organization import \ Organization from django.db.models.functions import Coalesce net_debit_client_date = ClientLedgerTransactionDetailed.objects.filter( fin_year=FinancialYear.objects.get(status='Active')).filter(ledger__ledger_id__in=[10795, "AC031", "A0001"]).values('trade_date').first() start_date = net_debit_client_date['trade_date'] print(start_date, "start date") start_obj_date_debit = \ ClientLedgerTransactionDetailed.objects.filter( Q(ledger__ledger_id__in=[10795, "AC031", "A0001"]) & (Q(trade_date__lte=self.from_date) | \ Q(trade_date__isnull=True)) & Q( fin_year=FinancialYear.objects.get(status='Active'))).aggregate( debit_sum=Coalesce(Sum('posted_debits'), 0) )['debit_sum'] start_obj_date_credit = ClientLedgerTransactionDetailed.objects.filter( Q(ledger__ledger_id__in=[ "AC031", "A0001", 10795]) & (Q(trade_date__lte=self.from_date) | \ Q(trade_date__isnull=True)) & Q( fin_year=FinancialYear.objects.get(status='Active'))).aggregate( credit_sum=Coalesce(Sum('posted_credits'), 0) )['credit_sum'] start_obj_date_debit_cd_nse = ClientLedgerTransactionDetailed.objects.filter( Q(ledger__ledger_id__in=[10795, "AC031", "A0001"]) & (Q(trade_date__lte=self.from_date) | \ Q(trade_date__isnull=True)) & Q( fin_year=FinancialYear.objects.get(status='Active')) & Q(org_unit='CD_NSE')).aggregate( debit_sum=Coalesce(Sum('posted_debits'), 0) )['debit_sum'] start_obj_date_credit_cd_nse = ClientLedgerTransactionDetailed.objects.filter( Q(ledger__ledger_id__in=[10795, "AC031", "A0001"]) & (Q(trade_date__lte=self.from_date) | \ Q(trade_date__isnull=True)) & Q( fin_year=FinancialYear.objects.get(status='Active'), org_unit='CD_NSE')).aggregate( credit_sum=Coalesce(Sum('posted_credits'), 0) )['credit_sum'] total_cd_nse = start_obj_date_credit_cd_nse - start_obj_date_debit_cd_nse if start_obj_date_debit_cd_nse is None: start_obj_date_debit_cd_nse = 0 print(start_obj_date_debit_cd_nse, "start_obj_date_debit_cd_nse") if start_obj_date_debit is None: start_obj_date_debit = 0 if start_obj_date_credit is None: start_obj_date_credit = 0 net_closing_balance = start_obj_date_credit - start_obj_date_debit print(start_obj_date_debit, "posted_debits") print(start_obj_date_credit, "posted_credits") print(net_closing_balance) target_date = self.from_date obj = ClientLedgerTransactionDetailed.objects.filter( Q(trade_date=target_date) | … -
upload multiple books to database automatically
I am working on a project that allows me to upload multiple books to database using django. For testing purposes and i order to save time, i want to automatically upload multiple books to database. Here is the code that helps me achieve that import random import string import httplib2 from urllib.parse import urlencode base_url = "http://localhost:8002/addbook/" def generate_data(): """ Generate a dictionary of random book data. """ data = {} data["title"] = "".join(random.choices(string.ascii_uppercase, k=8)) data["author_name"] = "".join(random.choices(string.ascii_uppercase, k=8)) data["coauthors_name"] = "".join( random.choices(string.ascii_uppercase, k=8)) data["publisher_name"] = "".join( random.choices(string.ascii_uppercase, k=8)) data["isbn"] = "".join(random.choices(string.digits, k=13)) data["genres_name"] = "".join(random.choices(string.ascii_uppercase, k=8)) data["edition"] = "".join(random.choices(string.ascii_uppercase, k=8)) data["description"] = "".join(random.choices(string.ascii_uppercase, k=50)) data["book_file"] = "/home/dubsy/A Guide to Broiler Chicken Growth Boosters & Probiotics.pdf" return data # Send a GET request to the book upload page to get the CSRF token http = httplib2.Http() response, content = http.request(base_url, "GET") csrf_token = response["set-cookie"].split("=")[1].split(";")[0] # Generate and send POST requests to upload 100 books for i in range(100): data = generate_data() data_encoded = urlencode(data).encode("utf-8") headers = { "Content-Type": "application/x-www-form-urlencoded", "Cookie": f"csrftoken={csrf_token}", "Referer": base_url, "X-CSRFToken": csrf_token, } response, content = http.request( base_url, "POST", body=data_encoded, headers=headers ) print(f"Response {i+1}: {response}") print(content.decode('utf-8')) When i run this above code in terminal, here are the … -
select_for_update doesn't prevent race conditions in PostgreSQL, while F expression does
I have a business model: from django.db import models from django.db.models import F from django.template.defaultfilters import slugify from rest_framework import status from rest_framework.response import Response from business.models.abstract import Entity from business.models.credit_history import CreditHistory class Business(Entity): title = models.CharField(max_length=160) slug = models.SlugField(max_length=120, unique=True) credit = models.PositiveBigIntegerField(default=0) def __str__(self): return f"{self.slug} - {self.title} - {self.credit}" def save(self, *args, **kwargs): if not self.id: self.slug = self.slug or slugify(self.title) return super().save(*args, **kwargs) def increase_credit(self, phone, amount): try: amount = int(amount) except ValueError: return Response({"message": "Amount must be a positive integer"}, status.HTTP_400_BAD_REQUEST) if amount <= 0: return Response({"message": "Amount must be a positive integer."}, status=status.HTTP_400_BAD_REQUEST) if amount > self.credit: return Response({"message": "Business doesn't have enough credit."}, status=status.HTTP_400_BAD_REQUEST) # self.credit = F("credit") - amount self.credit -= amount self.save() CreditHistory.objects.create( chargor=self.slug, chargee=phone, amount=amount, ) return Response({"message": "Successfully charged user."}, status.HTTP_200_OK) And then I wrote a test to check for race conditions: from django.test import TransactionTestCase from rest_framework.test import APIClient from business.models.business import Business from business.tests.increase_credit import IncreaseCredit import before_after class TestCreditHistory(TransactionTestCase): def setUp(self): self.client = APIClient() self.business1 = Business.objects.create( title="business 1", ) self.business2 = Business.objects.create( title="business 2", ) self.business3 = Business.objects.create( title="business 3", ) self.businesses = [self.business1, self.business2, self.business3] def test_total_charged_for_race_condition(self): obj = IncreaseCredit(1_000_000) def after_function(self, *args, … -
How create a model in Django with 3 default fields?
Please help me. I have the task of creating a model in Django with 3 default fields. The model looks simple enough: class TasksStatus(models.Model): status = models.CharField(max_length=255) You must initially add 3 statuses - new, in progress, and completed. So that when you create related models, you can choose from these 3 statuses. Can you tell me how to add 3 rows to the table at the time of model creation? -
Django Rest Framework Excel File Upload
Note: Please read the whole question before marking it as duplicate. Django has changed ALOT Since a couple of years. I have already tried all the solutions and read Django Rest Framework Documentation on: FileUploadPasrer https://www.django-rest-framework.org/api-guide/parsers/#fileuploadparser MultiPartParser https://www.django-rest-framework.org/api-guide/parsers/#multipartparser. None of the ways work. I also tried uploading using simple Django but that didnt seem to work Either. The Error I am getting is that request.FILES['file'] is always an empty {}. Write now my code looks like this parser_classes = [MultiPartParser] def put(self, request, format=None): file_obj1 = request.data['file'] data = json.loads(request.POST['form']) print(file_obj1) return Response(status=status.HTTP_201_CREATED) Like i said I always tried Using FileUploadParser. Same code just replaced MultiPartParser with FileUploadParser. I am using Postman to send an excel file and then reading it. Anyone who has recently upload an excel file in Django Rest Framework can guide me but make sure your code works becuase I have already spent a day and still can't find the solution so far. Edit: Curl Request from Postman would be: curl --location 'http://localhost:8000/amm-api/upload/upload_workbook/' \ --form '=@"/Users/razan/Projects/HTS/ags-carmax/Robbie_Lisa-Branch.xlsx"' This is how it looks in Postman -
i'm having django bug
in my project i need to build a function that send email to the trip owner depending on the button clicked accept or refuse: here is my views code : from django.shortcuts import render from .models import Guide,Trip from django.core.mail import EmailMessage from django.conf import settings def accept(request): trips = Trip.objects.all() z = {'aw': trips} if request.method == 'POST': for i, trip in enumerate(trips): trip_id = request.POST.get('trip_id_{}'.format(i)) #send email to the trip_id owner print("trip_id =", trip_id) if 'accept_{}'.format(i+1) in request.POST: email_msg = EmailMessage( 'Trip accepted', 'Hi there! Your trip has been accepted.', settings.EMAIL_HOST_USER, [trip.owner_email], ) email_msg.fail_silently = True email_msg.send() elif 'refuse_{}'.format(i+1) in request.POST: email_msg = EmailMessage( 'Trip refused', 'Hi there! Your trip has been refused.', settings.EMAIL_HOST_USER, [trip.owner_email], ) email_msg.fail_silently = True email_msg.send() return render(request, 'system/accept.html', z) here is my template code : {% block content %} {% for x in aw %} {{x.owner}} {{x.owner_email}} <form method="post" action="{% url 'accept' %}"> {% csrf_token %} <input type="hidden" name="trip_id_{{ forloop.counter }}" value="{{ x.id }}"> <br> <input type="submit" name="accept_{{ forloop.counter }}" value="accept"> <input type="submit" name="refuse_{{ forloop.counter }}" value="refuse"> </form> {% endfor %} {% endblock content %} my web page looks like this enter image description here but when i press accept button to send … -
Multi-database in django: Tables not dumped
I'm trying to demonstrate the use of multi-database in Django using db routers but facing issues dumping data into respective databases. The django models are visible in both databases, but not my own created ones. Here is my models.py file: from django.db import models from django.db import models from django.contrib.auth.models import User from peewee import * import psycopg2 # Create your models here. class temp(models.Model): id= models.IntegerField(primary_key=True) class Meta: app_label='client_db' db_table='temp' class temp2(models.Model): id= models.IntegerField(primary_key=True) class Meta: app_label='default' db_table='temp2' settings.py DATABASE_ROUTERS = ('app_celery.dbrouter.client_router', ) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } , 'client_db': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'amm', 'USER': 'xxxx', 'PASSWORD': 'xxxx', 'HOST': '127.0.0.1', 'PORT': 5432, }, } dbrouter.py class client_router: """ A router to control all database operations on models in the user application. """ def db_for_read(self, model, **hints): """ Attempts to read user models go to users_db. """ if model._meta.app_label == 'client_db': return 'client_db' return 'default' def db_for_write(self, model, **hints): """ Attempts to write user models go to users_db. """ if model._meta.app_label == 'client_db': return 'client_db' return 'default' def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the user app is involved. """ if obj1._meta.app_label == 'client_db' or \ obj2._meta.app_label … -
Javascript not loading in my Django + React Project with Vite.js
So I had created a project with React as frontend and Django as it backend. For the backend and frontend two separate folders were created : backend and frontends (ignore the spelling mistake it was intentional). I created a react project using vite.js and also created a build production by using the npm run build command. I then linked the dist folder which was generated to django through settings.py along with all other configurations needed for linking static files and stuff, editing views.py as well as urls.py. Below is the syntax for my STATICFILES_DIRS STATIC_URL = '/assets/' STATICFILES_DIRS = (os.path.join(REAL_BASE_DIR,'frontends', 'dist', 'assets'),) Also the directory tree of my project : screenshot So when I start the django server the static files successfully load (like the javascript and the .css) and its show 200 Success CODE and no 404 but in the console of my browser the following error shows up particularly for the Javascript file (not the css). error image The CSS file loads successfully with no errors but the Javascript file shows the above error and I can't find any possible solution on how to fix it. Expecting the JavaScript file to load since there were no 404 Not … -
Websocket connection to failed on production host but it is fine in localhost django
I implemented websocket connection for live ubdation in by django application . The problem is it works in localhost but when i host the same application in public host server it not connecting .i used to host Daphne server droping my code down below myjavascript.js let urls=`ws://${window.location.host}/ws/socket-server/` const Wsocket=new WebSocket(urls) Wsocket.onmessage=function (e) { let data=JSON.parse(e.data) console.log(data) } consumer.py # consumer.py class SocketConsumer(WebsocketConsumer): def connect(self): self.accept() self.room_group_name='test' async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.send(text_data=json.dumps({ 'type':'connection_established', 'message':'you are noew connected' })) #routnig.py websocket_urlpatterns=[ re_path(r'ws/socket-server',consumers.SocketConsumer.as_asgi()) ] #asgi.py application = ProtocolTypeRouter( { "http": get_asgi_application(), 'websocket':AuthMiddlewareStack( URLRouter( App.routing.websocket_urlpatterns ) ) # Just HTTP for now. (We can add other protocols later.) } ) I used channels settings.py CHANNEL_LAYERS = { 'default': { 'BACKEND': "channels.layers.InMemoryChannelLayer" } } and i run my application command daphne myproject.asgi:application help me legends -
What is the expected way to set `filterset_fields` in Django-Filter and Django REST Framework?
When I set the fiterset_fields like below, class SubCategoryViewSet(viewsets.ReadOnlyModelViewSet): filter_backends = [DjangoFilterBackend] filterset_fields = ["category_id"] # single underscore I get this response when a category with the specified ID doesn't exist { "category_id": [ "Select a valid choice. That choice is not one of the available choices." ] } But when I set it like class SubCategoryViewSet(viewsets.ReadOnlyModelViewSet): filter_backends = [DjangoFilterBackend] filterset_fields = ["category__id"] # notice the double underscore I get a [] when a category with the specified ID doesn't exist. Why does this happen? What is the right way to do this? -
Heroku Django app with AWS OpenSearch (anonymous user is not authorized issue)
I used to have an ElasticSearch Service instance (t2.micro.search) set up to enable a search functionality for an app hosted on Heroku. That old setup was working fine. I now tried to set up a new instance (t3.small.search) using the same settings as the previous one. However, when I tried to build the index from Heroku, I got this error: TransportError(403, '{"Message":"User: anonymous is not authorized to perform: es:ESHttpPost with an explicit deny in a resource-based policy"}' I realized my access policy has "Deny" instead of "Allow" I had before: { "Version": "2012-10-17", "Statement": [ { "Effect": "Deny", "Principal": { "AWS": "*" }, "Action": "es:*", "Resource": "arn:aws:es:us-east-1:000000000000:domain/my-domain/*" } ] } I tried to change it to "Allow" but the console would not allow me to save the settings ("Apply a restrictive access policy to your domain"). Does somebody know how to set up the access policy so I can continue to use AWS OpenSearch for a Heroku app? -
wagtail on-publish custom sucess message
I have a question regarding the success message wagtail is displaying when an editor is publishing a page in the admin interface. It's usually "Page {Page.title} has been published". I’am trying to figure out how to add one’s own success or error message on-publishing resp. an error occuring. For a Page in my project I have implemented the below receiver that gets activated if the editor uploads in a certain field a file and publishes the site. This file is then processed by a script, though the file itself is not saved. For the editors, I would like to have a custom success message displayed below the default on-publish success message if they uploaded the file successfully, tough only if the pages is published after uplaoding a file. I found the question linked below, I could figure out how to show a custom message but it is not a very satisfying solution. The wagtail version, I'am using is 4.22 customize-post-publish-flash-message-in-wagtail-cms @receiver(page_published, sender=Model) def process_uploaded_file(sender, instance, **kwargs): if instance.uploaded_file: process_data(instance.uploaded_file.path) instance.uploaded_file.delete(save=False) instance.uploaded_file = None instance.date = (date.today()) instance.save() I took the hook from the answer in the question linked above and changed it a bit. If one of the pages of … -
Django: AttributeError - ‘bytes’ object has no attribute ‘amount’
I got back this response from an api call b'response=1&responseMessage=APPROVED&noticeMessage=New+Card+Stored+-+New+Customer+Created+-+New+Order+Created+-+Order+Marked+as+Paid&date=2023-04-14&time=09%3A00%3A57&type=purchase&amount=100.00&cardHolderName=Sammy&cardNumber=5413+++9130&cardExpiry=0125&cardToken=0eaf06f7a255b5f0f7703f&cardType=Mastercard&transactionId=36341061&avsResponse=X&cvvResponse=M&approvalCode=T4E6ST&orderNumber=INV001007&customerCode=CST1007&currency=USD&xmlHash=10d7b700eb6d291b19368a437dd19709fcadb6da36879f078a9ad4548986101a&xml=%3Cmessage%3E%3Cresponse%3E1%3C%2Fresponse%3E%3CresponseMessage%3EAPPROVED%3C%2FresponseMessage%3E%3CnoticeMessage%3ENew+Card+Stored+-+New+Customer+Created+-+New+Order+Created+-+Order+Marked+as+Paid%3C%2FnoticeMessage%3E%3Cdate%3E2023-04-14%3C%2Fdate%3E%3Ctime%3E09%3A00%3A57%3C%2Ftime%3E%3Ctype%3Epurchase%3C%2Ftype%3E%3Camount%3E100.00%3C%2Famount%3E%3Ccurrency%3EUSD%3C%2Fcurrency%3E%3CcardHolderName%3ESammy%3C%2FcardHolderName%3E%3CcardNumber%3E5413+++9130%3C%2FcardNumber%3E%3CcardExpiry%3E0125%3C%2FcardExpiry%3E%3CcardToken%3E0eaf06f7a255b5f0f7703f%3C%2FcardToken%3E%3CcardType%3EMastercard%3C%2FcardType%3E%3CtransactionId%3E36341061%3C%2FtransactionId%3E%3CavsResponse%3EX%3C%2FavsResponse%3E%3CcvvResponse%3EM%3C%2FcvvResponse%3E%3CapprovalCode%3ET4E6ST%3C%2FapprovalCode%3E%3CorderNumber%3EINV001007%3C%2ForderNumber%3E%3CcustomerCode%3ECST1007%3C%2FcustomerCode%3E%3CincludeXML%3E1%3C%2FincludeXML%3E%3C%2Fmessage%3E' I am trying to get some attribute/value from the response, i don't know if that would be possible since this is not a json response, this is how i am trying to get the reponse def process_endpoint(request): data = request.body.amount print(data) context = { 'response':data } return render(request, "payments/response.html", context) but i keep getting this error that says AttributeError: 'bytes' object has no attribute 'amount' whenever i include json_data = request.body.amount. Firstly, can i convert this response that i got to a json response? I tried doing that but got an error that says JSONDecodeError at /process_endpoint/ Expecting value: line 1 column 1 (char 0) this is the code i used import json json_data = json.loads(request.body.decode(encoding='UTF-8')) Secondly, can i get some specific attributes/value from the response?, e.g amount, date, payment_type etc -
How to create Django model for data with multiple images
I basically want to create a multivalued attribute called images. I created a model called CseDepartment with attributes: title, description, updated and created. Then i created another model called NewsImage with attributes: cseDepartment (foreign key), images, created and updated. But while running the code i get error saying CseDepartment has no attribut called newsImage_set. how to fix this issue? each news or data in CseDepartment can have multiple images how can i make this work? Error shown when accessing template This is what I tried: views.py: def cse_dept(request): dept = CseDepartment.objects.all() context = { 'dept' : dept} return render(request, 'website/cse_dept.html', context) def cse_news(request, pk): cseDepartment = CseDepartment.objects.get(id=pk) images = cseDepartment.newsImage_set.all().order_by('-created') context = {'news' : cseDepartment, 'newsImages' : images} return render(request, 'website/cse_news.html', context) models.py: class CseDepartment(models.Model): title = models.CharField(max_length=200) image = models.CharField(max_length=300) description = models.TextField() updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-updated', '-created'] def __str__(self): return self.title class NewsImage(models.Model): cseDepartment = models.ForeignKey(CseDepartment, on_delete=models.CASCADE) image = models.CharField(max_length=300) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.image[0:50] urls.py path('cse_dept/', views.cse_dept, name="d-cse"), path('cse_news/<str:pk>/', views.cse_news, name="news"), template <h3>{{news.title}}</h3> {% for pic in newsImages %} <img src="{{pic.image}}" alt=""> {% endfor %} I want this template to display all the images relating …