Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why are my forms not saved in the Database
I want that when entering data into rows, when pressing the button, they are saved.But this is not happening.I'll attach my code. I would be very grateful if you would point out any more errors in my code. [models.py](https://i.stack.imgur.com/jupBK.png) [Forms.py](https://i.stack.imgur.com/v08eU.png) [today.html](https://i.stack.imgur.com/K1Lrw.png) [views.py](https://i.stack.imgur.com/ran58.png) -
How to show boolean field from django-restframework in react native
I am using the django rest-framework in combination with react-native. And I try to show a BooleanField in the react-native app. Django model looks: cites = models.CharField(max_length=5, choices=CitesChoices.choices, default=CitesChoices.EMPTY, verbose_name="Cites") uis = models.BooleanField(default=False, verbose_name="UIS") serializer: class SubAnimalSerializer(serializers.ModelSerializer): category = serializers.SlugRelatedField( slug_field='name', queryset=Category.objects.all() ) class Meta: model = Animal fields = ['id', "cites","uis" ] read_only_fields = ['id'] and react: /* eslint-disable prettier/prettier */ import React, { createContext, useState } from "react"; import { List } from "react-native-paper"; import { Text } from "react-native"; export const AccordionItemsContext = createContext(); export const AccordionItemsProvider = ({ children }) => { const [citesExpanded, setCites] = useState(false); const [UISExpanded, setUIS] = useState(false); const accordionItems = (item) => { return ( <> <List.Accordion title="Cites" expanded={citesExpanded} onPress={() => setCites(!citesExpanded)}> <Text>{item.cites}</Text> </List.Accordion> <List.Accordion title="UIS" expanded={UISExpanded} onPress={() => setUIS(!UISExpanded)}> <Text>{item.uis}</Text> </List.Accordion> </> ); }; return ( <AccordionItemsContext.Provider value={{ accordionItems, }}> {children} </AccordionItemsContext.Provider> ); }; And all properties are working(displayed): cites. Except the uis propertie. Question: how to show the BooleanField(uis) on the screen? -
Redirecting with base 64 encoded image throwing No reverse Match error
I have a base 64 image captured in the browser and sent to Django view for processing. I passed the image to the API and depending on the response, I want to redirect to another page with the base 64 image as parameter but it's generating an error. here is the codes. @login_required def snap_rider(request): if request.method == 'POST': base64 image``your text image = request.POST['photo_data'] #Calculate the size of the image in bytes image_size = len(image) * 3 / 4 if image_size > 5 * 1024 * 1024: return render(request, 'rider_management/snap-rider.html', {'error_message': 'Image size is too large. Please select a smaller image.'}) search_request_data = { "images": [image], "min_score": 0.7, "search_mode": "FAST" } response = requests.post(SEARCH_URL, json=search_request_data, headers=headers) if response.status_code == 200: data = response.json() if data == []: return redirect('create_rider', image=image) else: print(f"Error: {response.status_code} - {response.text}") return render(request, 'rider_management/snap-rider.html') The view I'm redirecting to: @login_required def create_rider(request): image = request.POST.get('image') the urls.py path('create-rider/', views.create_rider, name='create_rider'), -
Google Vertex AI Prediction API Authentication
I have written a Django-Web app that takes in user input from a ModelForm as a Python Dict, then passes into Django backend to make prediction with Google Vertex AI Prediction API, then return the prediction to the web frontend for user. I have obtained a Service Account Key (JSON) for getting the credentials needed. However I am still facing 401 Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential The same code worked initially dated in 14/7/2023, yet it stopped working as of two days ago. from google.oauth2 import service_account from google.cloud import aiplatform from google.protobuf import json_format from google.protobuf.struct_pb2 import Value def model_predict(json_data): key_path = 'path-to-service-account-key.json' # Create a credentials object using your service account key file credentials = service_account.Credentials.from_service_account_file( key_path, scopes=['https://www.googleapis.com/auth/cloud-platform'] ) # Deployed Endpoint model configs project_id = "project_id" endpoint_id = "endpoint_id" instance_dict = json_data location = "us-central1" api_endpoint = "us-central1-aiplatform.googleapis.com" # The AI Platform services require regional API endpoints. client_options = {"api_endpoint": api_endpoint} # Initialise client that will be used to create and send requests. client = aiplatform.gapic.PredictionServiceClient(credentials=credentials, client_options=client_options) # Pass required configs and instance into AI Client instance = json_format.ParseDict(instance_dict, Value()) instances = [instance] parameters_dict = … -
Python Django Forms how to create object using multiple sub-objects?
I'm trying to create form that will allow me to create Meal object using multiple MealItem sub-objects which also have parameter of quantity, however up to this point I was able to create form and view combination that will allow me either to pick only one sub-object with one quantity Models: class Meal(models.Model): name = models.CharField(max_length=200) user = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(upload_to=meal_image_upload_to, blank=True, null=True) def calculate_total_macros(self): total_kcal = 0 total_carbohydrates = 0 total_fats = 0 total_proteins = 0 total_glycemic_load = 0 total_glycemic_index = 0 total_weight = 0 weighted_glycemic_index = 0 meal_items = self.mealitem_set.all() for meal_item in meal_items: quantity = meal_item.quantity food_item = meal_item.food_item total_weight += quantity total_kcal += food_item.kcal * quantity/100 #food items have nutrition facts per 100g total_carbohydrates += food_item.carbohydrates * quantity/100 total_fats += food_item.fats * quantity/100 total_proteins += food_item.proteins * quantity/100 total_glycemic_load += food_item.glycemic_load * quantity/100 total_glycemic_index += food_item.glycemic_index weighted_glycemic_index += food_item.glycemic_index * quantity if total_weight != 0: total_kcal_per_100g = round((total_kcal / total_weight) * 100, 2) total_carbohydrates_per_100g = round((total_carbohydrates / total_weight) * 100, 2) total_fats_per_100g = round((total_fats / total_weight) * 100, 2) total_proteins_per_100g = round((total_proteins / total_weight) * 100, 2) total_glycemic_load_per_100g = round((total_glycemic_load / total_weight) * 100, 2) else: total_kcal_per_100g = 0 total_carbohydrates_per_100g = 0 total_fats_per_100g = … -
python's django is having problems, but I don't know why and how to fix it
enter image description here enter image description here enter image description here I modified the variable according to chatgtp's suggestion, but I still don't understand what it means and the correct solution,I hope someone can give me some concrete steps -
Preprocessing Engine in Django
I'm developing a web application of Preprocessing engine in django. Basically, I want to provide an interface to user where user can upload their csv files to database. There should be a drop drown where user can see all their uploaded csv files. When the user selects any csv file from the menu, the corresponding data of that file will be shown. Also I want to provide some data cleaning and preprocessing methods to user like dropping columns, dropping and imputing null values, forward and reverse geocoding , binning etc. I want a little guidance about the approach of doing this project like a workflow of the application. I have studied numerous threads and articles but could not find anything relevant. The one approach I am trying is: The user uploads the csv file and the file is uploaded in file format in the database and I am reading that file using pandas and passing it to template in html format. Is that a correct approach? Any guidance, tips, recommendations will be appreciated. -
How to rename a file in Azure File Share using Azure Python SDK?
I am trying to rename a file in Azure File Share using the Azure python SDK. But the problem I'm facing is, it removes the file instead of renaming it. with directory_client.get_file_client(file_name=project_from_db.project_name) as rename_client: rename_client.rename_file(new_name=new_data['project_name']) Is anything wrong here? -
Django Channels : TypeError( TypeError: ProactorEventLoop is not supported, got: <ProactorEventLoop running=False closed=False debug=False>
I was trying to copy the tutorial in Django Channels Documentation. I am using Django 2.2.19 and Channels 2.1.2 But I'm having errors. It says File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\twisted\internet\asyncioreactor.py", line 61, in init raise TypeError: ProactorEventLoop is not supported, got: -
How to revoke the JWT 'access token' in Django?
Is there any way to revoke the JWT access token in Django? (currently, I am using the rest_framework_simplejwt, and I want to write the logout view) Is adding the access token(revoked ones) to a database table a good idea? There is a way to revoke the 'refresh token' in simplejwt docs, But I have not found anything about revoking 'access token' in simplejwt docs. -
Using multiple packaged django project in docker-compose
I have a project called demo1 running in the docker container(any virtual env). In this project first, I was using only one packaged Django project called test_be. To use this packaged Django project, in the docker-compose file, I have to set an environment variable DJANGO_SETTINGS_MODULE: 'test_be.test_be.settings'. That packaged django projects structure looks as follows. test_be |__utils/ |__someTestFolder |__test_be |__ __init__.py |__ asgi.py |__ urls.py |__ wsgi.py |__ settings.py |__ manage.py |__ __init__.py But now I want to use one more packaged Django project test_be_2 in the same project demo1. If I want to use test_be_2 in demo1, then i need to set the DJANGO_SETTINGS_MODULE for test_be_2. But for the env variable DJANGO_SETTINGS_MODULE I cannot keep on changing the values right. (Please assume that test_be_2 django project also has the same structure as test_be. Only the folder name is different, instead of test_be, it is test_be_2) So does anyone know how to deal with this scenario? Thank you -
Tried to update field review.Review.name with a model instance, Use a value compatible with CharField
I was trying to add a review using the function i created and this error occured.. this is my Review model in models.py which is in the app review class Review(models.Model): title=models.CharField(max_length=100) place=models.ForeignKey(Place,on_delete=models.CASCADE,null=True) location=models.CharField(max_length=100,default='place') photo=models.ImageField(upload_to='places') desc=models.TextField(max_length=3000,default=None) name=models.CharField(max_length=50,default=None) def __str__(self): return self.location this is the address href="{% url 'review:add_review' place.slug %}" this is the path from django.urls import path from review import views app_name="review" urlpatterns = [ path('add_review/<slug:pslug>',views.addreview,name='add_review'), ] this is the add review function in views.py def addreview(request,pslug): place=Place.objects.get(slug=pslug) if(request.method=="POST"): user=request.user title=request.POST['title'] review=request.POST['review'] photo=request.FILES['photo'] review=Review.objects.create(title=title,desc=review, name=user,photo=photo, place=place) review.save() return placedetail(request,pslug) else: pass return render(request,'addreview.html') what am i doing wrong and how can i fix it... -
Django: request.GET.get('x') does not fetch selected item in dropdown. Error: None
I have the combobox countries (def trip_selector) dependent on the combobox trips (def trips). In the comboboxes I display the item correctly. If I click on the button I would like to print the selected item in the textarea (def result). The problem is that I can't extract the selected item in the trips combobox, I get the error: None. I use selected = request.GET.get('trips') also because trips is the name in select name="trips" id="id_trip" in the trips.html page. The selected item to print does not send data, it only displays it. I can't figure out why it doesn't work. Can you help me please? IMPORTANT: i specify one important thing in case you want to help me: I don't want to move selected = request.GET.get('trips') inside the def test1() function or inside the def result() function, at most create another function if necessary. def test1 is just one of many functions I'm going to create, so it's pointless to move selected = request.GET.get('trips') into each function test1, test2, test3, test4, etc. These functions will be displayed in textarea (def result) which must remain only a viewer because it will display various functions (and not just one). views.py from django.shortcuts … -
Dynamic filtering on the FastAPI site
I need to implement filtering on the site, I use MongoDB. The thing is, I have multiple arrays. old_fliters, where you use different values of all filters, there are arrays of filters, where available filters should be available, when I had only two age and brand filters, then the following logic worked if brand and age were selected: in the catalog by brand announcement and age in the catalog by brand announcement or age when the filters became more than two of these, the logic stopped working, please help solve a specific problem, what kind of logic should be used, but massive filters are presented in bold (available for selection), the old_fliters array for comparison with filters, that is, what is not in the filters array, but is in the old_fliters array on the frontend is obscured. Here is a good example: I choose a material from cardboard, the country is China, and with such logic as above, the age remains 0+, which either China or cardboard has, but if you cross all three filters, there are no such products. from math import ceil from fastapi import HTTPException, APIRouter, Query route_catalog_test = APIRouter() from database import my_collection from enum import … -
Is it possible to disable datatables' default custom search builder draw?
My Django webapp uses datatables with serverside processing and custom search builder. I am trying to change the URL to include the query parameters from the searchbuilder for bookmarking purposes. Using the ajaxSucesss settings.url object and the HTML history.pushState method, I can get the necessary parameters and append them to the URL. The issue is, each time an ajax request is made, datatabels adds a "&&" followed by a deafault draw to the request. Is there a way to disable the default datatables draw? In the Django html template: $( document ).on( "ajaxSuccess", function( event, xhr, settings ) { // collect everything in the URL after the "?" draw_string = settings.url.split("dt-json/?")[1] // split the original URL at the "&&" and keep only the first half. // the second half is the default dt draw let query_string = draw_string.split("&&")[0] // if the datatable is filtered. if (draw_string.split('&&').length === 2 && !draw_string.split('&&')[1].includes("draw=1&")) { // replace the string with the second draw query_string = draw_string.split('&&')[1]; } url_params = "/?" + query_string // and replace the URL with the new URL without reloading the page. history.pushState(null, "", url_params) } ); In views, to to process the ajax request: def query_string_to_dict(query_string_arg): # When adding params … -
No backend data is publishing from fullcalendar in Django
I am attempting to use the fullcalendar package with Django for calendar implementation. I am able to display the calendar, create and save a model to the database, but I am having issues bringing it into the template. I can bring in context event information, as for bringing it onto the actual calendar, I am missing the target and hitting a wall. My belief is how I am calling on the URL to bring back the JSON response data. All assistance is appreciated models.py class CalendarEvents(models.Model): id = models.AutoField(primary_key=True) type = models.CharField(max_length=50, choices=EVENT_CHOICES) name = models.CharField(max_length=145,null=True, blank=True) location = models.CharField(max_length=100, null=True, blank=True) start = models.DateTimeField(null=True, blank=True) end = models.DateTimeField(null=True, blank=True) urls.py path("calendar", view=apps_calendar_view, name="calendar"), path('calendar/all_events/', view=apps_calendar_all_events, name='calendar.all_events'), views.py def apps_calendar_view(request): all_events = CalendarEvents.objects.all() context = { "events":all_events, } return render(request,'apps/apps-calendar.html', context) def apps_calendar_all_events(request): all_events = CalendarEvents.objects.all() out = [] for event in all_events: out.append({ 'type':event.type, 'title': event.name, 'location':event.location, 'id': event.id, 'start': event.start.strftime("%m/%d/%Y, %H:%M:%S"), 'end': event.end.strftime("%m/%d/%Y, %H:%M:%S"), }) print(out) return JsonResponse(out, safe=False) apps-calendar.html <div class="col-xl-9"> <div class="card card-h-100"> <div class="card-body"> <div id="calendar"> </div> </div> </div> </div> <script> import { Calendar } from '@fullcalendar/core' import dayGridPlugin from '@fullcalendar/daygrid' const calendarEl = document.getElementById('calendar') const calendar = new Calendar(calendarEl, { plugins: [ dayGridPlugin // … -
Django intermediate many-to-many model
I wonder if I can create intermediate model for many-to-many field without specifying related_name but rather just put ManyToManyField on both Models. I was watching some tutorial on Django ORM and instructor explicitly said we can't use ManyToManyField on both Models (while I think that is true if Django creates own table, I am not sure if it is if we specify custom intermediate model). So this is the code: class Category(models.Model): products = models.ManyToManyField("Product", through="CategoryProduct") name = models.CharField(max_length=255, unique=True) class CategoryProduct(models.Model): category = models.ForeignKey("Category", on_delete=models.CASCADE) product = models.ForeignKey("Product", on_delete=models.CASCADE) class Meta: unique_together = ("category", "product",) class Product(models.Model): categories = models.ManyToManyField("Category", through="CategoryProduct") attribute_value = models.ManyToManyField("AttributeValue", related_name="products") name = models.CharField(max_length=255, unique=True) I tested it with dummy data and this code works for me: p = Product.objects.get(id=1) c = Category.objects.get(id=1) p.categories.add(1, 2, 3) c.products.add(1, 2, 3) -
Serialize list of a specific field of Many To Many relation in Django
What I want is to have a list of a specific field from a ManyToMany relation instead of a list of dictionaries that the field is in. For example, with the following code, I get the result shown below # models.py from django.db import models class Bar(models.Model): title = models.CharField(max_length=255) class Foo(models.Model): title = models.CharField(max_length=255) bars = models.ManyToManyField(Bar, related_name="foos") # serializers.py from rest_framework.serializers import ModelSerializer from .models import Bar, Foo class BarSerializer(ModelSerializer): class Meta: model = Bar fields = ("title",) class FooSerializer(ModelSerializer): bars = BarSerializer(many=True) class Meta: model = Foo fields = ("title", "bars") # views.py from rest_framework.generics import ListAPIView from .serializers import FooSerializer from .models import Foo class FooAPIView(ListAPIView): queryset = Foo.objects.prefetch_related("bars") serializer_class = FooSerializer Result: [ { "title": "foo 1", "bars": [ { "title": "bar title 1" }, { "title": "bar title 2" }, { "title": "bar title 3" } ] }, { "title": "foo 2", "bars": [ { "title": "bar title 4" }, { "title": "bar title 5" }, { "title": "bar title 6" } ] }, { "title": "foo 3", "bars": [ { "title": "bar title 7" }, { "title": "bar title 8" }, { "title": "bar title 9" } ] } ] But what I … -
Connecting to AS400 with Django using ibm-db-django
I am trying to connect my newly created django project to an AS400 system that already has a lot of data stored on it. The only documentation I can find on how to configure your Django project is on this github page and goes over how to set up your virtual environment and get all necessary dependencies and versions. Currently I have my package versions set up according to that documentation as seen here Package Version ----------------- -------- asgiref 3.7.2 Django 3.2 ibm-db 3.1.4 ibm-db-django 1.5.2.0 pip 22.0.4 pyodbc 4.0.39 pytz 2023.3 regex 2023.6.3 setuptools 58.1.0 six 1.16.0 sqlparse 0.4.4 typing_extensions 4.7.1 My current python version is also Python 3.10.4. I also have the my database setting within my settings.py folder set up like this DATABASES = { 'default': { 'ENGINE' : 'ibm_db_django', 'NAME' : '_____', 'USER' : '_____', 'PASSWORD' : '_____', 'HOST' : '_____', 'PORT' : '_____', 'PCONNECT' : True, } } And I know all the values for these settings are in fact connect since I am able to connect to the AS400 system when using the PYODBC library which requires a connection string with the same data in order to access the AS400 system. # Define the … -
Advanced Python Stopwatch
I'm thinking about creating an advanced stopwatch as a Python project. The way I want it to work is like this: Stopwatch Starts If stopwatch paused a "rest" stopwatch begins When stopwatch is started again initial stopwatch begins and the rest stopwatch is paused. This cycle continues until stopwatch time is ended. I haven't started writing this because I'm unsure of how it would work. I'm not sure how to manage the stopwatch times as they are pausing and starting. If it makes any difference I'm thinking of implementing this into a Django app. Thanks, Mitchell -
Could not get Response when i uplaod video on server in python django
I am having a problem with uploading videos using the Django rest framework. When I upload locally, it works fine and stores in S3. However, when I upload through the server, it does not respond. Even when I change the timeout limit of the reverse proxy, Postman gives me the error "could not get a response." I have tried all possible solutions but still need guidance from the developers. -
"Database Error when Deploying Django Project with Free MongoDB on Render Testing Platform
enter image description here Hello, I'm having issues using the free MongoDB database in a Django project. I managed to create a simple CRUD (Create, Read, Update, Delete) to list and add tasks. However, when I deploy the project to the free testing platform 'Render' and try to add a task there, it doesn't work and gives a database error. enter image description here enter image description here Perfectly Functional in Testing Environment, but Fails Upon Deployment on Render enter image description here requirements : Django>=3.2.4 djangorestframework>=3.12.4 djongo>=1.3.6 I dont know how to resolve this. -
Django separate own log from library log?
I have django project which print the log such as below. import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) . . . . logger.debug("test") However I am using boto3 library. so, there are many debugging information on console from boto3 libraru. I want to check my own log message. Is there any good method to do this?? my debug setting is like this below. DEFAULT_LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'formatters': { 'django.server': { '()': 'django.utils.log.ServerFormatter', 'format': '[%(server_time)s] %(message)s a', } }, 'handlers': { 'console': { 'level': 'INFO', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', }, 'django.server': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'django.server', }, 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django': { 'handlers': ['console', 'mail_admins'], 'level': 'INFO', }, 'django.server': { 'handlers': ['django.server'], 'level': 'INFO', 'propagate': False, }, } } -
How to show a user's favourites on a profile page using Django
I'm relatively new to Django and am attempting to build a website where a user can view products and favourite them. I then want the user to be able to login and see their list of favourites. FYI I've largely been using/following this django-blog tutorial to create this: https://www.youtube.com/playlist?list=PLCC34OHNcOtr025c1kHSPrnP18YPB-NFi I currently have two apps setup; Products and Customers. In the Products app I have a model called Product with a field likes which is a ManytoMany field. I've got the like/unlike button all setup, but I'm just a bit confused about how to actually pull all the liked products attached to a user. Any help much appreciated! Code below... Product model: class Product(models.Model): created_on = models.DateTimeField(auto_now_add=True) main_image = CloudinaryField('image', default='placeholder') item_name = models.CharField(max_length=50, unique=True) slug = models.SlugField(default="", null=False) price = models.DecimalField(max_digits=8, decimal_places=2) category = models.CharField(max_length=50) description = models.TextField(default='placeholder', blank=True, max_length=1000) colours = models.TextField(default='Ivory', blank=True, max_length=500) sizes_avail = models.TextField(default='Enquire in store', blank=True, max_length=500) likes = models.ManyToManyField(User, related_name='blog_post') def __str__(self): return self.item_name Customer model: lass Customer(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) profile_pic = CloudinaryField('image', default='placeholder') date_of_wedding = models.DateField(default='2024-12-31') website_url = models.CharField(max_length=500, null=True, blank=True) def __str__(self): return str(self.user) def get_absolute_url(self): return reverse('home') Views to like/unilike product: def LikeView(request, pk): product = get_object_or_404(Product, id=request.POST.get('product_id')) … -
accesing many to many fields in django
i am trying to build a clothes online store as a fun side project while studying django, i have products each of these products has multiple instances where each instance has a color and a size, like one usually sees in a clothes store, i am using many to one relationship to represent the relation between product and its multiple instances also, i am using many to many relationship to represent the relation between each instance and its color and size because many instances of a product could have many colors and a color could have many products, the same goes for the size. i have tried many solutions that i have found online but none have worked, here is my implementation. model.py class Size(models.Model): size_name = models.CharField(max_length=10) def __str__(self): return self.size_name class Color(models.Model): color_name = models.CharField(max_length=20) def __str__(self): return self.color_name class Product(models.Model): product_name = models.CharField(max_length=100) sub_category = models.ForeignKey(Sub_category, on_delete=models.CASCADE) price = models.PositiveIntegerField(default=0) def __str__(self): return self.product_name class productInstanceDetail(models.Model): product = models.ForeignKey( Product, related_name="product_instance", on_delete=models.CASCADE ) size = models.ManyToManyField(Size, related_name="product_instance_size") color = models.ManyToManyField(Color, related_name="product_instance_color") in_stock = models.PositiveBigIntegerField(default=0) sold = models.PositiveBigIntegerField(default=0) def __str__(self): return self.product.product_name views.py def product_detail_view(request, category_id, sub_category_id, pk): template_name = "hareswear/product.html" category = get_object_or_404(Category, id=category_id) sub_category = get_object_or_404(Sub_category, …