Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ktor - make a post request with different naming of the keys of the JSON in kotlin and django
I want to make a post request with different naming of the JSON keys in Ktor and django. It is not a big deal but I want to follow the convention of naming the vals in Kotlin and django. This is how my user post request body looks in Kotlin/Ktor: @Serializable data class UserPostRequest( val username: String, val email: String, val password: String, val password_check: String ) The problem with this on is the "password_check" val, which is not named by convention Property name 'password_check' should not contain underscores When I try to change it to passwordCheck, make post request, it returns me an error that the passwords do not match. I assumed this is because django expects 'password_check' as a JSON key. -
Django custom middleware doesn't caches sometime
I am trying to make a multi tenant website. For example a.com and b.com websites runs same home.html but it's values changes by it's domain name. But my middleware doesn't caches sometimes. I added my cache_tenant_mw.py and redis in settings.py MIDDLEWARE = [ ... 'rhsuite.cache_middleware.cache_tenant_mw', ] CACHES = { "default": { "BACKEND": "django.core.cache.backends.redis.RedisCache", "LOCATION": "redis://127.0.0.1:6379", } } and added the code which caches tenant values in cache_tenant_mw.py from rhsuite.models import Tenants, Themes, Settings, Metas, Languages from django.shortcuts import get_object_or_404 from django.core.cache import cache from rhsuite.helpers.utils import get_metas def cache_tenant_mw(get_response): def middleware(request): response = get_response(request) def get_hostname(request): host = request.get_host().split('.') popped = host.pop() joined = ".".join(host) return joined def get_tenant(request): hostname = get_hostname(request) tenant_obj = get_object_or_404(Tenants, name=hostname) # get metas and languages tenant_obj.metas = get_metas(Metas.objects.filter(meta_able_type="tenants", meta_able_id=tenant_obj.id)) tenant_obj.languages = Languages.objects.filter(id__in=list(tenant_obj.metas['languages'].values())) # cache tenant cache_key = "tenant" cache.set(cache_key, tenant_obj) cached_tenant = cache.get('tenant') # cache tenant settings settings_obj = Settings.objects.filter(tenant_id=tenant_obj.id) settings_key = "settings" cache.set(settings_key, settings_obj) # cache theme theme_obj = Themes.objects.get(tenant_id=cached_tenant.id) theme_key = "theme" cache.set(theme_key, theme_obj) return True get_tenant(request) return response return middleware How can i make it able to make my middleware cache every page everytime? -
What is the minimal setup for a Django Custom User Model?
I would like to install, as recommended, a custom user model for a new project early in the process, to avoid complications in migrating further down the line. But since the project is under development and acts as a testbed, I don't yet know which additional fields and methods I will require. I therefore want to get a custom user model up and running with the minimal required information so that the default registration (signup, login, etc) functions all work. I used the following code class User(AbstractUser): def __str__(self): return self.email I inherited from AbstractUser in order to obtain the default functionality, which seems to work. However, the (default) signup produces the following error in the browser: Manager isn't available; 'auth.User' has been swapped for 'accounts.User' So it seems to me that I must also define a UserManager for the custom User. Now there is much advice available about how to do this if additional functionality is required (eg make the email the username, supply extra fields, and so on). But at this stage, I don't want any additional functionality. That will come later. At this point I simply want to ensure that users can sign up, login, change passwords, … -
Django: Select a valid choice. [..] is not one of the available choices using TextChoices
as per the title says, here's my error upon the process of validation of a form. Select a valid choice. 1 is not one of the available choices. Here's the different pieces of code I have. models.py: class Cat(models.Model): class Sex(models.TextChoices): M = 1, 'Male' F = 2, 'Female' sex = models.PositiveSmallIntegerField(choices=Sex.choices, blank=False, null=False) forms.py: class CatForm(forms.ModelForm): # Other fields that I think are useless in this error but maybe I'm missing something for the TextChoice of sex to work out here? fur_color = forms.ModelMultipleChoiceField(queryset=FurColor.objects.get_all(), required=False, widget=forms.CheckboxSelectMultiple) birth_date = forms.DateField(widget = forms.SelectDateWidget(years=range(1980, 2023))) class Meta: model = Cat exclude = ('user','registered_on') The sex field in the form appear as a select list, but when I select either of Male or Female, it doesn't seems to be able to make the link back in the model. Do I need do modify my forms.py to make it work. Or my model is flawed to begin with ? I have Django 4.2.5. Thanks in advance. -
Internationalisation across Django, React and Webcomponents [closed]
I am looking for a solution to unify internationalisation across Django, React and Webcomponents. Currently, we are using Django's gettext, Lit's lit/localize and non yet for React. I would like to unify this to use a single solution across rendering options. So far I came across project-fluent which seems to support all of them separately (django-ftl, react) but is also fractured into various projects and i18next whose Django support is outdated. Can anybody recommend a solution? Any help is appreciated. -
Saved object to db doesn't persist across multiple fixtures in pytest
I everyone, I'm testing my django APIs with pytest and I want to test the login endpoint of my apis. Hence, I need first to create a test user object and save it to db and then try to login with that user credentials and finally test if the response I get is how I expected it to be. I want the test user creation and the login user actions to be in two different fixtures, so that I can eventually call them independently if I need to. This is what I've got so far: @pytest.fixture @pytest.mark.django_db def create_test_user(): def _(): test_user = User.objects.create_user( username="test_user", password="test_password", email="test_email@test.com" ) test_user.save() return test_user return _ @pytest.fixture def login_user(client): def _(user): url = reverse('auth-login') body = { "username": user.username, "password": user.password } response = client.post(url, body, content_type='application/json') cookies_dict = dict((k, v.value) for k, v in response.client.cookies.items()) return response, cookies_dict return _ And then in my test I have: @pytest.mark.django_db def test_login(login_user, create_test_user): # Create a test user on DB test_user = create_test_user() response, cookies = login_user(test_user) # assertions .... The problem here is that when I try to log in with the test user, the user is no longer in db and so … -
JSON response is not getting data when used NGROK's static domain
I want to get JSON data so that it can be used in frontend. const authToken = 'e6f13bd9e9b74d540b8fc998b44e25bf2857cb5d'; fetch('https://absolutely-relaxed-koala.ngrok-free.app/api/admin-products/', { method: 'GET', headers: { Authorization: `Token ${authToken}`, }, }) .then(response => { if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } return response.json(); }) .then(data => { console.log('API Response:', data); if (Array.isArray(data)) { // Process the data as an array and add product items to the list const productList = document.getElementById('product-list'); data.forEach(product => { const listItem = document.createElement('tr'); listItem.textContent = `${product.name} - Price: $${product.product_image}`; const image = document.createElement('img'); // Create an image element image.src = product.product_image; // Set the image source to the product_image URL listItem.appendChild(image); // Add the image to the list item productList.appendChild(listItem); }); } else { console.error('Invalid data structure. Expected an array.'); } }) .catch(error => { console.error('Error fetching products:', error); }); but I case of 'http://127.0.0.1:3000' works fine with JSON response while debugging a little I found out that the response is Response Data: <!DOCTYPE html> <html lang="en-US"> <head> <meta charset="utf-8"> <meta name="author" content="ngrok"> <meta name="description" content="ngrok is the fastest way to put anything on the internet with a single command."> <meta name="robots" content="noindex, nofollow"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link id="style" rel="stylesheet" href="https://cdn.ngrok.com/static/css/error.css"> <noscript>You are … -
RQ Job Terminated Unexpectedly
I have defined the rq task on module task.py as: import django_rq import logging from django.conf import settings import requests log = logging.getLogger(__name__) def req_call(): url = 'https://jsonplaceholder.typicode.com/posts' response = requests.get(url) return response @django_rq.job('default') def test_request_call_on_rq_job(): response = req_call() log.warning(f'REQUEST's RESPONSE {response.json()}') When I've offloaded task in another module as: if __name__ == '__main__': # rq job test log.setLevel(logging.DEBUG) test_post_request_on_rq_job.delay() I am getting error as: [INFO] *** Listening on default... [worker:702] [INFO] default: rq_test_module.tasks.test_request_call_on_rq_job() (676c1945-9e05-4245-aeb2-65100cdb4169) [worker:875] [WARNING] Moving job to FailedJobRegistry (Work-horse terminated unexpectedly; waitpid returned 11 (signal 11); ) [worker:1114] I then started doing debugging, then I saw error encounters as soon as the job task tried executing the request call i.e. requests.get(url) And if I remove the request call from the job, jobs executed gracefully without any errors. Signal 11 suggests a segmentation fault, I suspect something related to memory but not quite sure about it. So anyone here encountered similar issue and workaround for this :) -
deployment on elastic beanstalk
i am trying to deploy my django app on aws using the awsebcli amd i am trying to run the eb init command and i am getting this error DELL@DESKTOP-LOONUF5 MINGW64 ~/Desktop/kennedy_logistics (main) $ eb status ERROR: This directory has not been set up with the EB CLI You must first run "eb init". DELL@DESKTOP-LOONUF5 MINGW64 ~/Desktop/kennedy_logistics (main) $ eb logs ERROR: This directory has not been set up with the EB CLI You must first run "eb init". DELL@DESKTOP-LOONUF5 MINGW64 ~/Desktop/kennedy_logistics (main) $ eb init Select a default region us-east-1 : US East (N. Virginia) us-west-1 : US West (N. California) us-west-2 : US West (Oregon) eu-west-1 : EU (Ireland) eu-central-1 : EU (Frankfurt) ap-south-1 : Asia Pacific (Mumbai) ap-southeast-1 : Asia Pacific (Singapore) ap-southeast-2 : Asia Pacific (Sydney) ap-northeast-1 : Asia Pacific (Tokyo) ap-northeast-2 : Asia Pacific (Seoul) sa-east-1 : South America (Sao Paulo) cn-north-1 : China (Beijing) cn-northwest-1 : China (Ningxia) us-east-2 : US East (Ohio) ca-central-1 : Canada (Central) eu-west-2 : EU (London) eu-west-3 : EU (Paris) eu-north-1 : EU (Stockholm) eu-south-1 : EU (Milano) ap-east-1 : Asia Pacific (Hong Kong) me-south-1 : Middle East (Bahrain) il-central-1 : Middle East (Israel) af-south-1 : Africa (Cape Town) … -
Can I make a part of a finished Django Project CMS
So i finished programming the website for the company Newtive and i while programming i integrated Django because i wanted the projects part in the website to be CMS so that the owner of the website wont ask me to add each project whenever they make a new one but while trying to make it CMS from django's admin panel i faced allot of problems one of them is that i found out that he didn't want the same design pattern for all the project descriptions i could make them all the same pattern(for example making all the pictures inside a slider and under that will be the description) but he didn't want it he wants it the way it is now but i need a way to add this CMS feature because allot of projects are coming on the way. I am still a beginner and i have allot to learn any help is appreciated here is the page i am talking about https://newtivedesign.com/projects/ -
code to collectstatic on localhost static folder
I'm not sure what needs to be fixed, it's probably something on my settings.py, my localhost static folder is empty, but my s3 is working fine, picking up all of the collectstatic files that should also end up in my localhost folder (see image). Here's the relevant code from my settings.py: BASE_DIR = Path(__file__).resolve().parent.parent DATA_DIR = os.path.dirname(os.path.dirname(__file__)) STATIC_URL = 'static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(DATA_DIR, 'media') STATIC_ROOT = os.path.join(DATA_DIR, 'static') STATICFILES_LOCATION = 'static' MEDIAFILES_LOCATION = 'media' # CUSTOM STORAGES STATICFILES_STORAGE = 'custom_storages.StaticStorage' DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' AWS_STORAGE_BUCKET_NAME = 'xxxxxxx-xxx' AWS_S3_SIGNATURE_NAME = 's3v4', AWS_S3_REGION_NAME = 'xxxx-xxx-1' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None AWS_S3_VERITY = True DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME I run python.manage.py collectstatic, and absolutely nothing gets copied to the static folder of my Django project like it's supposed to. -
Is there a django plugin that produces documentation for the template inheritance structure?
The django.contrib.admindocs plugin provides a nice link in the admin view to a variety of documentation around the data models. Is there a similar plugin that provides a diagram or description of how templates inherit from one another and the variables defined? Searched Django plugins https://djangopackages.org/search/?q=template+inheritance -
Summarize Django Queryset where Amount falls into Specific Groups
I'd like to group my transactions by the amount category that they fall into and sum those. I'd love to do this with 1 query, but I can't figure out what this kind of grouping is called. So I'm having a hard time finding any examples. zero_to_twenty = Transactions.objects.filter(amount__lte=0, amount__gt=-20).aggregate(Sum("amount")) twenty_to_fifty = Transactions.objects.filter(amount__lte=-20, amount__gt=-50).aggregate(Sum("amount")) fifty_to_seventy_five = Transactions.objects.filter(amount__lte=-50, amount__gt=-75).aggregate(Sum("amount")) seventy_five_to_one_hundred = Transactions.objects.filter(amount__lte=-75, amount__gt=-100).aggregate( Sum("amount") ) one_hundred_plus = Transactions.objects.filter(amount__lte=-100).aggregate(Sum("amount")) Obviously this is not ideal, but it gets me the correct data. Is it possible to do this with 1 query? -
Expected type 'Sized', got 'TextField' instead
I am working on a small project with Django and i have to validate the size for a text field and then return some data based on the condition. I am using the len() method to check the TextField() size and then return some data. The code is working, but I have an error from the IDE (Pycharm) that says: "Expected type 'Sized', got 'TextField' instead". I spent some time looking in some resources online but i can't find anything related to my issue. Have you deal with this before? Here's the code: ` class Topic(models.Model): """A topic the user is learning about.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.text class Entry(models.Model): """Something specific learned about a topic.""" topic = models.ForeignKey(Topic, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): """Return a string representation of the model.""" if len(self.text) < 50: return f"{self.text}" return f"{self.text[:50]}..." ` Thank you! -
Getting Error No Module found after deploying my DRF profject on Vercel
i'm trying to deploy my django rest framework to vercel free tier and during the deployment to show deployed successful witth the ready been ready, but when i open the link it return the following This Serverless Function has crashed. Your connection is working correctly. Vercel is working correctly. 500: INTERNAL_SERVER_ERROR Code: FUNCTION_INVOCATION_FAILED ID: cdg1::525rm-1695080572313-5e091aaaa7b6 If you are a visitor, contact the website owner or try again later. If you are the owner, learn how to fix the error and check the logs. and when i open the logs i see these error message [ERROR] Runtime.ImportModuleError: Unable to import module 'vc__handler__python': No module named 'django' Traceback (most recent call last): please can anyone help out -
Django modeladmin fields - display/edit values in MHz, save to database in Hz?
I would like to change an existing django modeladmin view that currently has a field 'frequency_hz' so that users can view the current values in MHz and enter new values in MHz, and have modeladmin convert the value back to Hz when saving to the database. Is there a simple way to do this with modelAdmin - or is there any other suggested way to achieve what I am looking for? So far it looks like modelAdmin has limited capabilities with regards to any sort of calculation performed on a field: I can add a property to my model with the calculated value (frequency_MHz), and add this property to list_display, but it is not editable. It doesn't look like there's a way to enable modelAdmin to treat these calculated properties as writable fields (understandably) I see with modelInlines I can define a submethod that returns the expected value. - however I can't get this to work with modelAdmin - and I believe this suffers a similar limitation to being read only. -
Django Sales Page with Dynamic Customer and Product Data
I'm attempting to create a simple sales form using Django where customer data is displayed at the top of the page, followed by another form below it that allows users to add products. At the bottom, I want to show the total order amount and other calculated details. Essentially, I'm trying to create a product form nested within a sales form, involving data from various other models. I've made several attempts but haven't been able to find similar solutions in forums and tutorials. Could someone provide guidance or ideias on how to do this? -
How to create a link between two models in Django?
There are 2 models School Director It is necessary to make sure that in the school model there is a director (full name), and in the Director model there is the name of the school from django.db import models class Director(models.Model): created_at = models.DateTimeField(auto_now_add=True) first_name = models.CharField(max_length=50, verbose_name='Name') last_name = models.CharField(max_length=50, verbose_name='Surname') school = models.CharField() #<----???? photo = models.ImageField(upload_to="uploads/img/", height_field=None, width_field=None, max_length=10000, verbose_name='photo') birthday = models.DateField( verbose_name='birthday') class school(models.Model): created_at = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=50, verbose_name='name') capacity = models.IntegerField(max_length=20,verbose_name='capacity') registration_is = models.BooleanField(max_length=20,verbose_name='Registration') director_name = models.ForeignKey(Director, related_name='name boss') class school, inherits the model of the director in the director_name class Director, must also inherit the Boss class, for the director_name field school = models.CharField() But it doesn't work for obvious reasons Django guru, tell me how to implement this task, please I Googled everything I could but didn't find a solution. -
Sequnce vs TextChoice vs IntegerChoices in Django
Which method is preferable for determining the choices in the `choices` argument when defining the model field in Django? Suppose I have a some model: class Balance(models.Model): reason = models.CharField(choices=...) # or models.IntegerField ... Sequnce: REFILL = 1 CASHBACK = 2 SUBSCRIPTION = 3 ORDER = 4 Reason = ( (REFILL, "Refill"), (CASHBACK, "Cashback"), (SUBSCRIPTION, "Subscription"), (ORDER, "Order"), ) TextChoices: class Reason(TextChoices): REFILL = "refill", "Refill" CASHBACK = "cashback", "Cashback" SUBSCRIPTION = "subscription", "Subscription" ORDER = "order", "Order" IntegerChoices: class Reason(IntegerChoices): REFILL = 1, "Refill" CASHBACK = 2, "Cashback" SUBSCRIPTION = 3, "Subscription" ORDER = 4, "Order" Django documentation does not give preference to any one method. Just showing different ways. I often see examples with a sequence, but what's wrong with using TextChoices or IntegerChoices? In what situations is it better to use these classes? -
Two Layer Nested Serializers - Django Rest Framework
Say I have models with grandparent-parent-child relations like so: models.py class Unit(...): number = models.CharField(...) class Listing(...): unit = models.ForeignKey('Unit', related_name="listings", ...) number_of_bedrooms = models.IntegerField(...) class Price(...): listing = models.ForeignKey('Listing', realted_name="prices", ...) amount = models.DecimalField(...) Using DRF - how can I grab all of the price instances for a listing in the ListingSerializer; all prices are determined by the grandparent Unit. I am trying: serializers.py class PriceSerializer(serializers.ModelSerializer): class Meta: model = Price fields = ["amount"] class ListingSerializer(serializers.ModelSerializer): prices = PriceSerializer( source="unit__listings__prices", # <-- this does not seem to work many=True, read_only=True, ) ... Essentially: a unit can have multiple listings a listing can have multiple prices a unit will have many prices as its "grandchildren" how can I get all of the price "grandchildren" on the ListingSerializer -
Call Django service worker method for another device
I want to create a function needsToBeCalled(a, b) in serviceworker.js for Django that can be called from another device. What I need is when Django admin clicks a button, a function should be called but on every SELECTED device with service worker turned on. serviceworker.js var staticCacheName = 'djangopwa-v1'; self.addEventListener('install', function(event) { event.waitUntil( caches.open(staticCacheName).then(function(cache) { return cache.addAll([ '/base_layout' ]); }) ); }); self.addEventListener('fetch', function(event) { var requestUrl = new URL(event.request.url); if (requestUrl.origin === location.origin) { if ((requestUrl.pathname === '/')) { event.respondWith(caches.match('/base_layout')); return; } } event.respondWith( caches.match(event.request).then(function(response) { return response || fetch(event.request); }) ); }); function needsToBeCalled(a, b) { console.log(a + b); } Service worker is working as it should, I just need a way to call this function from device 1 so it outputs something on devices 2, 3, 4... -
generate a custom token on django rest framework
I am developing an application which I wrote an api for it this api create a user by verifying it's phone number so then I want to generate him token the post request should be like this { "phone_number": "", "username": "", "bio', "profilePic": null } and if model serializer is valid the output should be like this and it should generate a token for another requests { "phone_number": "", "username": "", "bio', "profilePic": null, "token": "28duw8he282hd2sszajqj" } so I want to create a customize auth class is there any one to help with my problem this is the user model class class WhIronUsers(models.Model): phone_number = models.CharField(max_length=100, verbose_name="phone_number", unique=True) username = models.CharField(max_length=100, verbose_name="username") bio = models.CharField(max_length=255, verbose_name="bio") profilePic = models.ImageField(upload_to="images/profile") and this is the view which in this view I want to generate the token from rest_framework import generics from .serializers import WhIronUserSerializer from .models import WhIronUsers class WhIronUserView(generics.ListCreateAPIView): serializer_class = WhIronUserSerializer queryset = WhIronUsers.objects.all() class WhIronDetailUserView(generics.RetrieveDestroyAPIView): serializer_class = WhIronUserSerializer queryset = WhIronUsers.objects.all() -
How do I use a forms action attribute to work with an object pk in django?
I have a form which needs to use the pk of the object its use is needed for. How do I write the url in the action attribute instead of leaving it blank? The url conf is this: path('add/<int:pk>/', ObjectView.as_view(), name='add') The link to the form from the other template pages is this: <a href="{% url 'app:add_users' object.id %}">Form</a> The class handling it is pretty basic with get and post which currently accept **kwargs for the object's pk So how do I edit the action attr to work when not left blank in the form?: <form action="" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Invite"> </form> -
Django Media files: https://https://
In Django the following settings are configured: MEDIA_URL="https://abcdefg.cloudfront.net/media/" STATIC_URL="https://abcdefg.cloudfront.net/static/" In web browsers the URL for the static files is correct. The URL for media files however is incorrect with https://https: leading to 404's: https://https://abcdefg.cloudfront.net/media/ When I print(f"MEDIA_URL: {MEDIA_URL}"), from the settings the URL is correct. I use {% get_media_prefix %} and {% get_static_prefix %} for my static and media files. For example: <img src="{% get_media_prefix %}image.jpg" alt="Image"> This alternative does not work: MEDIA_URL="abcdefg.cloudfront.net/media/" The result observed in the browser is https://example.com/abcdefg.cloudfront.net/media/ EDIT: I am using Django-CMS What is the issue here? -
Django get pk row if pk is found in queryset filter
I have the current table example : I know how to get the rows where the ID is found in : result_query_1 = models_contacts.objects.filter(company_members_id__icontains= str(pk)+";") result_query_2 = (here I would like the row of the ID used for the previous query if a match is found) But I would like to go one step further and also get the row of the ID in another queryset (depending on the first one matches). For example : If id 1 is found in company_members_id : result_query_1 = row N°2 (addidas) + row N°4 (Jordan) and result_query_2 = row N°1 (Nike) I was thinking of using a for loop but I don't Know how to do this in Django. Maybe there is a simpler / better way to do this ? Thanks