Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Integrate Sphinx documentation in Django
I've created the documentation for a webpage using Sphinx. The index.html generated via Sphinx is saved in a html folder. I'm not sure how to integrate the index.html and display on webpage content from Django. Currently, a link has been provided and it redirects to the documentation page. I would like to know how to display the page directly. For example, -
Console error 'Uncaught ReferenceError: React is not defined' when using Rollup.js + React 18
I am getting this console error in the Chrome browser index.tsx:13 Uncaught ReferenceError: React is not defined at index.tsx:13:2 I am really struggling to figure out how to get Rollup.js to work with React. I've been able to write a good-sized app in pure js using Rollup.js, but I want to start using React with it now. I'm not sure how to resolve this issue ; the code simply won't run in the browser yet I have no compilation issues. I've done much searching on this topic and none of the suggestions work. Any help would be appreciated! I am compiling to bundle.js using rollup -c -w The output from rollup is rollup v3.6.0 bundles src/ts/index.tsx → resources/public/js/bundle.js... LiveReload enabled created resources/public/js/bundle.js in 1.1s [2023-01-24 01:11:33] waiting for changes... My rollup.config.js looks like import typescript from '@rollup/plugin-typescript'; import { nodeResolve } from '@rollup/plugin-node-resolve'; import livereload from 'rollup-plugin-livereload'; import babel from '@rollup/plugin-babel'; export default { input: 'src/ts/index.tsx', output: { file: 'resources/public/js/bundle.js', format: 'iife', sourcemap: 'inline', inlineDynamicImports: true, globals: { "react/jsx-runtime":"jsxRuntime", "react-dom/client":"ReactDOM", "react":"React"}, }, external: [ 'react', 'react/jsx-runtime','react-is', 'react-dom/client','react-dom'], watch: true, plugins: [typescript(), nodeResolve(), livereload(), babel({ babelHelpers: "bundled", exclude: 'node_modules/**', presets: [ ["@babel/preset-react", {"runtime": "automatic"}] ] })] }; My tsconfig.js { "compilerOptions": … -
Is there any way I can delete all the rows from database before altering the model in django?
I want to alter my model but before doing so I want to delete all the records from my database, is there any dajngo ORM query for doing that cuz I don't want to do it manually. Thanks. I tried to alter my model but when I migrated the changes an error occured. it was a long error but the last line was this. File "C:\\Users\\ALI SHANAWER.virtualenvs\\PiikFM-App-Backend-O_dKS6jY\\Lib\\site-packages\\MySQLdb\\connections.py", line 254, in query \_mysql.connection.query(self, query) django.db.utils.OperationalError: (3140, 'Invalid JSON text: "Invalid value." at position 0 in value for column '#sql-45_2d01.qbo_class'.') any one knows what this is? -
Child form instance in Django
As a beginner in a contact list project I could not pass the instance of the contact profiles to the phone list form. When I want to add several phone numbers to a person I need the person's instance to be loaded to the add-phone form. models.py class newuser(forms.ModelForm): class Meta: model= contact_names fields='__all__' class newphone(forms.ModelForm): class Meta: model=contact_phone fields=['person','typep','phone'] views.py def user(request): form=newuser() if request.method =='POST': form=newuser(request.POST) if form.is_valid(): form.save(commit=True) return redirect('contacts') return render(request,'apptwo/form_page.html',{'form':form}) def addphone(request,pk): ps=contact_names.objects.get(id=pk) form=newphone(instance=ps) if request.method =='POST': form=newphone(request.POST) if form.is_valid(): form.save(commit=True) return redirect('contacts') return render(request,'apptwo/form_page2.html',{'form':form}) forms.py class newuser(forms.ModelForm): class Meta: model= contact_names fields='__all__' class newphone(forms.ModelForm): class Meta: model=contact_phone fields=['person','typep','phone'] -
how to insert daily average of a column into another column of another table(postgresql)
I have a machine that sends data every 3 minutes and i store that in a table called "machine_data" in postgresql. i need to get 10 minutes ,hourly,daily, monthly and yearly average of data column and store that in another table with columns of ( 10minutes_avg,hourly_avg ,daily_avg , ...) for these periodic tasks i wanted to use pgagent in postgresql but i didn't know how to write the code. note1: i have datetime field(2023-01-01 9:42:10+3:30) note2: additional note: i use django for getting and storing data , and i used many modules for scheduled tasks but i didn't get good results. thanks. -
WebSocket Django Python
I have to add real time data update in my Django project.I have to send data from one project and receive it in another project. I would like to add web socket in my first project and send data from it and listen that request in another project using Javascript to show real time update on dashboard. How is it possible to send data when we call an function from first project using web socket and listen that request in another project to update data . Thanks I have created Web socket connection in my first project but got stucked while sending data from that connection . We need to send data when an function call . -
templates does not show anything in react and django
I am trying to use react and django together and when I dont use Browser Router in react, the single page template loads perfectly but after adding route in App.js frontend is blank. folder structure -- Django_React -- frontend -- urls.py -- views.py --src -- templates -- index.html here is my urls.py urlpatterns = [ path('/login',indexView), re_path(r'^(?:.*)/?$',TemplateView.as_view(template_name='index.html')), ] App.js import React, { Component } from "react"; import ReactDOM from "react-dom/client"; import { BrowserRouter, Routes, Route } from "react-router-dom"; import Index from "./Home/index"; import Login from "./auth/Login"; const App = () => { <BrowserRouter> <Routes> <Route path="">element={<Index />}</Route> <Route path="/login"> element={<Login/>}</Route> </Routes> </BrowserRouter>; }; export default App; const root = ReactDOM.createRoot(document.getElementById("root")); root.render(<App />); This is webpack.config.js const path = require("path"); const webpack = require("webpack"); module.exports = { entry: "./src/index.js", output: { path: path.resolve(__dirname, "./static/frontend"), filename: "[name].js", }, module: { rules: [ { test: /\.js|.jsx$/, exclude: /node_modules/, use: "babel-loader", }, { test: /\.css$/, exclude: /node_modules/, use: ["style-loader", "css-loader"], }, ], }, optimization: { minimize: true, }, plugins: [ new webpack.DefinePlugin({ "process.env": { NODE_ENV: JSON.stringify("development"), }, }), ], }; If I remove Browser Router and return a <div>React</div>, I can see it on frontend but Browser Router does not work. I also recieve … -
Custom Validate function is not being called inside perform_create function in DRF
This is my code. class MyViewSet(ModelViewSet): serializer_class = MySerializer queryset = MyClass.objects.all() def get_serializer_class(self): if request.user.is_superuser: return self.serializer_class else: return OtherSerializer def perform_create(self, serializer): if request.user.is_superuser: if serializer.is_valid(): serializer.save(organization=self.request.user.organization) else: employee = Employee.objects.get(user=self.request.user) serializer.save(employee=employee, organization=self.request.user.organization) This is my Serializer: class MySerializer(serializers.ModelSerializer): class Meta: model = models.MyClass def validate(self, data): employee = data.get('employee') members = Team.objects.get(id=team.id.members.all()) if employee not in members: raise serializers.ValidationError('Invalid') return data The issue is, My custom validate function is not being called when I call it inside perform_create() in my ViewSet. What might be the issue? -
how i change the positions of the anwsers
I have a Quiz-Game and wanna change the positions of the answer. How i can fixed that? I've tried a few things but unfortunately nothing worked html {% for q in questions %} {% if q.kategorie == category and q.flaag == True %} {% if questions.has_next %} <br/> <div class="flex-container"> <div class="container1"> <div class="position_startButton"><button type="submit" name="next" value="{{q.question}}" class="nächstefrage_btn">Nächste Frage!</button></div> <div class="game_options_top"> <div class="option"> <p><button class="option_btn" name="next" value="{{q.op1}}" formaction="{% url 'quiz' %}?page={{ questions.next_page_number }} " type="submit">A: <span id="option_span">{{q.op1}}</span></button></p> </div> <div class="option"> <p><button class="option_btn" name="next" value="{{q.op2}}" formaction="{% url 'quiz' %}?page={{ questions.next_page_number }} " type="submit">B: <span id="option_span">{{q.op2}}</span></button></p> </div> </div> <div class="game_question"> <h1 class="display_question">{{q.question}}</h1> </div> <div class="game_options_bottom"> <div class="option"> <p><button class="option_btn" name="next" value="{{q.op3}}" formaction="{% url 'quiz' %}?page={{ questions.next_page_number }} " type="submit">C: <span id="option_span">{{q.op3}}</span></button></p> </div> <div class="option"> <p><button class="option_btn" name="next" value="{{q.op4}}" formaction="{% url 'quiz' %}?page={{ questions.next_page_number }} " type="submit">D: <span id="option_span">{{q.op4}}</span></button></p> </div> </div> </div> <div class="menü"> <button class="menü_button"><i class="fa fa-bars" aria-hidden="true"></i><b> Menü</b></button> <div class="items"> <a href="{% url 'Example_dashboard' %}"> <i class="fa-solid fa-house"></i> Startseite </a> <a href="{% url 'Example_fragenkatalog' %}"> <i class="fa-solid fa-pen"></i> Fragenkatalog </a> <a href="{% url 'statistics' %}"> <i class="fa-solid fa-trophy"></i> Statistik </a> <a href="{% url 'settings' %}"> <i class="fa-solid fa-gear"></i> Einstellungen </a> <a href="{% url 'logoutUser' %}"> <i class=></i> Log-Out </a> </div> </div> … -
How do I get a Django redirect to work properly when updating my database?
I can't get my Django redirect to work correctly after updating a bicycle in my Django app. When I use my update_bike view and update the bicycle profile, if my redirect is just to '/bikes', I'm taken back to the bicycle collection/bicycles owned. But when I try and redirect back to the profile of the current bike I'm editing, I get this error that my return pathway doesn't match any of the url patterns. I've pasted the function code here: def bikes_update(request, bike_id): if request.method != 'POST' or 'user_id' not in request.session: return redirect("/") this_bike = Bike.objects.filter(id=bike_id).update( name = request.POST['bike_name'], model = request.POST['model_id'], ) return redirect('/bikes') return redirect('/bikes/<int:bike_id>') return redirect('/bikes/<int:bike_id>/') I obviously comment out the bottom two redirects and the ('/bikes') works fine, it's trying to get back to the current bike profile that doesn't work and gives me the error. I'm able to update the bicycle profile correctly, so it's something to do with this redirect, but I don't get it. I don't understand how line 12 in my screen snippet and the current path (both highlighted in the image), aren't the same/don't match. -
Django while running the server ModuleNotFoundError: No module named 'customer data'
I'm using django to make an API that connects to another one to get some data and update some values. The idea is that the api can be executed from a CLI through commands like upgrade customer_id target_subscription. Before making the CLI file, the api works perfectly if you make requests to it (for example using vs code's thunder client). Once I make the CLI file and try to test I get the following error: Im running the code on Windows 10 and WSL bash. I create the django project using: django-admin startproject customer_data cd customer_data python manage.py startapp customer My file/folder strucutre is this: My API code: class UpdateCustomerSubscriptionView(APIView): def extractCustomerData(self, customer_id): """ Input: A customer id Output: The customer data """ customer = None try: response = requests.get(f'{API_LINK}{customer_id}/') customer_data = response.json() customer = Customer(**customer_data) except: return Response({"error": "The ID does not exist or is badly formated."}, status=500) return customer def upgrade_or_downgrade(self, customer_id, target_subscription): """ Input: A customer id and a target subscription level Output: The updated customer data """ # Validate that the id is not null if customer_id is None: return Response({"error": "The customer id is null."}, status=500) # Validate that the new subscription is not null … -
ManyToManyField constraints
Django ORM seems not to permit constraints on ManyToManyField. class Component(ComponentMetaData): class Type(models.IntegerChoices): Part = 0 Components = 1 type = models.IntegerField( choices=Type.choices, ) components = models.ManyToManyField( "self", blank=True, null=True, ) def clean(self) -> None: if self.type == 0 and self.components: raise ValidationError("Parts could not have components.") return super().clean() class Meta: constraints = [ models.CheckConstraint( check=( Q(type = 0) & Q(components__isnull = True) ) | ( Q(type = 1) # componenets only fields ), name = "components_enum" ) ] Migration attempt with the above model results in the error below; ERRORS: myapp.Component: (models.E013) 'constraints' refers to a ManyToManyField 'components', but ManyToManyFields are not permitted in 'constraints'. Does anyone know why this is not permitted and what should one do if one would like to keep a ManyToManyField empty on some condition based on the values of other fields? -
react oauth2 authentication not working when request is sent
i am trying to integrate social authentication for my react site which i am using drf for the server side, here i am using react-oauth2/google library because the react-google-login npm package seem to be depreciated, so unlike react-google-login that once a request is sent to google from the client side it return an accesstoken and refresh token that is automatically sent to django's end through a callback requesting django authtoken and also sending/comparing users data if any. react-oauth2/google on the other hand tend to only give me just one token called code. i sent it to my server side and it returned wrong credential. error i am using social_django for my drf server side AUTH.JS const GoogleLoginFunc = useGoogleLogin({ flow: 'auth-code', onSuccess: async (codeResponse) => { console.log(codeResponse); // const tokens = await axios.post( // 'http://localhost:3000/auth/google', { // code: codeResponse.code, // }); // console.log(tokens); SocialGoogleLoginFunc(codeResponse.code) }, onError: errorResponse => console.log(errorResponse), }); <GoogleLogin onSuccess={GoogleLoginFunc} // onSuccess={credentialResponse => { // console.log(credentialResponse.credential); // SocialGoogleLoginFunc(credentialResponse.credential) // }} onError={() => { console.log('Login Failed'); }} useOneTap />; GOOGLEAUTH.JS const SocialGoogleLoginFunc=(accesstoken,app_id,app_secret)=>{ // console.log(`MY CREDENTIALS ${app_id},${app_secret}`) // let client_id='nILBGJCOSiaLKDyRZeFpHmUoyDw0PgChrkEGzjkj' // let client_secret='fkUSbr5mtR6oIX3osX51zS1ycbWOfNWGvEjhhKwVQvBb3rJ8gRN1BW2gkFMiPBfBKq3437IC3joXQUEFxPRs1PSXfSgKehOCwoRJoNgjtAzI6ZXwdjyX3RyZfTKKb8hE' // console.log(client_secret.includes(' ')) // http://127.0.0.1:8000/client/auth/convert-token // grant_type:"convert_token", // client_id: client_id, // client_secret: client_secret, // backend:"google-oauth2", // token:accesstoken … -
Django template does not exist?
When I am trying to deploy to railway my project, i get the error mentioned above. This is one log that could give more insight? django.template.loaders.filesystem.Loader: /app/client/client/public/index.html (Source does not exist) Here is my project.settings.py file: from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = True TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'client') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'project.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'game-api', 'HOST': 'localhost', 'PORT': 5432 } } ROOT_URLCONF = 'project.urls' STATIC_URL = '/static/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' import dj_database_url db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' project.views.py file: from django.shortcuts import render def index(request): return render(request, 'build/index.html') My files: -
get chosen dropdown option from Django filter
I am new to the Django and searched a lot about my problem, but could not use any of the solution. I am using Django filter to select some of the options available and use them to recreate and show my table in the HTML output. I have created the databse and the query, and it partially works. Whenever I try to run the app, I get the IDs of the values from the database and actual values are not returned. I am using Django 2.2.16 filters.py import django_filters from .models import * class OrderFilter(django_filters.FilterSet): class Meta: model = Order fields = '__all__' model.py `from django.db import models class CodeName(models.Model): code_name = models.CharField(max_length=200, null=True) def __str__ (self): return self.code_name class FileName(models.Model): file_Name = models.CharField(max_length=200, null=True) def str (self): return self.file_Name class Order(models.Model): codename = models.ForeignKey(CodeName, null=True,on_delete = models.SET_NULL) filename = models.ForeignKey(FileName, null=True,on_delete = models.SET_NULL) ` views.py def stats1(request): import pandas as pd data = { "calories": [420, 380, 390], "duration": [50, 40, 45] } #load data into a DataFrame object: NoneConceptsTable1 = pd.DataFrame(data) myFilter = OrderFilter() print(df) print('stats') print(len(NoneConceptsTable1)) if len(NoneConceptsTable1)>0: print("Yes, the lenght of NoneConceptsTable1 was geater than 1") pos = NoneConceptsTable1.Frequency.values codeName_instance = list(NoneConceptsTable1.Name.values) # print(codeName_codeName_instance[i]instance) % I … -
Django, how to get current request method? request is not working in my views.py
I'm new to Django. I'm trying to get my current request method to see if it is "POST" method. But I got error message says: Unresolved reference 'request' I tried to import request, but I don't know which one is correct. import choices Thanks for your help! Kind regards, Xi -
How to get data from both sides of a many to many join in django
Let's say I have the following models: class Well(TimeStampMixin, models.Model): plate = models.ForeignKey(Plate, on_delete=models.CASCADE, related_name="wells") row = models.TextField(null=False) column = models.TextField(null=False) class Meta: unique_together = [["plate", "row", "column"]] class Antibiotic(TimeStampMixin, models.Model): name = models.TextField(null=True, default=None) class WellConditionAntibiotic(TimeStampMixin, models.Model): wells = models.ManyToManyField(Well, related_name="well_condition_antibiotics") volume = models.IntegerField(null=True, default=None) stock_concentration = models.IntegerField(null=True, default=None) dosage = models.FloatField(null=True, default=None) antibiotic = models.ForeignKey( Antibiotic, on_delete=models.RESTRICT, related_name="antibiotics" ) In plain english, there are a set of wells and each well can have multiple and many different types of antibiotics. I'm trying to fetch the data of a given well and all of the antibiotics contained inside it. I've tried WellConditionAntibiotic.objects.filter(wells__id=1).select_related('antibiotic') which gives me this query: SELECT "kingdom_wellconditionantibiotic"."id", "kingdom_wellconditionantibiotic"."created_at", "kingdom_wellconditionantibiotic"."updated_at", "kingdom_wellconditionantibiotic"."volume", "kingdom_wellconditionantibiotic"."stock_concentration", "kingdom_wellconditionantibiotic"."dosage", "kingdom_wellconditionantibiotic"."antibiotic_id", "kingdom_antibiotic"."id", "kingdom_antibiotic"."created_at", "kingdom_antibiotic"."updated_at", "kingdom_antibiotic"."name" FROM "kingdom_wellconditionantibiotic" INNER JOIN "kingdom_wellconditionantibiotic_wells" ON ( "kingdom_wellconditionantibiotic"."id" = "kingdom_wellconditionantibiotic_wells"."wellconditionantibiotic_id" ) INNER JOIN "kingdom_antibiotic" ON ( "kingdom_wellconditionantibiotic"."antibiotic_id" = "kingdom_antibiotic"."id" ) WHERE "kingdom_wellconditionantibiotic_wells"."well_id" = 1 This gives me all of the antibiotic data, but none of the well data. So I tried Well.objects.filter(pk=1).select_related(['well_condition_antibiotics', 'antibiotic']).query which errored. How can I generate a django query to include all well data and all well antibiotic data? -
Combing two querries using Q objects in Django?
I have defined following view: class SearchListView(ListView): template_name = "movies/search_list.html" # overwriting the get_queryset function to customize the queryset def get_queryset(self) -> list: query = self.request.GET.get("q") if query: movies = list( filter( lambda x: unidecode(query.lower()) in unidecode(x.title).lower(), Movie.objects.all(), ) ) actors = list( filter( lambda x: unidecode(query.lower()) in unidecode(x.name).lower(), Actor.objects.all(), ) ) # use the chain function to combine the querysets return list(chain(movies, actors)) else: # return an empty list if no query is provided return [] And it is working as I want it to, however I have been trying to combine the querries into one querry using Q objects, but did not succeed. Do you think it's even possible in this case? -
"ImproperlyConfigured at /plan-a-trip/ Empty static prefix not permitted" error in Django
So I was trying to add a form webpage to my Django application, but I got this error: ImproperlyConfigured at /plan-a-trip/ - Empty static prefix not permitted I have absolutely no idea what this means, but these are what my files look like: urls.py: from django.conf import settings from django.conf.urls.static import static from django.urls import path, include from itineraries.views import * from .views import * urlpatterns = [ path('admin/', admin.site.urls), path('sights/', include('sights.urls')), path('', index, name="index"), path('plan-a-trip/', createItinerary.as_view(), name="create-itinerary") ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) My settings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'i1kf*^g1+dt*8n9bgcl80$d!970186x(x(9z2)7dfy1ynlxixn' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['travelApp-kool4-env.eba-pfvej56m.us-west-2.elasticbeanstalk.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'sights.apps.SightsConfig', 'itineraries.apps.ItinerariesConfig' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'travelApp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'static')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] TEMPLATE_DIRS = ( '/home/django/myproject/templates', ) WSGI_APPLICATION = … -
Django looping through model data but need to pass additional list data
I am posting data from database using Model, which displays fine. But I am now need to pass an additional list (POST.getlist) variable "mylist" along with the model object data, but I dont know how to dynamically loop through it as the "mylist" requires an index number such as "mylist.0", "mylist.1" and so on. html page {% for employee in employees %} <tr> <td>{{ mylist.X }}</td> <td>{{ employee.USER }}</td> <td>{{ employee.MATERIAL }}</td> <td>{{ employee.C }}..... models.py from django.db import models class Materials(models.Model): ID = models.AutoField(primary_key=True) USER = models.CharField(max_length=30) MATERIAL = models.CharField(max_length=30) C = models.FloatField(max_length=5) MN = models.FloatField(max_length=5) V = models.FloatField(max_length=5) CR = models.FloatField(max_length=5) P = models.FloatField(max_length=5) S = models.FloatField(max_length=5) AL = models.FloatField(max_length=5) CU = models.FloatField(max_length=5) SI = models.FloatField(max_length=5) MO = models.FloatField(max_length=5) NI = models.FloatField(max_length=5) CO = models.FloatField(max_length=5) NB = models.FloatField(max_length=5) TI = models.FloatField(max_length=5) W = models.FloatField(max_length=5) PB = models.FloatField(max_length=5) SN = models.FloatField(max_length=5) MG = models.FloatField(max_length=5) AS = models.FloatField(max_length=5) ZR = models.FloatField(max_length=5) B = models.FloatField(max_length=5) FE = models.FloatField(max_length=5) class Meta: db_table = "materials" view.py def selection(request): current_user = request.user boxlist = request.POST.getlist('selectbox') weightlist = request.POST.getlist('weight') mylist = list(filter(None, weightlist)) employees = Materials.objects.filter(USER=current_user, ID__in=boxlist) return render(request,"selection.html",{'employees':employees, 'mylist':mylist}) -
how to find available quantity of products Django ORM
Inaccurate results using Django ORM for calculating available quantity of products. I'm facing a problem in finding the available quantity of products using the Django ORM. I've written a code that uses the ORM to annotate the queryset with the quantity produced, quantity sold and available quantity fields, but the results are inaccurate. However, when I use raw SQL to perform the same calculations, the results are accurate. I need help understanding why the ORM code is not working as expected and how to fix it. Django ORM code for finding quantities of products: def get_queryset(self): queryset = super().get_queryset() queryset = queryset.annotate(Quantity_Produced=Sum(F('production__qunatity_produced'))) queryset = queryset.annotate(Quantity_Sold=Sum(F('sales__qunatity_delivered'))) queryset = queryset.annotate(Quantity_available=Sum(F('production__qunatity_produced')) - Sum(F('sales__qunatity_delivered'))) return queryset The Output (Inaccurate): { "product_id": 1, "product_name": "Product 1", "weight": 10.0, "Quantity_Produced": 6300.0, "Quantity_Sold": 2600.0, "Quantity_available": 3700.0 } ORM's Raw SQL method for finding the available quantity of products: def get_queryset(self): queryset= models.Products.objects.raw(''' SELECT *, (SELECT SUM(q.qunatity_produced) FROM production q WHERE q.product_id = p.product_id) AS Quantity_Produced , (SELECT SUM(s.qunatity_delivered) FROM Sales s WHERE s.product_id = p.product_id) AS Quantity_Sold, sum((SELECT SUM(q.qunatity_produced) FROM production q WHERE q.product_id = p.product_id) -(SELECT SUM(s.qunatity_delivered) FROM Sales s WHERE s.product_id = p.product_id))as Quantity_available FROM products p group by Product_id order by Product_id ''') return … -
How can I replace a substring with a string in django nested in a JSONField?
If I have a model: class MyModel(Model): properties = JSONField() And I have instances where the properties look like this: {"a": {"b": ["some text A"]}} {"a": {"b": ["some other text A"]}} {"a": {"b": ["some text A"]}} How do I bulk-update these model instances, replacing the string "A" with "B"? I would assume it would be something like this: MyModel.objects.update( properties=Func( F("properties"), Value("{a,b,0}"), Replace(F("a__b__0"), Value("A"), Value("B")), function="jsonb_set", ) ) It doesn't quite work though. I think I'm just missing a proper reference to the field (F("a__b__0") is invalid). -
How can I filter the value selected in a Django model form based on a certain data condition?
Good day! I have a model table in order to add data to this model. [Citizen_2] I would like users to enter their country of residence first, it's like a simple one-field form. And then a form of two fields - where it is proposed to select the country of residence from the value already entered in the (name_country) field. For example, I have users added three countries there. Then they add the cities - for those respective countries. In the drop-down form field, select a country and write down your city there. And send the data to the model table. It is necessary that the data be saved in such a way that the city corresponds to the country to which the user wrote it down in the form. This is then used in the form to fill in the data. By country and its corresponding city in the main form. How can I make it in the form of a model [Citizen_2] the city of the corresponding country was chosen. From data previously filled in by users? Any information or help would greatly save me, please. Citizen_2 class Country(models.Model): name_country = models.CharField(max_length=150, db_index=True) def __str__(self): return self.name_country class … -
Creating An Application To Generate Files For eSignature
I'm currently working on a phone app an done of the features I need to create is the ability to generate a PDF that will need to be emailed to another person for them to eSign it. Is there a library for this? I'm using React Native on the frontend and Django/Python on the backend. Any suggestions would be appreciated. Thank you -
why can i not add object into field rest_framework
I want to add some pebbles but I am getting this error from the serializer { "user": [ "Incorrect type. Expected pk value, received str." ] } Of course, I read the documentation about serializers and relation but I still don't understand.. newbie in django Here my models class UserData(AbstractUser): username = None name = models.CharField(max_length=100, unique=True) email = models.EmailField(max_length=100, unique=True) date_joined = models.DateTimeField(auto_now_add=True) pseudo = models.CharField(max_length=200,unique=True) hashtag = models.CharField(max_length=200, unique=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = "pseudo" REQUIRED_FIELDS = ['name','hashtag','email'] def __str__(self): return self.name class Pebbles(models.Model): image = models.CharField(max_length=200) user = models.ForeignKey(UserData, related_name="pebbles",on_delete=models.CASCADE) class Meta(): unique_together = ["id","user"] I can get a list of pebbles from that view it works. class PebblesView(generics.ListCreateAPIView): permission_classes = [IsAuthenticated] authentication_classes = [JWTAuthentication] serializer_class = PebblesSerializer def get_queryset(self): return Pebbles.objects.all() def create(self, request): serializer = PebblesSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) I can register a user with my UserSerializer. I have the same logic for pebbles but it doesn't work. In the Django shell, I can add pebbles just like this. class UserSerializer(serializers.ModelSerializer): pebbles = serializers.StringRelatedField(many=True) class Meta: model = UserData fields = ["id", "pseudo", "hashtag","email", "name", "password","pebbles"] def create(self, validated_data): user = UserData.objects.create( …