Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django S3 private storage
Users in my django project can upload pdf files to a private storage. It is done using django-private-storage package - when user makes a request to get a file, django checks permissions on that and then adds x-sendfile header so apache would serve the file. Now I am trying to move all that to S3 storage. I can't seem to understand how to do that. Most info that I found on the internet is telling me to put private files in a private bucket and then serve expiring links. I don't like the expiring links and I don't want to expose any S3 links. One-shot links would be fine, maybe. Is there any way to serve files without exposing any direct S3 links and without using expiring links? Am I missing something? -
How to save separated values from a list of numbers
i want to recibe a list of values(numbers in this case) in a key called "sensor_data" and save those values separated but i couldnt figureout how to make this function without using another framework. @api_view(['POST']) def saveData(request): values_list = [] separated_values = values_list.split(',') sensor_data = {'sensor_data' : values_list } print (sensor_data) return Response() -
How to get last six month report django (even in between months not having entry)
I wanted to get last six months of employee count by checking joining_date field class Employee(models.Model): employee_name = models.CharField(max_length=100) joining_Date = models.DateField(blank=False, null=False) Example: July : 12, June : 10, May : 8, April : 16, March : 13, February : 10, I got an answer for that from 0svoid, check here Its really working great! but problem is when there is no entry in particular month I want it to be 0 instead of not coming in the list. Say for example june month not having any employee joining. it should show like July : 12, June : 0, May : 8, April : 16, March : 13, February : 10, instead of below one. July : 12, May : 8, April : 16, March : 13, February : 10, I want to work on many scenario(s) something like above , please suggest me any module or a way to generate reports to show in the template from the database(s).. -
Django and AmqpConsumer with another apps
I have django apps and amqp consumer/publisher. I want to send an incoming message to my function in another application. But I get error messange: 'django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.' how can I do this? My settings.INSTALLED_APPS: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'my_app', 'rabbit_client.config.AmqpConfig' ] AmqpConfig: from django.apps import AppConfig from rabbit_client.amqp_client import AMQPConsuming class AmqpConfig(AppConfig): name = 'rabbit_client' def ready(self): consumer = AMQPConsuming() consumer.daemon = True consumer.start() AMQPConsuming: import threading import pika from django.conf import settings from my_app.util import my_function # it's call error messange class AMQPConsuming(threading.Thread): def callback(self, channel, method, properties, body): data = body my_function(data) @staticmethod def _get_connection(): parameters = pika.URLParameters(settings.RABBITMQ_SETTING['URL']) return pika.BlockingConnection(parameters) def run(self): connection = self._get_connection() channel = connection.channel() channel.queue_declare( queue=settings.RABBITMQ_SETTING['QUEUE_CONSUME'], durable=True ) channel.basic_qos(prefetch_count=1) channel.basic_consume( on_message_callback=self.callback, queue=settings.RABBITMQ_SETTING['QUEUE_CONSUME'] ) channel.start_consuming() -
POST and models not matching - causing MultiValueDictKeyError
I inserted new model fields into my existing model in Django yesterday. This is how it looks: Then I ran these two commands- python manage.py makemigrations python manage.py migrate In my views.py I try to get from the post request all the added fields, but it gives me this error: When I look into the POST itself I see that none of my new fields were added! I understand that the fields are non-exsistent in the new request.POST, so the error pops in this part of the code: def updaterecord(request, id): group_name = request.POST['group'] sale_rent = request.POST['sale_rent'] street = request.POST['street'] city = request.POST['city'] rooms = request.POST['rooms'] size = request.POST['size'] floor = request.POST['floor'] porch = request.POST['porch'] storage = request.POST['storage'] mamad = request.POST['mamad'] elevator = request.POST['elevator'] parking = request.POST['parking'] price= request.POST['price'] phone= request.POST['phone'] date = request.POST['user_date'] I just don't understand how to solve this, is there any updates or commands I need to make? I don't remember how I solved it last time or how to avoid it in the future. Help please :-) -
Huey running task multiple times
I have a Huey task on a Django app that sends emails. The task runs every morning at 9am and is meant to send an email to certain customers. The task runs successfully, but runs again and again rather than just once, sending about 20 emails to each customer. @db_periodic_task(crontab(hour='9')) @lock_task('task-lock') def email_task(): emails_to_send = Customer.objects.filter(email_to_send=True) for customer in emails_to_send: send_email(customer) mark_email_to_send_false(customer) return True I've added a bool flag to the query and tried locking the task, but it keeps running multiple times. How do I make it just run once? -
Django project file is not showing
I created a my world project file in django and it’s not visible in the server. The response I get from my terminal is [Errno2 ] no such file or directory -
How to add html data attribute in django charfield?
I have following code in model password = models.CharField( max_length=32, null=True, blank=True, verbose_name="Code for downloaded Zip" ) I'm using admin to modify data, I want to add data-lpignore="true" attribute when django-admin displays form. I have added following code when I register model to admin which does not seems to work formfield_overrides = { models.CharField: {"widget": forms.TextInput(attrs={"data-lpignore": "True"})}, } Any ideas about how to add this data attribute in my model itself? -
what the meaning of : "Symbol not found: ____chkstk_darwin"?
I have the message below when I run my server : Symbol not found: ____chkstk_darwin I want to connect postgresql with django but it seems it doesn't work with this problem mentionned before ^^' this is the response of the shell when I am trying to run my server : raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: dlopen(/Users/Nicolas/Desktop/OC/Python/Projets/P8_purbeurre/venv/lib/python3.7/site-packages/psycopg2/_psycopg.cpython-37m-darwin.so, 2): Symbol not found: ____chkstk_darwin Referenced from: /Users/Nicolas/Desktop/OC/Python/Projets/P8_purbeurre/venv/lib/python3.7/site-packages/psycopg2/.dylibs/libcrypto.1.1.dylib (which was built for Mac OS X 10.15) Expected in: /usr/lib/libSystem.B.dylib in /Users/Nicolas/Desktop/OC/Python/Projets/P8_purbeurre/venv/lib/python3.7/site-packages/psycopg2/.dylibs/libcrypto.1.1.dylib I need some help please ! SN -
Django Raw SQL relation does not exists
I am trying to execute raw sql but it requires a relation and I am not really sure where and why it doesnt work as it should. Settings.py 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'Primary', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'host', 'PORT': '5433', }, 'DataDB': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'SpecialDataDB', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'host', 'PORT': '5433', } } getData.py if request.GET['data'] == True: with connections['DataDB'].cursor() as cursor: cursor.execute("Select i from Test") row = cursor.fetchone() return cursor return None I have no problem connecting to first database and use my user to authenticate, then I am trying to grab data from 2nd database (that should be read only) and I get error: relation "test" does not exist LINE 1: Select i from Test 2nd Database is only for read, why not DBRouter? I've created it before and it didnt work as intended. All I want to do now is get that raw data and return it to the view. On the other hand I can create table using raw query. cursor.execute("CREATE TABLE IF NOT EXISTS test (i integer)") ^ that works How should I write select query to get the data without creating a model or how to create the … -
Add single extra field in a paginated response in drf
I've a monthly quiz website. The quiz attempt model is something like this: class UserAttempts(models.Model): user = FK(User) quiz = FK(Quiz) answer = FK(Answer) points_earned = IntegerField Now I'm ranking each user for every month based on their total points earned. I'm using this query to achieve this task: UserAttempts.objects.filter(quiz__start_date__month=date.today().month ).values('user').annotate(correct_answer=Count('answer__is_correct') ).annotate(rank=Window(expression=DenseRank(), order_by= [F('correct_answer').desc(),])) I'm sending the paginated response of the monthly rankings of user with their names, id's and number of correct and incorrect answers. Now I want to add the previous month rank of the current logged in user in my paginated response so that I can show his progress against his last month rank when he's fetching the total user rank table. I'm using generics.ListAPIView in drf. How can I achieve this? -
Schema validation failed; XML does not comply with UBL 2.1 standards using python
I am trying to use validate my xml with UBL 2.1 standards in line with ZATCA specifications. But I can't validate that as my xml looking great but I don't understand what's going wrong .I used python json2xml package for creating xml. enter image description here My full xml code is here: <?xml version="1.0" ?> <Invoice> <ProfileID>reporting:1.0</ProfileID> <ID>INV003</ID> <UUID>8433de7f-578f-412e-b446-a5fbed12c0dd</UUID> <IssueDate>2022-08-07</IssueDate> <IssueTime>12:42:02</IssueTime> <InvoiceTypeCode>388</InvoiceTypeCode> <InvoiceTypeCodeName>0101001</InvoiceTypeCodeName> <DocumentCurrencyCode>SAR</DocumentCurrencyCode> <TaxCurrencyCode>SAR</TaxCurrencyCode> <Note>Thank you</Note> <OrderReference> <ID/> </OrderReference> <ContractDocumentReference> <ID/> </ContractDocumentReference> <AdditionalDocumentReference> <UUID>3</UUID> <PIH> <Attachment> <EmbeddedDocumentBinaryObject>TjAc7lON7F9I13Skn+jnXIaPgd3hpUdE6nsc1bmCpsI=</EmbeddedDocumentBinaryObject> </Attachment> </PIH> <QR> <Attachment> <EmbeddedDocumentBinaryObject>1um8CxIavzvt2RXp46R8miw0iOzlKt3UXfmwTLMjfJ0=</EmbeddedDocumentBinaryObject> </Attachment> </QR> </AdditionalDocumentReference> <Signature> <ID>urn:oasis:names:specification: ubl:signature:Invoice</ID> <SignatureMethod>urn:oasis:names:specification:ubl:dsig:enveloped: xades</SignatureMethod> </Signature> <AccountingSupplierParty> <Party> <PartyLegalEntity> <RegistrationName>Altaf Miazee</RegistrationName> </PartyLegalEntity> <PartyIdentification> <ID/> </PartyIdentification> <PartyTaxScheme> <CompanyID>300600363600003</CompanyID> </PartyTaxScheme> <PostalAddress> <Country> <IdentificationCode>BD</IdentificationCode> </Country> <AdditionalStreetName>Altafbari</AdditionalStreetName> <StreetName>dhaka</StreetName> <BuildingNumber>1233</BuildingNumber> <PlotIdentification>1233</PlotIdentification> <CityName>Dhaka</CityName> <PostalZone>12302</PostalZone> <CountrySubentity>Dhaka</CountrySubentity> <CitySubdivisionName>miazee</CitySubdivisionName> </PostalAddress> </Party> </AccountingSupplierParty> <AccountingCustomerParty> <Party> <PartyLegalEntity> <RegistrationName>Hosen MD Altaf</RegistrationName> </PartyLegalEntity> <PartyIdentification> <ID>398765409876333</ID> </PartyIdentification> <PartyTaxScheme> <CompanyID>398765409876333</CompanyID> </PartyTaxScheme> <PostalAddress> <StreetName>الملك سلمان</StreetName> <AdditionalStreetName>الملك سلمان</AdditionalStreetName> <BuildingNumber>1234</BuildingNumber> <PlotIdentification>1234</PlotIdentification> <CityName>dhaka</CityName> <PostalZone>12234</PostalZone> <CountrySubentity>Dhaka</CountrySubentity> <CitySubdivisionName>الملك سلمان</CitySubdivisionName> <Country> <IdentificationCode>BD</IdentificationCode> </Country> </PostalAddress> </Party> </AccountingCustomerParty> <Delivery> <ActualDeliveryDate>2022-08-18</ActualDeliveryDate> <LatestDeliveryDate/> </Delivery> <PaymentMeans> <PaymentMeansCode>10</PaymentMeansCode> <PayeeFinancialAccount> <PaymentNote/> </PayeeFinancialAccount> </PaymentMeans> <AllowanceCharge> <TaxCategory> <ID>S</ID> <Percent>0.0</Percent> <TaxScheme> <ID>VAT</ID> </TaxScheme> </TaxCategory> <ChargeIndicator>False</ChargeIndicator> <MultiplierFactorNumeric>52.1</MultiplierFactorNumeric> <Amount>0.00</Amount> <AmountcurrencyID>SAR</AmountcurrencyID> <BaseAmount>164277.12</BaseAmount> <BaseAmountcurrencyID>SAR</BaseAmountcurrencyID> </AllowanceCharge> <LegalMonetaryTotal> <LineExtensionAmount>164277.12</LineExtensionAmount> <LineExtensionAmountCurrencyID>SAR</LineExtensionAmountCurrencyID> <AllowanceTotalAmount>0.00</AllowanceTotalAmount> <AllowanceTotalAmountcurrencyID>SAR</AllowanceTotalAmountcurrencyID> <TaxExclusiveAmount>146676.00</TaxExclusiveAmount> <TaxExclusiveAmountcurrencyID>SAR</TaxExclusiveAmountcurrencyID> <TaxInclusiveAmount>164277.12</TaxInclusiveAmount> <TaxInclusiveAmountcurrencyID>SAR</TaxInclusiveAmountcurrencyID> <PrepaidAmount/> <PrepaidAmountcurrencyID>SAR</PrepaidAmountcurrencyID> <PayableAmount>164277.12</PayableAmount> <PayableAmountcurrencyID>SAR</PayableAmountcurrencyID> </LegalMonetaryTotal> <TaxTotal> <TaxAmount>17601.12</TaxAmount> <VatAmountCurrency>SAR</VatAmountCurrency> <VatAmountInAccountingCurrency>17601.12</VatAmountInAccountingCurrency> <CurrencyForVatAmountInAccountingCurrency>SAR</CurrencyForVatAmountInAccountingCurrency> <TaxSubtotal> <TaxableAmount>146676.0</TaxableAmount> <TaxableAmountcurrencyID>SAR</TaxableAmountcurrencyID> <TaxCategory> <ID>E</ID> <Percent>1</Percent> … -
Test correct model selection in a DRF View
I have a view with a get endpoint which determines which model to use by looking if the query contains a "bla" query param: class FooView(APIView): def get(self, request): if "bla" in self.request.query_params: model = ModelA else: model = ModelB # ... Now I want to test this via pytest. The approach below seems to work. Is the use of method_calls correct here? Nevertheless, it looks a bit clumsy. @pytest.mark.django_db def test_get_foo_correct_model_selection(client): with mock.patch('path.to.ModelA.objects') as model_a_manager, mock.patch('path.to.ModelB.objects') as model_b_manager: response = client.get(reverse("foo-list") + "?bla=true") assert len(model_a_manager.method_calls) >= 1 assert len(model_b_manager.method_calls) == 0 # and now without bla param with mock.patch('path.to.ModelA.objects') as model_a_manager, mock.patch('path.to.ModelB.objects') as model_b_manager: response = client.get(reverse("foo-list")) assert len(model_a_manager.method_calls) == 0 assert len(model_b_manager.method_calls) >= 1 Is there a more elegant way? -
Django set environment variable via command line and use in Migrations
Following on from this question - Specify a .env file in Django in command line or vscode launch.json. So we have an environment file for dev, test, and production - which is specified in an environment variable ENVIRONMENT_FILE. This holds the database connection information. However, I'm struggling to pass this information when running the migration command: python manage.py migrate Is it possible to setup environment variables before migrations can be run? -
How to make presigned url not downloadable in DRF?
**# setting response for uploading file to s3.** client = boto3.client('s3', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY) response = client.put_object( Bucket=BUCKET_NAME, Body=in_mem_file.getvalue(), Key=str(img_name)) **# getting s3 url of the uploaded image.** url = client.generate_presigned_url('get_object', Params={ 'Bucket': BUCKET_NAME, 'Key':str(img_name)}, ExpiresIn=518400) I am generating a URL for the uploaded image, but the the url generated is getting downloaded. How to make it streamable instead of downloading. PS - The S3 bucket is a private one. -
Django media not loading. staticfiles works
Using Django, I've deployed my webapp to http://159.223.177.51/. To login to see the images, use sof///stackoverflow123 I can see the custom fonts and css so I know the css is working. However, none of the media files are showing. When I try to upload a photo using the forms on the webapp, it gives me a 505 error. On localhost on my desktop computer, all the images work properly. When I uploaded it to ubuntu and edited the new location of the files, none of it works. I've looked through similar posts like this but it didn't solve it. Here's what I tried: in settings.py: MEDIA_ROOT= os.path.join(BASE_DIR, '/home/stelity/myonlinefp/foodpantry/media') MEDIA_URL= "/media/" DEBUG = FALSE In urls.py: ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I also edited the permissions of the media folder to allow everyone to read/write/execute and that didn't solve it either. -
How can I implement a Login system without using django default authentication in Python/Django?
Suppose I have a self-made User Model which holds username and password field. Now I want to login with my self-made username and password in Django. How can I do that? Besides I need to build a Login Api using this username and password. How to do that? -
Better way to generate a slug in django with id appended to it
In Django, I am trying to generate a slug with the name and id fields concatenated. I have the following model: models.py class Item(models.Model): slug = models.SlugField(max_length=255, null=False, blank=False, editable=False, verbose_name=_("item url"), help_text=_("format: required, letters, numbers, underscore or hyphen")) name = models.CharField(max_length=250, null=False, blank=False, verbose_name=_("item name"), help_text=_("format: required, max_length=250")) def save(self, *args, **kwargs): value = str(self.name) + "-" + str(self.pk) self.slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) def __str__(self): return self.name With the above code, when I created an Item with name Apple 15, the slug created was apple-15-none. So, I noticed that the id is not generated until the Item is created and saved. And I was trying to access the id before it was generated. So, I changed the above code to the following: models.py class Item(models.Model): slug = models.SlugField(max_length=255, null=False, blank=False, editable=False, verbose_name=_("item url"), help_text=_("format: required, letters, numbers, underscore or hyphen")) name = models.CharField(max_length=250, null=False, blank=False, verbose_name=_("item name"), help_text=_("format: required, max_length=250")) def save(self, *args, **kwargs): super().save(*args, **kwargs) value = str(self.name) + "-" + str(self.pk) self.slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) def __str__(self): return self.name I saved the item first so that the id is created and generated the slug using that id and saved it again. It works … -
Django Deploy issue
I'm having a little trouble deploying a project. A program error is popping up when I try deploying my code. Below is the exact message that I received. If anyone could help that would be great! Traceback (most recent call last): File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) The above exception (relation "OuterV_category" does not exist LINE 1: ...V_category"."name", "OuterV_category"."name" FROM "OuterV_ca... Exception Type: ProgrammingError at / Exception Value: relation "OuterV_category" does not exist LINE 1: ...V_category"."name", "OuterV_category"."name" FROM "OuterV_ca... ``` ^ -
Python Modules like virtualenv, django is not recognized
I have python version 3.10.5 and the latest pip installed. I have also added python in the environment variables. Commands like pip install django works and it says Requirement already satisfied. But when i try to run "django-admin startproject mysite" or "virtualenv env1" from cmd. It gives me errors like "django-admin" is not recognized as an internal or external command. -
Error "Select a valid choice. That choice is not one of the available choices."
I'm using Django with Mongodb using Djongo Connnector. With Django 2.2 everything is working fine but When I'm upgrading my Django version > 3 , I'm getting - Error "Select a valid choice. That choice is not one of the available choices." while doing any create operation in Django admin. Its happening in models where foreign keys are there , for foreign key it is showing - Select a valid choice. That choice is not one of the available choices. What can be the issue. If I'm downgrading my Django version to 2.2 , everything seems working. enter image description here -
How to stop Ngrok from resetting request headers?
A Django app is hosted with the help of Ngrok. Somehow the react app keeps getting cors error when api's are called. But when both web and server are running on local they work just fine. origin "http://localhost:3000 has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. When the same api is called using postman it works and all the headers are present. But when called from react, it shows cors error. Django Setup for Cors -
ModuleNotFoundError when trying to get my django project to run in ebs
I am following this tutorial: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html As it states I created a django.config file in .ebextensions/django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: matador-web.wsgi:application wsgi.py: """ WSGI config for matador_web project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'matador_web.settings') application = get_wsgi_application() In settings.py I have: WSGI_APPLICATION = 'matador_web.wsgi.application' In var/logs/webstdout.log: ModuleNotFoundError: No module named 'matador_web' ModuleNotFoundError: No module named 'matador_web.wsgi' -
Sabre API Integration with Django
How can we create or integrate Sabre API with Django(python) project. How can we get username and secret key to get connected with the sabre API project. Will you provide any tutorials for the sabre API-Django integration. -
Django 4.1. changes in Admin changelist searches spanning multi-valued relationships
This question is in the context of Admin changelist searches spanning multi-valued relationships changes introduced in django 4.1 as explained here. Suppose there's a model arrangement as follows: class Person(models.Model): official_name = models.CharField(max_length=255) ... class NickName(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) nick_name = models.CharField(max_length=255) ... And suppose that NickNameAdmin is implemented as: class NickNameAdmin(admin.ModelAdmin): search_fields = ['person__official_name', 'nick_name'] ... Now, suppose a person with Robert Downey as his official name also has Iron Man and Junior as his nick names. Now, if one were to search for Iron Man, then how is the search filter going to behave for NickNameAdmin? Will it search for Iron in the person__official_name field and Man in the nick_name field?