Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Filter row by ManyToManyField so that all m2m are a sublist of a list
I have a list [1,2,3,4] and a django model with a manytomany field id If id can contain [1,2,3] or [1,5] How can I return the objects that contain a substring of my list [1,2,3,4] and not anything outside that list [1,5]. I've seen this Django filter queryset __in for *every* item in list. But I only want to return a substring -
How to use if else condition using mathfilters in Django?
I have a question, I'm doing a project in Django and there is a part of the application called Pagos(payments), there I show the following: payments made, total_pagos(total payment) and pending payment, To show the information of these payments I'm using mathfilters because addition and subtraction are used in my templates. For the template it's showing the information properly, only the problem comes when I want to use conditionals since once pending payment is equal to 0.00 it means that the client already pays everything and must show a text that says “PAGADO” (paid), when pending payment it has another number than 0.00 must show a label that says “PENDIENTE” (pending). This is the code that I am using and it works, since it shows me the result of the costo_servicio (amount of the service) cost minus the total_pagos (total payments), whatever it shows is the pending payment, it can show several numbers or 0.00: {% for juicio in juicios %} {{ juicio.costo_servicio|sub:total_pagos }} {% endfor %} But if I put this, it doesn't show the if and therefore doesn't do the subtraction or show the text PAGADO(paid): {% for juicio in juicios %} {% if juicio.costo_servicio|sub:total_pagos == 0.00 %} … -
How can I restrict the images selectable by the user in Wagtail's ImageChooserBlock?
Some image content on my Wagtail site must meet certain requirements (e.g. a differing minimum size for banner images, carousel images, etc.). I know I can validate my image requirements after the edit form data is submitted, but I'd like to make the workflow more user-friendly by restricting the widget to only show images that will pass validation in the first place. What is the best way to go about this? Wagtail 5.2.2 -
Django REST Framework (DRF)'s FileField behave differently in generics view and APIView
I want handle file upload in django. The Model and Serializer are as follow: def save_file(instance, filename): _, ext = os.path.splitext(filename) return f"{instance.id}{ext}" class FileModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=64) file = models.FileField(upload_to=save_file) created = models.DateTimeField(auto_now_add=True) class FileModelSerializer(serializers.ModelSerializer): class Meta: model = FileModel fields = "__all__" When I use generics view like this: class FileListApi(generics.ListAPIView): queryset = FileModel.objects.all() serializer_class = FileModelSerializer The API will be like this, the url is absolute path: [ { "id": "2c5488ec-7b5d-45ab-9c43-058c19d76626", "title": "file.png", "file": "http://127.0.0.1:8000/media/2c5488ec-7b5d-45ab-9c43-058c19d76626.png", "created": "2024-02-07T02:29:29.845808Z" } ] However when I use APIView: class FileListApi(APIView): def get(self, request): serializer = FileModelSerializer(FileModel.objects.all(), many=True) return Response(serializer.data) The url is now relative path: [ { "id": "2c5488ec-7b5d-45ab-9c43-058c19d76626", "title": "file.png", "file": "/media/2c5488ec-7b5d-45ab-9c43-058c19d76626.png", "created": "2024-02-07T02:29:29.845808Z" } ] I can image there will be situations that require absolute path or relative path, in my particular case I want to use relative path. Why DRF behave differently in generics view and APIView? How to make DRF output url differently? -
i deploy a django-React app on fly.io, but the data in redux does not appear
I deploy this app in Fly.io, but when I access the url it shows me the templates and does not access the APIs, I am using redux and it shows everything null I do not know what is happening I'm stuck, i can't fix the problem -
How to add a schema under actions in django_rest_framework
`@api_view(['POST']) def createUser(request): print(to_jsonschema(UserSerializer())) serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) else: return Response(serializer.errors, status=400)` For example I would like for this to be returned { "name": "Token Refresh", "description": "Takes a refresh type JSON web token and returns an access type JSON web\ntoken if the refresh token is valid.", "renders": ["application/json", "text/html"], "parses": [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ], "actions": { "POST": { "refresh": { "type": "string", "required": true, "read_only": false, "label": "Refresh" }, "access": { "type": "string", "required": false, "read_only": true, "label": "Access" } } } } This is from an built in view from rest_framework_simplejwt. Overall I would like to add a schema such as the actions data which shows for the method post refresh and access are required. I want something like this for my createUser view as I can easily see what attribute the api endpoint takes for example username or password, I looked online and found this https://www.django-rest-framework.org/api-guide/metadata/ but I couldn't get it to work. I looked at other solutions also but they were just showing to create a different view which sends a JSON schema back as get request. Overall I just want something simple that I can easily use to communicate … -
Implement tabs with htmx
I want to implement simple tab functionality with htmx for a Django template. I know of the django_htmx package, but I chose to use htmx directly and I’m now having trouble implementing the tab functionality. I tried using the example from the htmx website using JavaScript but I’m having trouble, all the prospective tabs are divs on the same page. -
Django update_or_create within a loop is duplicating field values, but just a couple fields
It's been a while but I have a somewhat puzzling issue. I am looping over some data being pulled from an api and performing an update_or_create call through django. for product in response['products']: for variant in product['variants']: print(variant['product_id']) obj, created = Product.objects.update_or_create( sku=variant['sku'], defaults={ 'name': product['title'], 'price': variant['price'], 'sku': variant['sku'], 'shopify_product_id': variant['product_id'], 'shopify_variant_id': variant['id'], 'weight_grams': variant['grams'], }, ) During the loop you'll notice I am printing the value of the variant product id. print(variant['product_id']) In the console I see the print results are correct with different variant product ids. 7396903682207 7405275381919 7405275775135 7405273579679 7405278101663 7396921475231 9034125279391 But in the database both the variant['product_id'] and variant['id'] are all the same for every row. Yet the other details such as name and price are all correct and differ per row. I can not for the life of me figure out why this is happening. I am using the sku as the unique identifier to filter on and it is set as unique in my model. No matter what I do or try, it is only those two fields that get duplicated. -
django autofill inlineformset_factory
first of all ,i'm start usin django a few mounth ago also i'm not good using english language so sorry in the first place i've create models like this class Project(models.Model): def __str__(self): return self.name name=models.CharField(max_length=80) class champs(models.Model): def __str__(self): return self.nom def ImageSet(instance,nom): return """/project_manager/static/projects/{}_{}""".format(instance.id,nom) name=models.CharField(max_length=50,unique=True) ordre=models.IntegerField(default=999) illustration=models.ImageField(upload_to=ImageSet, height_field=None, width_field=None, max_length=None,blank=True,null=True) parent=models.ForeignKey(Project, verbose_name="projet", on_delete=models.CASCADE) class commade(models.Model): def __str__(self): return self.description clientFirstName=models.CharField(max_length=50) clientLastName=models.CharField(max_length=50) addres=models.CharField(verbose_name="adresse de l'intervention", max_length=300) email=models.EmailField(max_length=254) tel=PhoneNumberField(blank=True) date_d_intervention=models.DateTimeField(auto_now=False, auto_now_add=False,verbose_name="date d'intervention") project = models.ForeignKey(Project, on_delete=models.CASCADE) description=models.TextField() class Response(models.Model): def __str__(self): return self.champs.name commande=models.ForeignKey(commade, on_delete=models.CASCADE) champs=models.ForeignKey(champs, on_delete=models.CASCADE) valeur=models.CharField( max_length=80) i've create django admin were i can autofill inlineformset of response model champs with values of which have the same project before i choose the project when i chose the project now what i need is how to make it using inlineformset_factory in django forms.py or usin views.py without using js or jquery for security purpos can you teach me please thanks in advence -
How to not save a Django model if certain conditions are not met, and display an error message in the console page
In Django what is the best way to not save a model if certain conditions are met and stay on the change page, and display a custom Django error message in the console -
Input Json data in django models
I have a json file with a huge number of data in it, I have also created a django model to store that data and now I can't figure out how to put that json data into my models. Doing it manually will consume a lot of my time. However, I can use models.JSONField to put that data but that's not what I want. I want to put each data in a model field. Here's a sample of my JSON data: [ { "end_year": "", "intensity": 6, "sector": "Energy", "topic": "gas", "insight": "Annual Energy Outlook", "url": "http://example.com", "region": "Northern America", "start_year": "", "impact": "", "added": "January, 20 2017 03:51:25", "published": "January, 09 2017 00:00:00", "country": "United States of America", "relevance": 2, "pestle": "Industries", "source": "EIA", "title": "Test phase", "likelihood": 3 } ] And this is my model: class myModel(models.Model): end_year = models.PositiveIntegerField(null=True, blank=True) intensity = models.PositiveSmallIntegerField(null=True, blank=True) sector = models.CharField(max_length = 255, null=True, blank=True) topic = models.CharField(max_length = 55, null=True, blank=True) insight = models.TextField() url = models.URLField(max_length = 300) region = models.CharField(max_length = 50, null=True, blank=True) start_year = models.PositiveIntegerField(null=True, blank=True) impact = models.CharField(max_length = 255, null=True, blank=True) added = models.DateTimeField(null=True, blank=True) published = models.DateTimeField(null=True, blank=True) country = models.CharField(max_length = 50, … -
<django.db.models.query_utils.DeferredAttribute object at ... > instead of data value in PostgreSQL database
I am trying to display a value on an html page but the value is just returning as <django.db.models.query_utils.DeferredAttribute object at ... >. The issue is the variable 'card_name'. This is my code files from my Django project: Models.py: class mProSet1990(models.Model): Image = models.CharField(max_length=255, primary_key=True) Card = models.CharField(max_length=255) class Meta: managed = False db_table = '1990 Pro Set' Views.py: def ProSet1990_1(request): # Fetch the card details from the database card_1 = mProSet1990.objects.get(Card="David Seaman #1") # Use the web scraping bot to get the lowest card price lowest_price = get_lowest_card_price(f'{mProSet1990.Set} {mProSet1990.Card}') # Pass the data to the template context = { 'card_1': card_1, 'card_name': mProSet1990.Card, 'lowest_price': lowest_price, } # Render the template with the data return render(request, 'Application/ProSet1990_1.html', context) ProSet1990_1.html body: <body> <h1>{{ card_name }}</h1> {% if lowest_price %} <p>Lowest Price: {{ lowest_price }}</p> {% else %} <p>Price not available</p> {% endif %} </body> mProSet1990.Set and mProSet1990.Card are not pulling the actual values, they are returning as <django.db.models.query_utils.DeferredAttribute object at ... >. -
How do I handle multiple user selected actions when updating my database via CSV?
I'm working on a database of shows which has models for Actors, Characters, and Shows. I'm trying to implement a Bulk Upload feature that accepts a CSV file. I'm starting with bulk uploading shows, here's the relevant model: class Show(models.Model: title = models.CharField(max_length=2083, blank=True, null=True) blurb = RichTextField(blank=True) website = models.CharField(max_length=2083, blank=True, null=True) host = models.ManyToManyField('Host', through='ShowHosts', blank=True) Currently, when the file is submitted, the site checks the 'Title' and 'Host' fields against existing records in the database and, if there are no duplicates, it creates a new instance of the 'Show' and 'Host' and assigns the new 'Host' to the new 'Show'. Where I need assistance is what happens when a duplicate is found. This is how I'd like to handle it: The user is redirected to a new page containing a table. Each row has three columns; the first contains a dict consisting of the uploaded info for the new show, the second contains the Model Object of the duplicate Show/Host that was found in the database already, the third is a element prompting the user to choose how they'd like to handle the duplicate. Here's an example of the results when one of the rows of the … -
Django @csrf_exempt a logging endpoint
I'm making a social media site where users click into posts, and every time they do so, I call an endpoint to log a view for that post. Would it be safe to csrf_exempt this endpoint that only fetches a Post object from a slug and increases the post's view_count by 1? -
Model Creation Freezing Django (or Django Rest Framework)
I have this model: class AllowedUser(models.Model): PLACE_CHOICES = ( (1, 'Loc1'), (2, 'Loc2'), (3, 'Loc3'), (4, 'Loc4'), (5, 'Loc5'), ) id = models.CharField(primary_key=True, max_length=8, unique=True, default=generate_unique_id) name = models.CharField(max_length=60) place = models.IntegerField(choices=PLACE_CHOICES) current_version = models.CharField(max_length=8, default="0.0.1") last_updated = models.DateTimeField(default=datetime.datetime(1970,1,1,0,0,0)) def __str__(self): return self.id + ' - ' + self.name And when I try it in shell, or even in runtime with DRF, it just does nothing. In DRF, it stops with no error right after serializer.save(), in Shell it freezes (not actually freeze, but waits for something) right after AllowedUser(...Data...). I'm using SQLite3 as database. I actually don't know what's the root problem here. Anyone got an idea on what's causing it to hold? Thanks in advance. -
How do I get return value on different color in front end
I have backend code written in python where it returns a number, I want to show the number in different color for certain threshold. For example if the number is 15 and above it should show in red color Here is the code: def zulu_extracts(weather_input,datis=None): # This could be work intensive. Make your own conversion if you can avoid using datetime raw_utc = Root_class().date_time(raw_utc='HM')[-4:] raw_utc_dt = datetime.strptime(raw_utc,"%H%M") if datis: zulu_item_re = re.findall('[0-9]{4}Z', weather_input) else: zulu_item_re = re.findall('[0-9]{4}Z', weather_input) if zulu_item_re: zulu_weather = zulu_item_re[0][:-1] zulu_weather_dt = datetime.strptime(zulu_weather,"%H%M") diff = raw_utc_dt - zulu_weather_dt diff = int(diff.seconds/60) return diff else: zulu_weather = 'N/A' return zulu_weather The front end is based on html,css and JS I already searched on google and tried chat GPT but nothing seems to work -
Does Django formsets prevent editing hidden fields with id?
Formset is created with modelformset_factory and uses regular ModelForm, I'm also using django-crispy-forms. Why modifying form-X-id hidden field value from A to B (both A and B ids exist in database) does not modify that record? Inside view form_valid method I can see that field value is B, so I would expect that record A attributes would be the same as record B, but thankfully it does not happen, instead view proceeds as if nothing went wrong, why is that? -
Why are Django related object queries not cached?
I have the following unit test: def test_cache(self): with self.assertNumQueries(1): print(database.records.all()) print(database.records.all()) print(database.records.all()) The test fails because 3 queries are made: Captured queries were: 1. SELECT "store_record"."id", "store_record"."key", "store_record"."database_id", "store_record"."user_id", "store_record"."organization_id", "store_record"."data", "store_record"."created_at", "store_record"."updated_at" FROM "store_record" WHERE "store_record"."database_id" = '7d86d143-9e4e-4420-801c-3d3c5e6875fb'::uuid LIMIT 21 2. SELECT "store_record"."id", "store_record"."key", "store_record"."database_id", "store_record"."user_id", "store_record"."organization_id", "store_record"."data", "store_record"."created_at", "store_record"."updated_at" FROM "store_record" WHERE "store_record"."database_id" = '7d86d143-9e4e-4420-801c-3d3c5e6875fb'::uuid LIMIT 21 3. SELECT "store_record"."id", "store_record"."key", "store_record"."database_id", "store_record"."user_id", "store_record"."organization_id", "store_record"."data", "store_record"."created_at", "store_record"."updated_at" FROM "store_record" WHERE "store_record"."database_id" = '7d86d143-9e4e-4420-801c-3d3c5e6875fb'::uuid LIMIT 21 Why is the records field not cached? What is telling Django to do refetch the data from the database? -
File path not saved in database, but it is in storage. Collision? Django rest framework
Hey im trying to handle file upload with use of celery tasks. However after all tasks complete, file appears to be in storage and not in database when i query /files. Thumbnail (which is generated as second task, but is much faster) is both saved in storage and database. What could be the issue? views.py @extend_schema( description="Upload file", request=FileSerializer, responses={201: FileSerializer}, ) def post(self, request, *args, **kwargs): file = request.data["file"] total_sum = File.objects.filter(owner=request.user).aggregate(models.Sum("size")) total_sum = total_sum["size__sum"] if total_sum["size__sum"] else 0 if total_sum + file.size > request.user.storage_limit: return Response( {"error": "Storage limit exceeded"}, status=status.HTTP_400_BAD_REQUEST ) request.data["size"] = file.size serializer = FileSerializer(data=request.data) if serializer.is_valid(): serializer.save(owner=request.user, size=file.size) FileService.upload_file(serializer.data["id"], file.read(), file.content_type) return Response(serializer.data, status=status.HTTP_202_ACCEPTED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) services.py import base64 import mimetypes from common.service import Service from storage.tasks import UploadHandler, ThumbnailHandler class FileService(Service): # Service is empty class, just class Service: ... handlers = [UploadHandler, ThumbnailHandler] handler = handlers[0]() for next_handler in handlers[1:]: handler.set_next(next_handler()) @staticmethod def get_file_extension(mimetype: str): return mimetypes.guess_extension(mimetype) @staticmethod def upload_file(file_id: str, file: bytes, mimetype: str): file_bytes = base64.b64encode(file) extension = FileService.get_file_extension(mimetype) FileService.handler.handle((file_id, extension, file_bytes)) tasks.py import base64 from celery import shared_task from django.conf import settings from django.core.files.base import ContentFile from services.grpc_client import Client from common.chain import AbstractHandler from storage.models import File … -
Django ORM groupby
row_1(PK) row_2 row_3 1 row one 2 row two 3 row three Data from my database table looks like the above table. SELECT GROUP_CONCAT(row_3) FROM table_ WHERE row_2 = 'row' GROUP BY row_2; My Django query to achieve above mysql query table_.objects.filter( row_2='row' ).annotate( val=GroupConcat('row_3', '') ).values('val') When converting the above ORM to raw mysql query, it's grouing by primary key (row_1). I want to group by 'row_2' column . -
How to get the image path when applying UUID to the image file name
I've implemented a function that applies a UUID-based name to images in my Django project. The function is used as the 'upload_to' parameter for the ImageField in my 'Image' model. Here's the code: models.py def image_file_path(instance, filename): """Generate file path for new image""" ext = os.path.splitext(filename)[1] filename = f'{uuid.uuid4()}{ext}' return f'{instance.category.name}-{filename}' class Image(models.Model): """Image model""" user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) category = models.ForeignKey('category', on_delete=models.PROTECT, null=False, blank=False) image = models.ImageField( upload_to=image_file_path, null=False, blank=False ) results = models.TextField(default=None) created_at = models.DateTimeField(auto_now_add=True) def calculate_results(self): from .preprocessing.brain.preprocess_image import get_image_results print("Image URL:", self.image) # Returns the original image name self.results = get_image_results(self.image.path, target_size=(150, 150)) return self.results def __str__(self): return f"{self.category.name}-{self.created_at}" views.py @method_decorator(login_required(login_url='login'), name='dispatch') class CreateImageView(CreateView): model = Image form_class = ImageForm template_name = 'home.html' success_url = reverse_lazy('upload_homepage') def form_valid(self, form): form.instance.user = self.request.user form.instance.calculate_results() return super().form_valid(form) templates/home.html {% if image %} <img src="/static/media/{{ image.url }}"> {% endif %} However , when I try to access image.url in the home.html, I retrieve the original image name upon upload, not the one with the newly generated UUID. How can I modify this to obtain the correct name to display in the template? -
Slack message is not getting sent when python code is connected to celery
I have created a django project to upload articles. In that I have created a functionality where if the user did not upload article before 11:00 a.m. a message will be sent on slack to upload the article. The problem is that if I do not add the task to celery and execute it independently it works. But when combined with celery it does not. The celery worker gives message : [2024-02-06 20:49:49,015: INFO/MainProcess] Task account.tasks.check_articles_and_send_slack_message[fdc4f121-f123-4697-85c2-ce2bb57e6004] received [2024-02-06 20:49:49,017: INFO/MainProcess] Task account.tasks.check_articles_and_send_slack_message[fdc4f121-f123-4697-85c2-ce2bb57e6004] succeeded in 0.**strong text** but still no slack message is sent. This is the tasks.py which is in the accounts app: from celery import shared_task from django.utils import timezone from slack_sdk import WebClient from slack_sdk.errors import SlackApiError from writer.models import Article @shared_task def check_articles_and_send_slack_message(): articles = Article.objects.filter(date_posted__date=timezone.now().date()) for article in articles: if article.date_posted.time() < timezone.time(11, 0, 0): send_slack_message(article.user) def send_slack_message(user): client = WebClient(token='dummy-token') try: response = client.chat_postMessage( channel='#qa', text=f"Hi @{user.first_name}, please upload your article before 11:00 a.m. today." ) print("Slack message sent successfully") except SlackApiError as e: print(f"Error sending Slack message: {e.response['error']}") This is my celery.py which is in the project called cron: from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab … -
how to fetch data multiple times in React
I've been working a full stack app, in frontend I am using react,and for Backend I am using Django.... what I want to do is when the user login it will automatically render all the posts for users he is following, I got three models, Post, User, Following first I must fetch data to get all followings id's , and then I must fetch data again to get all Posts that is related to the followings ,, I tried to do this: Home.js const [following,setFollowing]=useState([]); const getFollowing = async()=>{ if(authToken){ console.log("TOKEN : ",authToken.access); try{ let response= await fetch(`${BASE_URL}profile/following/`,{ method:"GET", headers:{ "Content-Type":"application/json", "Authorization":`Bearer ${authToken.access}`, } }) let data= await response.json() setFollowing(data) }catch(error){ console.log(error); } } //for getting posts const getPost= async (num)=>{ let response= await fetch(`${BASE_URL}post/${num}`,{ method:"GET", headers:{ "Authorization":`Bearer ${authToken.access}`, "Content-Type":"application/json" }, }) let data= await response.json() console.log("Fetched Posts : ", data); } //loop to fetch all posts const getAllPosts=()=>{ let values=Object.values(following) values.map(value=>( posts.push(value[Object.keys(value)[0]]) )) var arrayLength=posts.length-1 while(arrayLength=>0){ getPost(posts[arrayLength]) arrayLength-=1 }} what I don't undersatand is how to fetch data multiple times, like if I have followings id's=[4,3] how to send them to getPost method -
Django application handling for multiple tabs
I have a django based application integrated with login. When I open the application for the first tab and login, this tab logs out automatically when the application is opened in another tab of the same browser. When the sessions created for each tab is separate, why this logs out the old tabs. And the behaviour is not consistent too. I tried to add the settings SESSION_EXPIRE_AT_BROWSER_CLOSE = True SESSION_SAVE_EVERY_REQUEST = True and this seems to be not working -
Django tables2: Skipping object from queryset possible?
A database table contains a column "body" of type "text". This column contains valid JSON data. Displaying data from this table using django-tables2 should skip objects depending on JSON elements in this text field. This filter is obviously not possible using the usual Django QuerySet mechanisms. Therefore, I want to skip an object before rendering it into the table. Something like "before_render_row()" with the possibility to e.g. "return None" to skip the object. Is there any possibility to do that? Thanks!