Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Check if the "tag" from the flash message match inside the template
I am currently attempting to create a global message using tags from Django messages. Globaly: I would like to use the tags from the messages to determine if the message is a warning, success, or something else. for example, my message inside my view)* : messages.success(self.request, f'Success, your account has been deleted', 'success') my template : <p> {% if message.tag == success %}Success {% elif message.tag == welcome %}Welcome {% else %}Warning {% endif%} </p> Alternatively, is it possible to directly display the tag string in my template, without condition ? -
Django postgresql adminer import sql file syntax error
Firstly I exported the database in sql file and without changing anything, I tried to import same sql file to empty postgresql database using adminer. But I get some errors and don't know what is the problem Any ideas? -
Django admin download reportlab PDF
I use this guide(https://docs.djangoproject.com/en/4.1/howto/outputting-pdf/) to download PDF. It works on regular public page. But I am trying to get it working in the admin for a specific model and have model data on the PDF. In my admin I have: cakes/models.py from django.db import models class Cake(models.Model): date = models.DateField("Date ordered") name = models.CharField() def pdf_link(self): from django.utils.html import format_html return format_html("<a href='pdf/%s/'>Download PDF</a>" % self.pk) Dislay the PDF link in the django admin. The link is showing up in admin, it just doesn't link to the PDF yet(pass pdf_link)... cakes/admin.py from django.contrib import admin from .models import Cake @admin.register(Cake) class OrderAdmin(admin.ModelAdmin): list_display = ( 'id', 'customer', 'date', 'pdf_link', ) On my cakes.views.py I have the generate_pdf function from the django docs. How do I connect/link my view function(generate_pdf) with the pdf_link function in my model? I can download the PDF outside the admin. I'm just not sure how to tie it all together in the admin. -
jsONDecodeError. AJAX + Django. Comment system
I'm trying to implement a comment system in Django. The problem is that I can add a comment to the very first post and AJAX will work, that is, the comment will be published without reloading. But if I try to leave a comment on the following posts, I stumble upon an error: jsONDecodeError Exception Value: Expecting value: line 1 column 1 (char 0). In data = json.loads(request.body), there is a post_id and a body, but only if you leave a comment on the first post. To the rest of the request.body is just an empty string models.py from django.utils import timezone from django.db import models from django.contrib.auth.models import User class Post(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='posts') title = models.CharField(max_length=30) body = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=timezone.now()) def __str__(self) -> str: return self.title class Comment(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='comments') body = models.CharField(max_length=255) post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name='comments', blank=True) created_at = models.DateTimeField(auto_now_add=timezone.now()) def __str__(self) -> str: return self.body views.py from django.utils.formats import date_format from django.shortcuts import get_object_or_404 from django.http import JsonResponse from .models import * from django.shortcuts import render import json def post_detail(request): quotes = Post.objects.all() context = { 'quotes': quotes, } return render(request, 'app_one/post_detail.html', context) def comment_create(request): … -
Collect data from multiple Django signals in session or cache
I have a view in views.py that hits multiple database models. Each model has its own signals registered with it (pre_save, post_save, post_delete, ...etc). Each signal collects the changes in data for each model. Now, I want to collect all those changes to use them somehow at the end of my view. So, I though about saving such data temporarily in the user's session or cache to retrieve them just at the ned of my view, but unfortunately the signal functions doesn't take request parameter with it. So, how can I do such? -
Delete a user from a room Django
In my app, I have created rooms where participants(users) can message. (In models.py) from django.db import models from django.contrib.auth.models import User # Create your models here. class Topic(models.Model): name = models.CharField(max_length=200) def __str__(self) : return self.name class Room(models.Model): host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) participants = models.ManyToManyField(User, related_name='participants', blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-updated', '-created'] def __str__(self): return self.name class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) body = models.TextField() updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.body[0:50] Now, in the participants section, I have added a user whenever the user sends a message sends a message for the first time in that room. (In views.py) def room(request, pk): room = Room.objects.get(id=pk) room_messages = room.message_set.all().order_by('-created') participants = room.participants.all() print(participants.all()) if request.method == 'POST': message = Message.objects.create( user=request.user, room=room, body=request.POST.get('body') ) room.participants.add(request.user) return redirect('room', pk=room.id) context = {'room':room, 'room_messages':room_messages, 'participants':participants} return render(request, 'base/room.html', context) Now I want to delete a user from participants when that user deletes all his messages from the room. I am not getting an idea how to proceed here. (In views.py) @login_required(login_url='login') def deleteMessage(request, pk): message … -
docker compose ignores that a service depends on another
Here's the current docker-compose.yml version: '3' services: db: image: postgres environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_DB=my_app ports: - '5432:5432' web: build: . image: my-app ports: - "8000:8000" depends_on: - db command: sh -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/code environment: - DB_USER=postgres - DB_PASSWORD=postgres - DB_HOST=db - DB_NAME=my_app When I run the app for the first time, this happens: % docker compose build && docker compose up [+] Building 2.5s (10/10) FINISHED => [internal] load build definition from Dockerfile 0.1s => => transferring dockerfile: 189B 0.0s => [internal] load .dockerignore 0.0s => => transferring context: 150B 0.0s => [internal] load metadata for docker.io/library/python:3.11.1-bullseye 2.0s => [1/5] FROM docker.io/library/python:3.11.1-bullseye@sha256:cc4910af48 0.0s => [internal] load build context 0.2s => => transferring context: 1.21MB 0.2s => CACHED [2/5] COPY requirements.txt requirements.txt 0.0s => CACHED [3/5] RUN pip install -r requirements.txt 0.0s => CACHED [4/5] COPY . /app 0.0s => CACHED [5/5] WORKDIR /app 0.0s => exporting to image 0.0s => => exporting layers 0.0s => => writing image sha256:d7b4a64b01b9de03dec4a0732eaf975b7bc68f1daefb4 0.0s => => naming to docker.io/library/my-app 0.0s Use 'docker scan' to run Snyk tests against images to find vulnerabilities and learn how to fix them [+] Running 3/3 ⠿ … -
I kindly ask to help me populate my many-to-many relation in Django
I am new in Django and Python at all. I kindly ask to help me with my case. There are three models in my study project among a number of others: models.py class Protein(models.Model): protein_id = models.CharField( max_length=256, null=False, blank=False, db_index=True) taxonomy = models.ForeignKey( Taxonomy, on_delete=models.DO_NOTHING, null=True, blank=True) length = models.IntegerField(null=True, blank=True) access = models.IntegerField(null=False, blank=False, default=0) def __str__(self): return self.protein_id class Pfam(models.Model): domain_id = models.CharField( max_length=256, null=False, blank=False, db_index=True) domain_description = models.CharField( max_length=256, null=True, blank=True) def __str__(self): return self.domain_id class Domain(models.Model): pfam = models.ForeignKey(Pfam, on_delete=models.CASCADE) description = models.CharField(max_length=256, null=True, blank=True) start = models.IntegerField(null=True, blank=True) stop = models.IntegerField(null=True, blank=True) protein = models.ManyToManyField( Protein, related_name='domains', through='ProteinDomainLink') def __str__(self): return self.pfam.domain_id class ProteinDomainLink(models.Model): protein = models.ForeignKey(Protein, on_delete=models.DO_NOTHING) domain = models.ForeignKey(Domain, on_delete=models.DO_NOTHING) Class Domain has ManyToMany field, linked to class Protein through class ProteinDomainLink. There are three csv files to retrieve data from, and my populate script looks like: populate_data.py data_sequences_file = '../..source_file_1'; pfam_descriptions_file = '../..source_file_2'; data_set_file = '../..source_file_3'; pfam = defaultdict(list) domains = defaultdict(list) proteins = defaultdict(list) ... with open(pfam_descriptions_file) as pfam_descriptions_csv_file: pfam_descriptions_csv_reader = csv.reader( pfam_descriptions_csv_file, delimiter=',') for row in pfam_descriptions_csv_reader: pfam[row[0]]=row[1:2] with open(data_set_file) as data_set_csv_file: data_set_csv_reader = csv.reader(data_set_csv_file, delimiter=',') for row in data_set_csv_reader: domains[row[5]] = row[4:5]+row[6:8] proteins[row[0].strip()] = row[1:2]+row[8:9] pfam_rows = … -
Django - ListView - populate table dynamically
I am trying to create a generic table (that I can reuse for other Objects as well) by passing in the views the context "table" As part of view.py I have the following information passed on as Context: object_list = User.objects.all() table.columns that contains the Column Accessor (the property of the User object I want to access) and the Header Name e.g. {'last_name': 'Last Name', 'first_name': 'First Name'} In my template I want to loop through the objects, and find the "Column Accessor" and get the property of the object. So far I have the following, but I am not sure how I can access the property of the object from the template. I can imagine I could create a filter tag, but any help on how to accomplish that would be appreciated. #template.py {% for object in object_list %} {% for column in table.columns %} <td>{{object.????}}</td> {% endfor %} {% endfor %} -
How can I pass the id list in nested serialiazer and get dict output
I pass the list of tag ids in nested serializer during POST. I want to get all the fields of the object in Response, I got only the id. My output: { "id": 87, "tags": [ 1, 2 ]... I need it to be like this: { "id": 0, "tags": [ { "id": 0, "name": "breakfast", "color": "#E26C2D", "slug": "breakfast" } ... How can I do it? My code: class RecipesSerializer(serializers.ModelSerializer): author = serializers.StringRelatedField(read_only=True, default=serializers.CurrentUserDefault()) image = Picture2Text(required=False, allow_null=True) ingredients = IngredientsSerializer(many=True, required=False) class Meta: model = Recipes fields = ( 'id', 'tags', 'author', 'ingredients', 'is_favorited', 'is_in_shopping_cart', 'name', 'image', 'text', 'cooking_time', ) def create(self, validated_data): new_recipe = Recipes.objects.create( author=self.context['request'].user, name=validated_data['name'], image=validated_data['image'], text=validated_data['text'], cooking_time=validated_data['cooking_time'], ) new_recipe.save() for ingredient in validated_data['ingredients']: ingredient_obj = Ingredients.objects.get(id=ingredient['id']) RecipeIngredients.objects.create( recipe=new_recipe, ingredients=ingredient_obj, amount=ingredient['amount'] ) amount = ingredient['amount'] ingredient_obj.amount = amount ingredient_obj.save() new_recipe.ingredients.add(ingredient_obj) for tag in validated_data['tags']: tag_obj = Tags.objects.get(id=tag.id) new_recipe.tags.add(tag_obj) new_recipe.save() return new_recipe I tried to explicit the tag serializer but it didn`t work. I did: class RecipesSerializer(serializers.ModelSerializer): author = serializers.StringRelatedField(read_only=True, default=serializers.CurrentUserDefault()) image = Picture2Text(required=False, allow_null=True) tags = TagWithinRecipeSerializer(many=True, read_only=True) With: class TagWithinRecipeSerializer(serializers.ModelSerializer): id = serializers.IntegerField() class Meta: fields = ('id', 'name', 'color', 'slug') model = Tags But it didn't work: File "/home/aladinsane/.local/lib/python3.10/site-packages/rest_framework/serializers.py", line 205, in save … -
django.urls.exceptions.NoReverseMatch: Reverse for 'watchlist' not found. 'watchlist' is not a valid view function or pattern name
I am building a django (v3.2.5) project called commerce which has an app called auctions. urls.py for commerce: from django.contrib import admin from django.urls import include, path urlpatterns = [ path("admin/", admin.site.urls), path("", include("auctions.urls")) ] urls.py of auctions: (notice that watchlist path is commented out) from django.urls import path from . import views app_name = 'auctions' urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("create", views.create, name='create'), path("listing/<int:listing_id>/", views.listing, name='listing'), # path("watchlist/", views.watchlist, name='watchlist') ] views.py: (watchlist function is commented out) @login_required(login_url='/login') def listing(request, listing_id): if request.method == 'GET': listing_data = list(Listing.objects.filter(id = listing_id)) return render(request, "auctions/listing.html", context={"listings":listing_data}) else: pass # @login_required(login_url='/login') # def watchlist(request): # pass index.html: <a href="{% url 'auctions:listing' listing.id %}" class="btn btn-primary">View Listing</a> This is the only tag that points to the listing function/path in views.py. No tag points to the watchlist function/path. This is the error message when I click on the above tag to go to listing.html enter image description here The error points to this particular line of code in views.py: return render(request, "auctions/listing.html", context={"listings":listing_data}) Whenever I remove the context dictionary, that is put only the request and the template in render(),the code runs perfectly fine … -
Fail to integrate scss in my rollup build
What I try to achieve I'm trying to create a little library for private use - basically just splitting up some code into lib (product) and app (project) code. All my source code lives in /src folder which contains React, TypeScript and SCSS code. It would be great, if I can use the SCSS imports directly in React like: import './_button.scss'; I have another SCSS file: src/style/_main.scss it includes some mixins, global styles, resets etc. Config files import commonjs from '@rollup/plugin-commonjs'; import json from '@rollup/plugin-json'; import resolve from '@rollup/plugin-node-resolve'; import terser from '@rollup/plugin-terser'; import typescript from '@rollup/plugin-typescript'; import url from '@rollup/plugin-url'; import dts from 'rollup-plugin-dts'; import scss from 'rollup-plugin-scss'; import { format, parse } from 'path'; import pkg from './package.json' assert { type: 'json' }; const getTypesPath = (jsFile) => { const pathInfo = parse(jsFile); return format({ ...pathInfo, base: '', dir: `${pathInfo.dir}/types`, ext: '.d.ts', }); }; export default [ { input: 'src/index.ts', output: [ { file: pkg.main, format: 'cjs', interop: 'compat', exports: 'named', sourcemap: true, inlineDynamicImports: true, }, { file: pkg.module, format: 'esm', exports: 'named', sourcemap: true, inlineDynamicImports: true, }, ], plugins: [ resolve({ browser: true }), commonjs({ extensions: ['.js', '.jsx', '.ts', '.tsx'] }), typescript({ tsconfig: './tsconfig.build.json' }), url(), scss({ … -
Trying to upload data from python to mysql, but the insertion is not commited
I'm trying to upload some rows of data from python to mysql, using django and mysql, as we also want to show data from the database in our webpage. The connection to the server does work correctly, and so the connection to the database. The problem comes when we execute the following query to insert data from python to mysql. def addInfo(request, T, P, A, Rx, Ry, Rz, Ax, Ay, Az, Fecha, Long, Lat, Vel): """conexion = mysql.connector.connect(user='root', password='admin', host='localhost', database='datos', port='3306') print(conexion) cursor = conexion.cursor() print("T:"+str(T))""" query = "use datos; INSERT INTO datos(Temperatura, Presion, Altitud, RotacionX, RotacionY, RotacionZ, AceleracionX, AceleracionY, AceleracionZ, Fecha, Longitud, Latitud, Velocidad) VALUES ('"+T+"','"+P+"','"+A+"','"+Rx+"','"+Ry+"','"+Rz+"','"+Ax+"','"+Ay+"','"+Az+"','"+Fecha+"','"+Long+"', '"+Lat+"', '"+Vel+"');" print(query) cursor.execute(query) documento = """<!DOCTYPE html> <html> <head> --HTML PART IS OMITTED-- </html>""" print(cursor) cursor.close() return HttpResponse(documento) When we execute this code, database does not update rows, but when we execute manually in mysql, it does work and the id auto-increments as if we had uploaded the previous query. (but the previous row doesn't appear ) -
Is there any way to get the value of multiplecheckboxes that the rendering in for loop with django-template-language
How to get value of mutiplecheckboxes in django. the below code showing the groups at frontend {% for group in groups %} <tr><td>{{group.name}}</td> <td><input type="checkbox" name="superuser" id="group-{{group.id}}" value="{{group.id}}"></td> </tr> {% endfor %} I want to get the values of all checked boxes at backend when I submit the record. -
How to build a django web app using huggingface model api's
I am a beginner and I want to build Django app having hugging face model api to do a specific task in that app. but I am not getting any helping material. please help me guide me about how can I do that. I tried but I failed. I am a beginner to this -
Django HttpResponse does not redirect after Javascript Post with fetch
With the following Post using Javascript function send_dialog() { fetch('dialog', { method: 'POST', body: JSON.stringify({ id_to_dialog }) }) .then(response => response.json()) .then(result => { // Print result console.log(result); }); } and the corresponding function of the django view: @csrf_exempt def dialog(request): print(request) data = json.loads(request.body) print(data) return HttpResponse("HEY") I'm able to print out the data, but the website doesn't get redirected to the simple page showing "Hey". So far I've tried several other methods reverse, redirect etc. from django, but could never successfully redirect to the "hey" page. -
Django get objects created by users, with those users belonging to a list of users
I have a model for followers. Here is the model: class Follow(models.Model): followee = models.ForeignKey(User, on_delete=models.CASCADE, related_name="followee") follower = models.ForeignKey(User, on_delete=models.CASCADE, related_name="follower") created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: unique_together = ["followee", "follower"] def __str__(self): return "{} is following {}".format(self.follower, self.followee) def save(self, *args, **kwargs): if self.followee == self.follower: return "You cannot follow yourself" else: super().save(*args, **kwargs) Users create multiple types of objects like posts and questions. I would like to show all the posts and questions of all the users that follow a specific user. Simplified show me all the posts and questions of users that follow me. I am using a module called drf_multiple_model and here is my view, which I cannot get to work. It gives me the following error that I don't understand: Cannot use QuerySet for "Follow": Use a QuerySet for "User". Here is the view I am using: def get_followers(queryset, request, *args, **kwargs): id = kwargs['user'] user = User.objects.get(id=id) followers = Follow.objects.all().filter(followee=user) return queryset.filter(user__in=followers) class HomeView(FlatMultipleModelAPIView): permission_classes = [IsAuthenticated] def get_querylist(self): querylist = [ {'queryset':Post.objects.all(), 'serializer_class': UserPostSerializer, 'filter_fn': get_followers, 'label':'post'}, {'queryset':Question.objects.all(), 'serializer_class': QuestionSerializer, 'filter_fn': get_followers, 'label':'question'}, ] return querylist What am I doing wrong please? -
Celery task is not sending message
I'm running a periodic task with Celery and Django. The web scraping task is executing well and saving the new data, if any, to the database. However, the task is not sending a LINE message throug messagebird. This is the task snippet: tsukisamu = suii_scrap(TSUKISAMU_URL) try: t_jikan = tsukisamu[0] t_suii = tsukisamu[1] except TypeError: print("Error at Tsukisamu.") tsukisamu_obj = Tsukisamu.objects.latest() if t_jikan and t_suii is not None: tsukisamu_obj = Tsukisamu.objects.get_or_create(jikan=t_jikan, suii=t_suii) if tsukisamu_obj[0].shussui: client.conversation_start({ 'channelId': '881d2c2f475b23e38ed6d8da2eb9645e', 'to': 'Ua918d75611833f8d933e5a941dd9494d', 'type': 'text', 'content': { 'text': 'test', } }) If the model shussui method is True (which it is for test purposes), a message should be sent by the messagebird client's conversation_start method (imports are also alright). This exact same code is working on a normal Django view code, but when inside the celery task it isn't being sent. I'm new to Celery so maybe there's something I'm missing but can't really find what it can be. Any ideas? -
Can't convert string to float. Its showing error "could not convert string to float: 'None'"
Im working a Django project that gets my deivce location and shows the nearest places. Ive manage to pass the cordinates to the views module but I cant change from "str" to "float". It shows the error "could not convert string to float: 'None'". This is my code Template (index.html) <h1> Pharmacy Finder </h1> <button onclick="getLocation()">Try It</button> <p id="demo"></p> var x = document.getElementById("demo"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { x.innerHTML = "Geolocation is not supported by this browser."; } } function showPosition(position) { x.innerHTML =position.coords.latitude + "," + position.coords.longitude; var lat = x; $.ajax({ url:'', type: 'get', data: {location: $(lat).text()} }); } View (views.py) from contextlib import nullcontext from django.shortcuts import render from django.http import HttpResponse #finder imports import time import googlemaps import pandas as pd # pip install pandas import numpy as np import re #Google Maps API Key API_KEY = 'AIzaSyAffT1NSiYnE4n_4v8No2GCYUqKp-XLtcc' map_client = googlemaps.Client(API_KEY) Rlatitude = 0 Rlongitude = 0 def index(request): global Rlatitude global Rlongitude text = request.GET.get('location') a = str(text) cordinates = re.split('\,',a) for ls in range(len(cordinates)): if ls ==0: Rlatitude = cordinates[ls] elif ls>0: Rlongitude = cordinates[ls] #the error is here: print(type(Rlatitude)) print(Rlatitude) if Rlatitude != 0: print(Rlatitude) a = float(Rlatitude) … -
django not recognizing my index.html page, stuck on the install worked
I have an index.html page made and also referenced in views.py and urls.py. For some reason, the home page at http://127.0.0.1:8000/ only shows the install worked default page. Am I calling it wrong? I followed the installation step-by-step and it's not working at all views.py: from django.shortcuts import render # Create your views here. def index(request): return render(request, 'index.html') from django.urls import include, path from django.contrib import admin from . import views urlpatterns = [ path('', views.index, name='index'), ] index.html <!DOCTYPE html> <html lang="en"> <head> </head> <body> <p>index</> </body> </html> -
How to save in the DB multiple images along with text using Reactjs and Django Rest Framework?
I am creating an e-commerce like app and I am stuck on implementing the feature to add the item (text + multiple images). I am sending a POST request from a Reactjs form, containing text and multiple images and I am able to save the text to the DB, and the images to the media folder, but I cannot save the images (path to media folder) in the DB (Psql). This is the error message: "IntegrityError at /api/image/multiple_upload/ null value in column "item_id_id" of relation "api_image" violates not-null constraint" My assumption is, as I am sending 2 different fetch POST requests on submit, one for the text and the other one for the images, and as each image has a FK to the item_id, the image's column cannot be filled as the item has not been yet created. Am I wrong? Is there any suggestion on how to implement that? models.py class Image(models.Model): image = models.ImageField(blank=True, null=True, upload_to='%Y/%m/%d') item_id = models.ForeignKey('Item', default="", on_delete=models.CASCADE) class Item(models.Model): item_name = models.CharField(max_length=200, default="") user_id = models.ForeignKey('User', on_delete=models.CASCADE,) serializers.py class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ['id', 'item_name', 'user_id', 'details', 'desire'] class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = "__all__" class MultipleImageSerializer(serializers.Serializer): … -
Can anyone explain how to list the objects vertically instead of horizontal?
*Here is the code. With this code listing is done vertically.Here is the current output I want to make this vertically. *This is the current code I written. {% extends 'index.html' %} {%block body_block%} {%for p in carslist%} <section class="py-5"> <div class="container px-4 px-lg-5 mt-2"> <div class="row gx-4 gx-lg-5 row-cols-2 row-cols-md-3 row-cols-xl-4 justify-content-center"> <div class="col mb-5"> <div class="card h-100"> <!-- Product image--> <img class="card-img-top" src="{{p.carpic.url}}" alt="..." /> <!-- Product details--> <div class="card-body p-4"> <div class="text-center"> <!-- Product name--> <h5 class="fw-bolder">{{p.carcompany}}</h5> <p>{{p.carmodel}}</p> <!-- Product price--> </div> <ul class="list-group list-group-flush"> <li class="list-group-item">Price: {{p.carprice}}</li> <li class="list-group-item">Kms: {{p.carkms}}</li> </ul> </div> <!-- Product actions--> <div class="card-footer p-4 pt-0 border-top-0 bg-transparent"> <div class="text-center"><a class="btn btn-outline-dark mt-auto" href="#">View Details</a></div> </div> </div> </div> </div> </div> </section> {%endfor%} -
django query use aggregate on joined table
In my project , Each candidate can take part in some assessments, each assessment has some tests and each test has some questions in it and candidates should answer the questions. at the end of the test , scores of the questions are saved in question_score automatically and the score of test is saved in test_score table(which is average of question scores) each test has a weight and I want to add a field to candidate model as assessment_score and write a method in candidate class model which calculate the score of assessment based on weight of each test and score of it How can I use aggregate in my query with these joins on tables? the simplified models are : Assessment: class Assessment(BaseModel): title = models.CharField(max_length=255) tests = models.ManyToManyField( 'exam.Test', related_name='assessments', blank=True, through='TestOfAssessment', ) candidates = models.ManyToManyField( 'user.User', related_name='taken_assessments', blank=True, through='candidate.Candidate' ) def __str__(self): return self.title Test: class Test(BaseModel): class DifficultyLevel(models.IntegerChoices): EASY = 1 MEDIUM = 2 HARD = 3 questions = models.ManyToManyField( 'question.Question', related_name='tests', blank=True, help_text='Standard tests could have multiple questions.', ) level = models.IntegerField(default=1, choices=DifficultyLevel.choices) title = models.CharField(max_length=255) summary = models.TextField() def __str__(self): return self.title TestOfAssessment: class TestOfAssessment(models.Model): assessment = models.ForeignKey('Assessment', on_delete=models.CASCADE) test = models.ForeignKey('exam.Test', on_delete=models.CASCADE) weight … -
Python - missing 1 required positional argument
Here is my first Django project. I am trying to develop a Scholarship system whereby the admin can add Countries that offer Scholarships into the system. Everything works fine at the level of my database and I'm able to add the countries. However, I have a sidebar menu and want any new country I add to the system, added to the menu automatically. **Views.py ** class CountryListView(ListView): template_name = "base.html" models = Country context_object_name = "countrys" Sidebar HTML Snippet -
Accessing Data from an Intermediate Model and the Main Model at the same time?
We've run into an interesting problem. We're using an intermediate model to track the quality of an item (PlayerProfile in this case) that belongs to a specific UserInventory. We'd like to be able to find the "total value" of that UserInventory by multiplying the "quantity" (in UserInventoryItemModel) by the "best_buy_price (in the MarketListing model). Here is what I have in the serializer now, but it fails at card.quantity. def get_owned_value(self, obj): inventory = obj.inventory.all() value = 0 for card in inventory: try: best_buy_price = card.marketlisting.best_buy_price quantity = card.quantity #this fails total = best_buy_price * quantity value = value + total except: continue return value I tried this - and it is able to get the quantity, but it can not longer access marketlisting.best_buy_price. def get_owned_value(self, obj): inventory = obj.userinventoryitem_set.all() value = 0 for card in inventory: try: best_buy_price = card.marketlisting.best_buy_price #this fails quantity = card.quantity total = best_buy_price * quantity value = value + total except: continue return value How can I access quantity and best_buy_price in the same loop? Here is a simplified version of the models: class PlayerProfile(auto_prefetch.Model): card_id = models.CharField(max_length=120, unique=True, primary_key=True) game = models.CharField(max_length=120, null=True) class MarketListing(auto_prefetch.Model): item = models.CharField(max_length=120, unique=True, primary_key=True) player_profile = auto_prefetch.OneToOneField( PlayerProfile, …