Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am trying to upload a Image in django i am very new
TypeError at /admin/lessons/lesson/add/ expected str, bytes or os.PathLike object, not list Request Method:POSTRequest URL:http://127.0.0.1:8000/admin/lessons/lesson/add/Django Version:4.1.7Exception Type:TypeErrorException Value:expected str, bytes or os.PathLike object, not listException Location:/Users/mobyfashanu/opt/anaconda3/lib/python3.9/posixpath.py, line 375, in abspathRaised during:django.contrib.admin.options.add_viewPython Executable:/Users/mobyfashanu/Desktop/mobius/learning_manager/bin/pythonPython Version:3.9.12Python Path:['/Users/mobyfashanu/Desktop/mobius', '/Users/mobyfashanu/opt/anaconda3/lib/python39.zip', '/Users/mobyfashanu/opt/anaconda3/lib/python3.9', '/Users/mobyfashanu/opt/anaconda3/lib/python3.9/lib-dynload', '/Users/mobyfashanu/Desktop/mobius/learning_manager/lib/python3.9/site-packages']Server time:Sun, 05 Mar 2023 16:09:25 +0000 By the power of deduction i can tell the problem comes from these line of code but i am unsure def dic_path(instance, filename): return 'user_'+ str(instance.user.id)+'/'+filename class Lesson(models.Model): id = models.UUIDField(primary_key=True,editable=False,default=uuid.uuid4) photo = models.ImageField(upload_to=dic_path) name = models.CharField(max_length=200) desc = models.CharField(max_length=300)` -
The UnicodeDecodeError occurred while executing the runserver command
enter image description here What does the UnicodeDecodeError error mean and how to solve the problem? -
navbar not working in home page but it's working in all pages
i try to add navbar but my problem is the navbar not working in home page but it's working in all pages .. in home page i can press on button and open it but i can't close it , it's keep open , but in all pages it's work normally navbar.html : <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="{% url 'home' %}"><h2><big><i>Uni-Study</i></big></h2></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> </ul> <form id="search_form" action="{% url 'search' %}" method="GET" value="{{request.GET.q}}" class="form-inline"> <input id="search_box" type="text" name="q" placeholder=" Search For ... " style="color:black" class="form-control mr-sm-2"/> <input class="btn btn-outline-text-white my-2 my-sm-0" id="search_button" style="width: 100px;" type="submit" name="submit" value="Search"/> </form> </div> </nav> home.html : i did this in all pages and work perfect but in home page it's not work good <!-- navbar and search + buttons --> {% include 'website_primary_html_pages/navbar_search.html' %} -
Django override save method for resize image only works forn one function. Why is this happening?
I got those two functions in my Model but only the cover_photo one is working. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True) profile_picture = models.ImageField(upload_to='users/profile_pictures', blank=True, null=True) cover_photo = models.ImageField(upload_to='users/cover_photos', blank=True, null=True) ... def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.profile_picture: img = Image.open(self.profile_picture.path) if img.height > 50 or img.width > 50: new_height = 100 new_width = int(new_height / img.height * img.width) img = img.resize((new_width, new_height)) img.save(self.profile_picture.path) def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.cover_photo: img = Image.open(self.cover_photo.path) if img.width > 100 or img.height > 100: new_width = 600 new_height = int(new_width / img.width * img.width) img = img.resize((new_height, new_width)) img.save(self.cover_photo.path) If i swap then, only the profile_picture works but the other one stops. Does any one have any idea why this happens? Is there a way to make both works. Thank you very much! -
I have 69 Heads in git. I don't see recent commits on reflog. How can I find recent commits?
My Problem in Git Bash is that the most recent version that I can find is Head@{0} and is 2 months old. When running recent commits the feed back stated that everything was up to date. Is there anywhere my recent commits might be? I looked into the history and cannot find commits that I made just last night. I had been trying git push to send my commits to Github but it did not work the last couple of times I tried. I pulled the file from Github and now my program is as it was 2 months ago. I have 69 Heads and cannot find any sha that contains new versions. I tried the Github desktop program and cannot find any recent commits there either. I did not have any branches going at the time. -
Django DRF on kubernetes and max concurrent requests tuning
I migrated a Django 4 DRF app running in a Docker container to kubernetes on OVH and I cannot figure out how to determine the max concurrent requests supported by a single replica (to later be able to increase that with more replicas/nodes) My configuration is the following 1 node : 16 core 3ghz / 60GB RAM Django / gunicorn gunicorn api.wsgi --workers=64 --timeout=900 --limit-request-line=0 --bind 0.0.0.0:8000 I first tried with a simple DRF function (no DB / no model / no serializer). Later it will database queries and a CPU demanding function. class BenchView(APIView): permission_classes = (AllowAny,) def get(self, request, format=None): return Response({"bench":"bench"},status=200) I would expect that with 16 cores, a such simple function and 64 workers I get the same response time for one request that for 64 requests launched in parallel but I get this kind of result using apache bench for example ab -n 64 -c 1 'https://server/api/bench/' 50% 96 66% 98 75% 99 80% 100 90% 103 95% 111 98% 120 99% 121 100% 121 (longest request) ab -n 64 -c 16 'https://server/api/bench/' 50% 127 66% 130 75% 133 80% 137 90% 141 95% 142 98% 145 99% 150 100% 150 (longest request) ab -n … -
javascript does not work in a Django crispy form
I want to create a client, with country, province, city selected based on 3 different models : class Country(models.Model): Country = models.CharField(max_length=100, unique=True) def __str__(self): return self.Country class Province(models.Model): province = models.CharField(max_length=100, unique=True) Country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='province', null=True) def __str__(self): return self.province class City(models.Model): city = models.CharField(max_length=100, unique=True) Province = models.ForeignKey(Province, on_delete=models.CASCADE, related_name='city', null=True) def __str__(self): return self.city When the user selects a country, province list is updated with country's province and same thing for cities. I create urls for that and code in my views.py: class GetProvincesView(View): def get(self, request, *args, **kwargs): country_id = request.GET.get('country_id') provinces = Province.objects.filter(Country_id=country_id) data = [{'id': province.id, 'name': province.province} for province in provinces] return JsonResponse(data, safe=False) class GetCitiesView(View): def get(self, request, *args, **kwargs): province_id = request.GET.get('province_id') cities = City.objects.filter(Province_id=province_id) data = [{'id': city.id, 'name': city.city} for city in cities] return JsonResponse(data, safe=False) My template is: <!DOCTYPE html> <html lang="fr"> {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <h2>Ajouter un client</h2> <form method="post"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-primary">Enregistrer</button> </form> {% endblock %} {% block scripts %} <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script> $(document).ready(function() { console.log('Document ready'); // Code pour filtrer les provinces en fonction du pays … -
I was working on a project and get the error that : "(" was not closed and "{" was not closed even if I closed it
I was working on a project and get the error that : "(" was not closed and "{" was not closed even if I closed it from django.shortcuts import render from .models import * from django.http import JsonResponse # Create your views here. def get_hotel(request): try: hotel_objs=Hotel.objects.all() payload=[] for hotel_obj in hotel_objs: payload.append ({ 'hotel_name' : hotel obj.hotel_name, 'hotel_price' : hotel obj.hotel_price, 'hotel_description' : hotel obj.hotel_description 'banner_image' : banner obj.banner_image, }) return JsonResponse(payload, safe=False) except Exception as e: print(e) I am expecting that the error messagees that : "(" was not closed and "{" was not closed should not pop up -
Django Quiz App - Add timer efficiency for each question
I have create a quiz application on django. I have add timer for all question after submitting the quiz, timer will stopped and result will be displayed with total time but now I want to add timer for every question so that use can see there efficiency for particular question. Here is my view.py code- def home(request): if request.user.is_authenticated: if request.method == 'POST': questions=QuesModel.objects.filter(category=request.GET.get('id')) score=0 wrong=0 correct=0 total=0 for q in questions: total+=1 if q.ans == request.POST.get(q.question): score+=10 correct+=1 else: wrong+=1 percent = score/(total*10) *100 context = { 'score':score, 'time': request.POST.get('timer'), 'correct':correct, 'wrong':wrong, 'percent':percent, 'total':total } return render(request,'Quiz/result.html',context) else: questions=QuesModel.objects.filter(category=request.GET.get('id')) context = { 'questions':questions } return render(request,'Quiz/home.html',context) else: return redirect('login') Below is my template code ` {% extends 'Quiz/dependencies.html' %} {% block content %} {% load static %} <div class="container "> <h1><b> Welcome to Quiz</h1> <div align="right " id="displaytimer"><b>Timer: 0 seconds</b></div> <form method='post' action=''> {% csrf_token %} {% for q in questions%} <div class="form-group"> <label for="question">{{q.question}}</label> </div> <div class="form-check"> <div class="form-check"> <input class="form-check-input" type="radio" name="{{q.question }}" id="gridRadios1" value="option1"> <label class="form-check-label" for="gridRadios1"> {{q.op1}} </label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="{{q.question}}" id="gridRadios2" value="option2"> <label class="form-check-label" for="gridRadios2"> {{q.op2}} </label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="{{q.question}}" id="gridRadios1" value="option3"> <label class="form-check-label" for="gridRadios1"> {{q.op3}} … -
Django admin - building HTML page with 2,000 inlines is slow, while DB query is fast
Question in short: I have a model admin with tabular inlines. There are around 2,000 related records. Fetching them from the database takes only 1 ms, but then it takes 4-5 seconds to render them into an HTML page. What can I do to speed this up? Question in detail: I have the following (simplified) models: class Location(models.Model): name = models.CharField(max_length=128, unique=True) class Measurement(models.Model): decimal_settings = {'decimal_places': 1, 'max_digits': 8, 'null': True, 'blank': True, 'default': None} location = models.ForeignKey(Location, related_name='measurements', on_delete=models.CASCADE) day = models.DateField() # DB indexing is done using the unique_together with location temperature_avg = models.DecimalField(**decimal_settings) temperature_min = models.DecimalField(**decimal_settings) temperature_max = models.DecimalField(**decimal_settings) feels_like_temperature_avg = models.DecimalField(**decimal_settings) feels_like_temperature_min = models.DecimalField(**decimal_settings) feels_like_temperature_max = models.DecimalField(**decimal_settings) wind_speed = models.DecimalField(**decimal_settings) precipitation = models.DecimalField(**decimal_settings) precipitation_duration = models.DecimalField(**decimal_settings) class Meta: unique_together = ('day', 'location') I have created the following inlines on the Location admin: class MeasurementInline(TabularInline): model = Measurement fields = ('day', 'temperature_avg', 'temperature_min', 'temperature_max', 'feels_like_temperature_avg', 'feels_like_temperature_min', 'feels_like_temperature_max', 'wind_speed', 'precipitation', 'precipitation_duration') readonly_fields = fields extra = 0 show_change_link = False def has_add_permission(self, request, obj=None): return False When I open a Location in the admin panel, I get a nice-looking overview of all measurements. This takes however 4-5 seconds to load. I have installed Django Debug Toolbar to … -
I am getting this error " TypeError at /generate_pdf/10 expected str, bytes or os.PathLike object, not JpegImageFile"
I want to generate a pdf with content and uploaded images of each user uniquely in django but its throwing this error .This is the error message This is the code to generate pdf from django.shortcuts import render from django.http import HttpResponse , HttpResponseServerError from reportlab.pdfgen import canvas from reportlab.lib.units import inch from PIL import Image from io import BytesIO from django.core.files.base import ContentFile import tempfile import os def generate_pdf(request, pid): # Get the user object based on the user_id user = Reports.objects.get(id=pid) # Create a new PDF object response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = f'attachment; filename="{user.Title}.pdf"' # Create the PDF using ReportLab pdf = canvas.Canvas(response, pagesize=(8.5*inch, 11*inch)) # Open the uploaded image as an Image object try: image = Image.open(user.report_image) except Exception as e: print(f"Error opening image: {e}") return HttpResponseServerError("Error generating PDF") # Add the user's uploaded image to the PDF pdf.drawImage(image, 2*inch, 9.5*inch, width=3*inch, height=3*inch) # Add the user's content to the PDF pdf.setFont("Helvetica", 12) pdf.drawString(2*inch, 8*inch, user.Content) # Save the PDF and return it pdf.save() return response -
Django adds quotes in template to each TextField. How to get rid of them?
I have some TextFields in my MySQL Database, like: body = models.TextField(default = 'initial') When I call out it in my template doing this: <p class = "service_description"> {{ post.body }} </p> I get this: <p class = "service_description"> " This is the text from the database, but it is with 2 quotes and 2 spaces around itself. " </p> As you can see, it adds excess quotes around the text. I tried to add |safe to the post.body it doesn't help. I also tried to add {% autoescape off %} {{ post.body }} {% endautoescape %} it doesn't help as well. Please let me know, why do I get these excess quotes and how to remove them correctly without slicing? Thanks. -
How can I requiest API with Nginx, Vuejs in Public EC2 and Django in Private EC2
I have a question about infra setting with Nginx, Vuejs, Django. enter image description here This is Architecture. Nginx, Vuejs's dist/ in WS Django(Docker Container), Postgresql in Django Server and This is Nginx conf.d/default.conf That's all about Nginx configuration in default.conf. server { listen 80; server_name localhost; #access_log /var/log/nginx/host.access.log main; location / { root /usr/share/nginx/html; index index.html; } } And When I click button in UI, I expect the request to go to the Django server. axios.get(process.env.VUE_APP_BASE_API + 'app/test-action/', { headers: { 'Content-Type': 'application/json;charset=UTF-8-sig' }, } ).then(res => { var vm = this; console.log('ACCESS SUCCESS!!'); console.log('ACCESS RESPONSE::', res, typeof (res)); vm.message = res.data.message; }) .catch(function () { console.log('ACCESS FAILURE!!'); }); but, Nothing happened! I can get (failed)net::ERR_CONNECTION_TIMED_OUT response in Web Browser. how can I fix it? curl worked in Django Server. like curl [django_server_ip]:8000/app/test-action/?format=json also curl worked in WS. like curl [django_server_ip]:8000/app/test-action/?format=json I was able to get a response from server 2 above. -
Unable to expose docker container port to another container
I have been trying for days to solve the following issue. I cannot make container A expose port for container B in docker compose. The two containers, however, can ping the other (so they are on the same network e.g. ping db from Container B resolves the IP). Example: Container A: postgres (exposes port 5432) Container B: django project (trys to connect to postgres on port 5432) django.env DB_NAME=freelancetracker DB_USER=freelance DB_PASSWORD=freelance1234 DB_HOST=postgresdb DB_PORT=5432 postgres.env POSTGRES_PASSWORD=freelance1234 POSTGRES_USER=freelance POSTGRES_DB=freelancedb version: "3.9" services: db: image: postgres env_file: - postgres.env ports: - 9001:5432 environment: - "POSTGRES_HOST_AUTH_METHOD=trust" volumes: - ./data/db:/var/lib/postgresql/data web: build: context: . network: host args: progress: plain volumes: - .:/code ports: - 9101:9100 env_file: - django.env depends_on: - db Container postgres: { "Id": "sha256:680aba37fd0f0766e7568a00daf18cfd4916c2689def0f17962a3e1508c22856", "RepoTags": [ "postgres:latest" ], "RepoDigests": [ "postgres@sha256:901df890146ec46a5cab7a33f4ac84e81bac2fe92b2c9a14fd649502c4adf954" ], "Parent": "", "Comment": "", "Created": "2023-02-11T05:02:41.267291947Z", "Container": "7f186dd9993cc4c4ee68d8e17c42f9205a5b09b06131c62d79861b85ff4aec1d", "ContainerConfig": { "Hostname": "7f186dd9993c", "Domainname": "", "User": "", "AttachStdin": false, "AttachStdout": false, "AttachStderr": false, "ExposedPorts": { "5432/tcp": {} }, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/lib/postgresql/15/bin", "GOSU_VERSION=1.16", "LANG=en_US.utf8", "PG_MAJOR=15", "PG_VERSION=15.2-1.pgdg110+1", "PGDATA=/var/lib/postgresql/data" ], "Cmd": [ "/bin/sh", "-c", "#(nop) ", "CMD [\"postgres\"]" ], "Image": "sha256:073c3dc2528e2f091ce4497b9f51f4a69105de3faff43bd8675b99c5c2e470a6", "Volumes": { "/var/lib/postgresql/data": {} }, "WorkingDir": "", "Entrypoint": [ "docker-entrypoint.sh" ], "OnBuild": null, "Labels": {}, "StopSignal": "SIGINT" }, … -
How to render new tag using Django views?
I have index.html template in Django 4. Before. <video><source src="https://mysite/dfh2/video.mp4"></video> When I click play in player I want to render iframe, and hide all in video tag. After. <iframe src="https://somesite/ideo.mp4"></iframe> How can I do it in views.py ? -
from django.db.models.functions.math import Random2 ImportError: cannot import name 'Random2' from 'django.db.models.functions.math'
How can fix this problem ? Now I am using my Django version is 3.0.7 , I am tried another version but not support this solutions. -
How to Store file_paths for fast matching queries?
I am trying to store the file path of all files in a BUCKET. In my case a bucket can have millions of files. I have to display that folder structure in a UI for navigation. storage_folder: - bucket_1 - bucket_files.txt - bucket_metadata.txt - bucket_2 - bucket_files.txt - bucket_metadata.txt # bucket_file.txt contains folder1/sub_folder1/file1.txt folder1/sub_folder1/file2.zip folder1/sub_folder2/file1.txt folder2/..... .... .... Current approach: I will create a .txt file corresponding to each BUCKET which will contain absolute paths of each file in that bucket. Then whenever a query comes the whole file goes through lots of string matching which is really slow. What I want: I want to store those files in a tree based structure for optimized queries. Is there any solution for this? for context I am building my backend in Django. -
I have problem in Graphql. I can not get any query with Django use Graphql
I start new with Graphql. I write code from documentation. I create app named grph my project name is book. I added schema.py into my app named grph How can help me. I do not now what problem i think i write code right. Could this problem be due to the version of graphql? I use graphene 3.2.1 graphene-django 3.0.0 graphql-core 3.2.3 graphql-relay 3.2.0 It is my schema.py import graphene from .models import Category, Ingredient from graphene_django import DjangoObjectType class CategoryType(DjangoObjectType): class Meta: model = Category fields = ("id", "name", "ingredients") class IngredientType(DjangoObjectType): class Meta: model = Ingredient fields = ("id", "name", "notes", "category") class Query(graphene.ObjectType): all_ingredients = graphene.List(IngredientType) category_by_name = graphene.Field(CategoryType, name=graphene.String(required=True)) def resolve_all_ingredients(root, info): # We can easily optimize query count in the resolve method return Ingredient.objects.select_related("category").all() def resolve_category_by_name(root, info, name): try: return Category.objects.get(name=name) except Category.DoesNotExist: return None schema = graphene.Schema(query=Query) It is my models.py from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Ingredient(models.Model): name = models.CharField(max_length=100) notes = models.TextField() category = models.ForeignKey( Category, related_name="ingredients", on_delete=models.CASCADE ) def __str__(self): return self.name It is my settings.py INSTALLED_APPS = [ 'grph.apps.GrphConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'graphene_django', ] … -
ERROR: Service 'docs' failed to build : Build failed
So I had this django project for a few days and have delted and re-built it a couple of times already. I built it again this morning but it encountered an error: ERROR: Service 'docs' failed to build : Build failed The error in much detail is : ERROR: failed to solve: process "/bin/sh -c apt-get update && apt-get install --no-install-recommends -y build-essential libpq-dev && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false && rm -rf /var/lib/apt/lists/*" did not complete successfully: exit code: 100 Here's my local.yml file: version: '3' volumes: rantr_local_postgres_data: {} rantr_local_postgres_data_backups: {} services: django: &django build: context: . dockerfile: ./compose/local/django/Dockerfile image: rantr_local_django container_name: rantr_local_django depends_on: - postgres - redis volumes: - .:/app:z env_file: - ./.envs/.local/.django - ./.envs/.local/.postgres ports: - "8000:8000" command: /start postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: rantr_production_postgres container_name: rantr_local_postgres volumes: - rantr_local_postgres_data:/var/lib/postgresql/data - rantr_local_postgres_data_backups:/backups env_file: - ./.envs/.local/.postgres docs: image: rantr_local_docs container_name: rantr_local_docs build: context: . dockerfile: ./compose/local/docs/Dockerfile env_file: - ./.envs/.local/.django volumes: - ./docs:/docs:z - ./config:/app/config:z - ./rantr:/app/rantr:z ports: - "9000:9000" command: /start-docs redis: image: redis:6 container_name: rantr_local_redis celeryworker: <<: *django image: rantr_local_celeryworker container_name: rantr_local_celeryworker depends_on: - redis - postgres ports: [] command: /start-celeryworker celerybeat: <<: *django image: rantr_local_celerybeat container_name: rantr_local_celerybeat depends_on: - redis - postgres ports: … -
How to show and keep the last record in Django
I'm new to Django I hope I'm making sense. I have two models: Usecase and Usecase_progress. I'm creating a page where I can see a list of all the use cases with their information + the usecase progress for each use case gets recorded. My views.py: def view_usecase(request): usecase_details = Usecase.objects.all() context = {'usecase_details': usecase_details} return render(request, 'ViewUsecase.html', context) My template: {% extends 'EmpDashboard.html' %} {% block body %} <div class="row d-flex"> <div class="col-12 mb-4"> <div class="card border-light shadow-sm components-section d-flex"> <div class="card-body d-flex row col-12"> <div class="row mb-4"> <div class="col-lg-12 col-sm-16"> <h3 class="h3 mb-4">View Usecases:</h3> </div> {% if usecase_details is not none and usecase_details %} <div class="table-responsive"> <table id="example" class="table table-flush text-wrap table-sm" cellspacing="0" width="100%"> <thead class="thead-light"> <tr> <th scope="col">No.</th> <th scope="col">Usecase ID</th> <th scope="col">Usecase Name</th> <th scope="col">Client</th> <th scope="col">KPI</th> <th scope="col">Progress</th> <th scope="col">Progress date</th> <th scope="col">Pipeline</th> <th scope="col">View</th> </tr> </thead> <tbody> {% for result in usecase_details %} <tr> <td>{{ forloop.counter }}</td> <td><span class="badge bg-info">{{result.usecase_id}}</span></td> <td>{{result.usecase_name}}</td> <td>{{result.business_owner.business_owner_name}}</td> <td>{{result.kpi.kpi_name}}</td> {% for progress in result.usecaseids.all %} <td><div class="progress-wrapper"> <div class="progress-info"> <div class="progress-percentage"> <span>{{progress.usecase_progress_value}}</span> </div> </div> <div class="progress"> <div class="progress-bar bg-success" role="progressbar" style="width: 60%;" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100"></div> </div> </div> </td> <td>{{progress.usecase_progress_date}}</td> <td>{{progress.pipeline.pipeline_name}}</td> {% endfor %} <td> <a href="/view-usecase/{{result.usecase_id}}" class="btn btn-success">VIEW</a> </td> </tr> … -
Django Template dynamically generated sidebar
I have created a two django views home() and machine_detail(). Home view renders an home.html template and pass it a dictionary containing equipment names. my side bar consists of the items in this dictionary which is dynamically generated below these names. The equipment model is related to Machines model and I have used django foreign key relation to make a drop down for each equipment showing all the machines related to that specific equipment. all the machines are in an anchor tag and upon click i want to show a detail of machine page but why cant i see my side bar contents in machine detail template it is extending home.html but still the sidebar is not showing anyhting. please help me Equipment Model name = models.CharField(max_length=255) quantity = models.IntegerField() manufacturer = models.ForeignKey(Manufacturer, on_delete=models.PROTECT) contractor = models.ForeignKey(Contractor, on_delete=models.PROTECT, null=True, blank=True) Machines Model name = models.CharField(max_length=50) type_of_machine = models.ForeignKey(Equipment, on_delete=models.CASCADE, related_name='typeOfMachine') spares = models.ManyToManyField(Spares,related_name='machines' ,blank=True) dop = models.DateField(verbose_name="Date of Purcahse", blank=True, null=True) purchase_cost = models.FloatField(default=0) model = models.CharField(max_length=50,blank=True, null=True) image = models.ImageField(upload_to='images', blank=True, null=True) Home View def home(request): eq_map = {} equipment = models.Equipment.objects.all() for e in equipment: eq_map[e] = e.typeOfMachine.all() return render(request, "user/sidebar.html",{'equipments':eq_map}) machine_Detail view def machine_detail(request,pk): machine_detail = models.Machines.objects.get(pk=pk) … -
I am getting this error Page not found on my ecommerce store which i am making using django
`The problem being Django not able to find the that, I told it to, I am trying to access the add to cart feature which shows me this error Here's a look at my urls.py path('add-to-cart/`<int:product_id>`/', views.add_to_cart, name='add-to-cart'), path('cart/', views.show_cart, name='showcart')`, #Views.py def add_to_cart(request): user = request.user product_id = request.GET.get('product_id') product = Product.objects.get(id=product_id) Cart(user=user, product=product).save() return redirect("/cart") ``def `show_cart`(request):` user = `request.user` cart = Cart.objects.filter`(user=user) amount = 0``your text`` for p in cart: value = p.quantity * p.product.discounted_price amount = amount + value ` totalamount = amount + 40 return render(request, 'app/add-to-cart.html',locals())`` and my html file name is add-to-cart.html please help I tried to use the feature add to cart on my website when it showed me this error, i was expecting it to add this to the cart function` -
Django showing error 'constraints' refers to the joined field
I have two models Product and Cart. Product model has maximum_order_quantity. While updating quantity in cart, I'll have to check whether quantity is greater than maximum_order_quantityat database level. For that am comparing quantity with maximum_order_quantity in Cart Model But it throws an error when I try to migrate cart.CartItems: (models.E041) 'constraints' refers to the joined field 'product__maximum_order_quantity'. Below are my models class Products(models.Model): category = models.ForeignKey( Category, on_delete=models.CASCADE, related_name="products" ) product_name = models.CharField(max_length=50, unique=True) base_price = models.IntegerField() product_image = models.ImageField( upload_to="photos/products", null=True, blank=True ) stock = models.IntegerField(validators=[MinValueValidator(0)]) maximum_order_quantity = models.IntegerField(null=True, blank=True) ) class CartItems(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) product = models.ForeignKey(Products, on_delete=models.CASCADE) quantity = models.IntegerField() class Meta: verbose_name_plural = "Cart Items" constraints = [ models.CheckConstraint( check=models.Q(quantity__gt=models.F("product__maximum_order_quantity")), name="Quantity cannot be more than maximum order quantity" ) ] #Error SystemCheckError: System check identified some issues: ERRORS: cart.CartItems: (models.E041) 'constraints' refers to the joined field 'product__maximum_order_quantity'. -
Django css and javascript app not served in production
I have a django project which in development mode css are loaded just fine but not in production. In my settings.py file I've set these trhee variables STATIC_ROOT = BASE_DIR / 'staticfiles/' STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / 'static', ] I also set DEBUG = False When I run python manage.py collectstatic command the staticfiles folder receives the files properly. I created a static folder in the root of the project to install bootstrap there, again, in developent runs just fine. I'm using Apache server throug XAMPP becasuse I'm on Windows. the configuration for the project is next: `LoadFile "C:/Python310/python310.dll" LoadModule wsgi_module "C:/Users/life/.virtualenvs/outgoing-qJCH8A9k/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd" WSGIPythonHome "C:/Users/life/.virtualenvs/outgoing-qJCH8A9k" WSGIScriptAlias /outgoing "D:/DEV/PYTHON/GASTOS/software/outgoing/project/wsgi.py" application-group=%{GLOBAL} WSGIPythonPath "D:/DEV/PYTHON/GASTOS/software/outgoing" <Directory "D:/DEV/PYTHON/GASTOS/software/outgoing/project"> Require all granted Alias /static/ "D:/DEV/PYTHON/GASTOS/software/outgoing/staticfiles/" <Directory "D:/DEV/PYTHON/GASTOS/software/outgoing/staticfiles"> Require all granted ` The point is, the app load well but without the bootstrap css and javascript files. Also the browser console tells this. `Refused to apply style from 'http://localhost/outgoing/static/node_modules/bootstrap/dist/css/bootstrap.min.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. GET http://localhost/outgoing/static/node_modules/bootstrap/dist/js/bootstrap.bundle.min.js` Help please. -
How to filter a trasaction model in django
i am trying to make transctions between two users models.py class Trasaction(models.Model): sender = models.ForeignKey( Account, on_delete=models.PROTECT" ) recceiver = models.ForeignKey( Account, on_delete=models.PROTECT" ) amount = models.IntegerField() purpose = models.CharField(max_length=100, null=True, blank=True) date = date = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.sender.username}" i want to query for all transactions where a user is either a sender or a receiver. views.py def transactions_log(request): user = request.user transactions = Transactions.objects.filter #am stuck return render(request, "trasaction.html")