Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Picture showing as broken when referenced in template
I am trying to create a settings page for user profiles and I have hit a roadblock. I included a profile image inside of my User model and when trying to reference said ImageField in my profile template the image shows up as broken. Firstly, everything else related to the storing of a profile image works. When an account is created, the default image saves and same with using the upload picture form. The issue comes when trying to display the current profile picture through the model's url and the image shows up as broken. models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) id_user = models.IntegerField() bio = models.TextField(max_length=300, blank=True) profileimg = models.ImageField(upload_to='profile_images', default='blank-profile.jpg') verified = models.BooleanField(default=False) def __str__(self): return self.user.username views.py def settings(request): user_profile = Profile.objects.get(user=request.user) if request.method == "POST": if request.FILES.get('image') == None: image = user_profile.profileimg bio = request.POST['bio'] user_profile.profileimg = image user_profile.bio = bio user_profile.save() if request.FILES.get('image') != None: image = request.FILES.get('image') bio = request.POST['bio'] user_profile.profileimg = image user_profile.bio = bio user_profile.save() return redirect('settings') return render(request, 'settings.html', {'user_profile': user_profile}) Section of html file that tries to show image <img width="100" heigh="100" src="{{ user_profile.Profileimg.url }}" /> I have also added all of the necessary MEDIA_URL/root settings and have tried … -
Django form not showing errors but redisplays new form
I have a Insert view which displays model data from one primary and one related model. Once finished displaying the data a form is appended to the table to add a new related item. This works fine - however if I enter invalid data (like a invalid time to be exact), and hit one of the submit buttons, it simply refreshes the page with a blank entry form for the related data again. It doesn't display the data I entered, and it doesn't display an error message even though the form includes the error fields. I have tried adding form_invalid to my CBV and calling the form but I can see that it just calls the InserView again with no context (which basically does the get_context_data call again and give me a new blank form). How do I get it to put up the form with my data from before and the errors as well. See code below: views.py class SegmentAddView(LoginRequiredMixin,CreateView): login_url = reverse_lazy('login') model = Segment template_name = 'segment_add_view.html' form_class = SegmentForm def get_context_data(self, **kwargs): context = super(SegmentAddView,self).get_context_data(**kwargs) program_info = get_object_or_404(Program, pk=self.kwargs['pk']) context['program_info'] = program_info last_segment = program_info.segments.last() if last_segment: add_sequence_num = last_segment.sequence_number + Decimal(1.00) else: add_sequence_num = Decimal(1.00) … -
Django: Display data from other table
I'm having a hard time displaying some datas from two or three tables. So this is my code for showing all the data only from Device table. def device(request): if request.method == 'GET': queryset = Device.objects.all() if queryset: data = {"queryset": queryset} return render(request, 'device/device.html', data) else: return render(request, 'device/device.html') And I want to add some data from other table, how do I insert it here? -
Adding parameters into URL via django url name
There are following files: #urls.py from django.urls import path from . import views app_name = 'some_app' urlpatterns = [ path('', views.index, name='index'), path('some_url/', views.view_func, name='some_url') ] #views.py from django.shortcuts import redirect def index(request): return redirect('some_app:some_url') def view_func(request): pass Now, if I follow the first link (index) it will redirect me to /some_url/. How can I change my code to add any parameters to URL for redirecting to /some_url/?param1=abc&param2=def? -
how can i view my python bot data in my mysql table?
In the bookfiles folder, there are bots I wrote with python. I imported my model class inside bots. I created the table in the models.py file in the database, but the bots' data is not displayed. There are only column names. How can I display this data in my database table? I've included the bot's code below. from ast import Str from base64 import decode import requests from bs4 import BeautifulSoup import pandas as pd import csv from time import sleep from random import randint import numpy as np from bookList.models import BookList headers = dict() headers[ "User-Agent" ] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36" def sendBooksToMysql(): bkmArt() def bkmArt(): pages = range(1, 3, 1) for page in pages: url = "https://www.bkmkitap.com/sanat" results = requests.get(url, headers=headers) soup = BeautifulSoup(results.content, "html.parser") book_div = soup.find_all("div", class_="col col-12 drop-down hover lightBg") sleep(randint(2, 10)) for bookSection in book_div: img_url = bookSection.find("img", class_="lazy stImage").get('data-src') name = bookSection.find("a",class_="fl col-12 text-description detailLink").get('title') author = bookSection.find("a", class_="fl col-12 text-title").get('title').replace('Model:', '') publisher = bookSection.find("a", class_="col col-12 text-title mt").get('title').replace(name, '') price = bookSection.find("div", class_="col col-12 currentPrice").text.replace('\n', '').replace('TL', ' TL') b_link = bookSection.find("a").get('href') bookList = BookList.objects.using("bookList").update_or_create( site_name="Bkmkitap", site_id="1", image=img_url, #book=name, #author=author, publisher=publisher, price=price, link=b_link, … -
django Templates sum prices of cart items
Inside DJango templates, in an HTML Page, I have the following lines of code in body. {% for cart_data in cart_items|slice:"0:"%} <div class="Cart-Items pad "> <div class="image-box"> <img src={{cart_data.img_url}} style="height:120px;"}} /> </div> <div class="about"> <h1 class="title">{{cart_data.name}}</h1> <h3 class="product_id">{{cart_data.retailer_sku}}</h3> <div class="sku"> <div class="color">{{cart_data.color}} ({{cart_data.size}})</div> </div> </div> <div class="prices"> <div class="amount">$ {{cart_data.price}}</div> </div> </div> {% endfor %} This code extacts the cart items and displays them on the page. Now I want to do is sum all the proces and show total after this loop. How to do that? -
Django SAML2 Authentication with AZURE
I have a Django application in production on an Ubuntu 20.04 server that uses python3.8.10 and I'm trying to implement the SSO connection with pysaml2 with Azure. I chose to use the django-saml2-auth-ai package. So I have configured correctly according to the doc. However when I try my url /accounts/login/ I get an error /saml/deny/. same for /saml/acs/. however when I try the url /saml/welcome/ it redirects me to the SAML connection correctly so I know there is no problem with my Azure configuration. urls.py import django_saml2_auth.views urlpatterns = [ path('saml/', include('django_saml2_auth.urls')), path('accounts/login/', django_saml2_auth.views.signin), path('', login_, name="login"), path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')), ] settings.py # more code... LOGIN_URL = "/accounts/login" LOGIN_REDIRECT_URL = 'accounts:index' # more code... SAML2_AUTH = { 'SAML_CLIENT_SETTINGS': { # Pysaml2 Saml client settings 'entityid': 'https://mysiteweb.com/', 'metadata': { 'local': [ os.path.join(BASE_DIR, 'mysiteweb.xml'), ], }, 'service': { 'sp': { 'logout_requests_signed': True, 'idp': 'https://sts.windows.net/83d4d*****-*****-***/' } } }, 'debug': 1, 'DEFAULT_NEXT_URL': 'https://mysiteweb.com/', 'NEW_USER_PROFILE': { 'USER_GROUPS': [], # The default group name when a new user logs in 'ACTIVE_STATUS': True, # The default active status for new users 'STAFF_STATUS': False, # The staff status for new users 'SUPERUSER_STATUS': False, # The superuser status for new users }, 'ATTRIBUTES_MAP': { # Change Email/UserName/FirstName/LastName to … -
Corse headers adding Error while using Django in IIS
I have a django application which is hosted in IIS (with custom URL) and its front end is hosted in Angular. The front end is showing corse related error so i tried to resolve that by adding 'corseheaders' in settings.py of my backend code. After that when i tried to access the API (by clicking the hosted URL in IIS) the following error is showing in the browser. Error occurred while reading WSGI handler: Traceback (most recent call last): File "D:\TESTAPP\API\venv\Lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) Following is the changes i have done in the settings.py of my backend(django). Actually i have added the last line with "corsheaders". if its removed the error is gone. ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = True # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'survey_app.apps.SurveyAppConfig' "corsheaders", ] Can you guys please help me out. -
passing a value in anchor tag in django
So I'm in my profile page & want to edit my profile so I click edit button ,it takes me to a edit page where I have two buttons 'save'(inside form tag) & 'Exit'. Now if I click exit I want to get redirected to profile page of same person again. what input should I pass in below tag to do this? (<a href="{% url 'profile' %}"><button>Exit</button></a> -
what is the fastest and easiest to learn styling framework for django? [closed]
I've been developing this app in django and was wondering whether people had an idea what would be the optimal framework for styling the web app. Figma? Tailwind? Sass? I don't really have an eye for designing and want something rather simple and fast. Thank you very much for any answer! -
django.db.utils.IntegrityError: NOT NULL constraint failed: sales_position.created
Hi I'm working on a django project where I'm parsing a CSV file to create objects. I'm getting a database error that results in django.db.utils.IntegrityError: NOT NULL constraint failed: sales_position.created It looks like a database error because before the traceback I get the follwing message: sqlite3.IntegrityError: NOT NULL constraint failed: sales_position.created The above exception was the direct cause of the following exception: Traceback (most recent call last): Does deleting all migrations except 0001_initial.py fix this? -
How to get the number of created raw in bulk-create in django orm
Need to know the count of created raws in a bulk-create query in django. how can I get it ?? please help. -
How to compress a video using FFmpeg in Django Rest Framework?
I want to resize the video and picture files. so I looked for it and found FFmpeg and now I'm getting errors while compressing. FileNotFoundError: [WinError 2] The system cannot find the file specified Code import os import subprocess import ffmpeg MEDIA_MAX_UPLOAD_SIZE = 5242880 def check_media_size(media): media_size = media.size if media_size < MEDIA_MAX_UPLOAD_SIZE: return media_size @api_view(["POST"]) def medias_upload(request): if request.method == 'POST': received_media=request.FILES.getlist('media') allowed_mime_types = ['image/jpeg','image/png','image/gif','image/jpg','video/mp4','video/mkv','video/mov','video/avi'] upload_data = [] if received_media: for media in received_media: received_media_mime_type = mime_type_check(media) received_media_size = check_media_size(media) if received_media_mime_type in allowed_mime_types and received_media_size: new_uuid = uuid.uuid4() if str(received_media_mime_type).split('/',1)[0] == "image": file_type = str(received_media_mime_type).split('/',1)[1] converted_uuid = subprocess.run(f'ffmpeg -i {media} -acodec {file_type} temp_location/{new_uuid}') upload_data.append(converted_uuid) if str(received_media_mime_type).split('/',1)[0] == "video": file_type = str(received_media_mime_type).split('/',1)[1] converted_uuid = subprocess.run(f'ffmpeg -i {media} -acodec {file_type} temp_location/{new_uuid}') upload_data.append(converted_uuid) else: return Response({"response": False, "return_code":"Failed", "result": {}, "message": "Wrong MIME-TYPE or MAXIMUM file size allowed 5MB"}, status=status.HTTP_404_NOT_FOUND) return Response({"response": True, "return_code": "success", "result": {"media_uploaded_uuid":upload_data}, "message": success["success"]}, status=status.HTTP_200_OK) return Response({"response": False, "return_code":"Failed", "result": {}, "message": "No Data Found"}, status=status.HTTP_404_NOT_FOUND) Q . Is there any better way to compress video and picture file size? -
How to display JSON data in Django webpage like in JSON viewer?
I'm creating a webpage in Django that will display the contents of a JSON file in the database. So far, I was able to display the raw JSON output in my webpage like this. { "name": "John", "age": 22, "gender": "male" } But I also intended to display the "beautify" version of this in my webpage like in any JSON viewer. Any idea on how to implement this in my code? -
How to Stream RTSP IP Camera Properly using Django Channel and OpenCV?
I am really stuck on this issue. I am able to stream the RTSP IP Camera using Django Channel and OpenCV using Asyncio but after opening two or more channel room, the video got freeze Here is the Code import json from channels.generic.websocket import AsyncWebsocketConsumer import asyncio import numpy as np import cv2 from PIL import Image import base64 from io import BytesIO from threading import Thread PREFERED_FPS = 30 FRAME_DELAY = 1 / PREFERED_FPS global loop, cap, broadcast_task cap = cv2.VideoCapture("rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mp4") dataOld = [] def capture_and_process(cap=cap): """Capture frame from video source and process.""" # Capture frame-by-frame frame_got, frame = cap.read() if frame_got is False: return None # frame processing ret = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # .. return ret async def broadcast_task(channel_layer, room_group_name): print('*********Start broadcasting..') while True: await asyncio.sleep(FRAME_DELAY) frame = capture_and_process() if frame is None: pass else: # cv2.destroyAllWindows() frame = Image.fromarray(frame.astype("uint8")) rawBytes = BytesIO() frame.save(rawBytes, "JPEG") frame_base64 = base64.b64encode(rawBytes.getvalue()) await channel_layer.group_send( room_group_name, { 'type': 'frame_message', 'message': frame_base64.decode('utf-8') } ) class VideoStreamConsumer(AsyncWebsocketConsumer): async def connect(self): global dataOld, loop, broadcast_task self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'ClientAdmin_%s' % self.room_name dataOld.append(self.room_group_name) dataOld.reverse() try: dataOld.pop(1) except: pass # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() print("connected") loop = asyncio.get_event_loop() loop.create_task(broadcast_task(self.channel_layer, self.room_group_name)) … -
Parse &-character in GET query using Django and Vue
We are using axios to pass GET request to our django instance, that splits it into search terms and runs the search. This has been working fine until we ran into an edge case. We use urlencode to ensure that strings do not have empty spaces or others So generalize issue, we have TextField called "name" and we want to search for term "A & B Company". However, issue is that when the request reaches django. What we expected was that name=A%20&%20B%20Company&field=value would be parsed as name='A & B Company' and field='value'. Instead, it is parsed as name='A ' 'B Company' and field='value'. The & symbol is incorrectly treated as separator, despite being encoded. Is there a way to indicate django GET parameter that certain & symbols are part of the value, instead of separators for fields? -
Setting only categories to be view on homepage/set amount of images
<html> <head> <meta charset='utf-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <title>Gallery</title> <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous"> <style> .image-thumbnail { height: 200px; object-fit: cover; } .container { margin-left: 1; } .h1 { text-align: center; } .list-group-item a { text-decoration: none; color: black; } </style> </head> <h1 class="text-center m-5 p-3 mb-2 bg-light text-secondary">CHARLIES LIFE</h1> <body class="m-5"> <div class="container"> <div class="row"> <div class="col-md-3 mt-2"> <div class="card"> <div class="card-header"> Categories </div> <ul class="list-group list-group-flush"> <li class="list-group-item"> <a href="{% url 'gallery' %}">All</a> </li> {% for category in categories %} <li class="list-group-item"> <a href="{% url 'gallery' %}?category={{category.name}}">{{category.name}} </a> </li> {% endfor %} <a href="{% url 'add' %}" class="btn btn-dark btn-block m-1" type="button"">Add Photo</a> </ul> </div> </div> <div class=" col-md-9"> <div class="row"> {% for photo in photos %} <div class="col-md-4"> <div class="card my-2"> <img class="image-thumbnail" src="{{photo.image.url}}" class="card-img-cap" alt="..."> <div class="card-body"> <p class="card-text text-center">{{photo.category.name}}</p> </div> <div class="d-grid gap-2"> <a href="{% url 'photo' photo.id %}" class="btn btn-dark m-1" type="button">View</a> </div> </div> </div> {% empty %} <h3> No Photos...</h3> {% endfor %} </body> </html> Hi, I'm currently trying to make a photo blog to record the life of my son with photos as he grows. The above is my code for the "home" page (name as gallery). So at … -
Relational queryset not showing properly in template
I believe is a quite basic problem, but I'm trying to render in a template all the titles for an specific page, and inside that title its corresponding text. With these models: class Page(models.Model): page_title = models.CharField(_("title of the page"), max_length=50) category = models.ForeignKey('Category', on_delete=models.CASCADE) def __str__(self): return self.page_title class Category(models.Model): category_name = models.CharField(_("name of the category"), max_length=50) def __str__(self): return self.category_name class Title(models.Model): title = models.CharField(_("titulo"), max_length=50) page = models.ForeignKey(Page, on_delete=models.CASCADE) def __str__(self): return self.title class Text(models.Model): title = models.ForeignKey(Title, verbose_name=_("titulo de la pagina a la que pertenece"), on_delete=models.CASCADE, default='') content = models.TextField() def __str__(self): return f"{self.title}" I am using this view to render the logic: def index(request): pages = Page.objects.all() titles = Title.objects.filter(page__id=2) for title in titles: title_id = title.id texts = Text.objects.filter(title__id=title_id) context = { 'pages' : pages, 'titles' : titles, 'texts' : texts, } return render(request, 'index.html', context) But with this approach the texts only gives me the text of the last title when rendered this way in template: {% for page in pages %} <h1>{{page}}</h1> {% for title in titles %} <h3>{{title}}</h3> {% for text in texts %} <p>{{text}}</p> {% endfor %} {% endfor %} {% endfor %} The desired rendering would be all the … -
how do I remove repition of tags used in posts
I want to display the tags in a dropdown list. But the problem here is that same tags are being displayed per post. So is there any way that I can avoid this repetition? my dropdown list is as below: <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Tags </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> {% for post in posts %} {% for tag in post.tags.all %} <a class="dropdown-item" href="{% url 'post_tag' tag.slug %}"> {{ tag.name }} </a> {% endfor %} {% endfor %} </div> </div> It would be handy if there are any JS script or anything else to avoid this repetition. Thanks! -
Debugging django project in docker-compose in VS code
I cannot tune debugging django project from docker-compose in VS code. Docker-compose: version: '3' services: helpdesk_web: build: context: ./ dockerfile: Dockerfile container_name: helpdesk_web volumes: - ./static:/usr/src/app/static - media:/usr/src/app/media ports: - "8000:8000" - "5678:5678" env_file: - ./.env restart: always depends_on: - helpdesk_db helpdesk_db: image: postgres container_name: helpdesk_db volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env ports: - "5432:5432" environment: POSTGRES_DB: something POSTGRES_PASSWORD: something POSTGRES_USER: something nginx: build: context: ./docker/nginx dockerfile: Dockerfile container_name: helpdesk_nginx restart: on-failure depends_on: - helpdesk_web - helpdesk_db ports: - "80:80" volumes: - ./static:/usr/src/app/static - media:/usr/src/app/media volumes: postgres_data: media: DockerFile: FROM python:3.10 # Задаем рабочую директорию(app) внутри контейнера WORKDIR /usr/src/app # Запрещаем Python писать файлы .pyc на диск ENV PYTHONDONTWRITEBYTECODE 1 # Запрещает Python буферизовать stdout и stderr ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip # Копируем файл из рабочей директории на диске в рабочую директорию(/usr/src/app) контейнера COPY requirements.txt . RUN pip install -r requirements.txt # Копирует все файлы из рабочей директории на диске в рабочую директорию контейнера COPY . . RUN chmod +x entrypoint.sh ENTRYPOINT ["/usr/src/app/entrypoint.sh"] launch.json: "version": "0.2.0", "configurations": [ { "name": "Django DEBUG", "type": "python", "request": "attach", "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "/usr/src/app" } ], "port": 5678, "host": "0.0.0.0", }, { "name": "Python: Django", "type": "python", … -
How to deploy jupyter notebook development version using django in own website?
I am working on Jupyter Notebook and want to add only the retro version of it to my django app to run code on my website. I installed it using mamba(mambaforge) and build but where are the build versions or files stored or how do I launch only the retro version using Django URLs? I think it creates some js files like the Jupyter-lite version of it but didn't find where it is and how do I run it using my django app. -
Django runs on pm2 but nginx fails to start
We are running Django app using PM2 with following script: apps: [{ name: "app_name", script: "manage.py", args: ["runserver", "127.0.0.1:8000"], exec_mode: "fork", instances: "1", wait_ready: true, autorestart: false, max_restarts: 5, interpreter : "python3" }] } And we expect nginx to tunnel it to world. While nginx -t results ok but nginx fails to start. Following is the nginx configuration: upstream app_server { server unix:/home/django/gunicorn.socket fail_timeout=0; } server { listen 8000 default_server; listen [::]:8000 default_server; root /usr/share/nginx/html; index index.html index.htm; client_max_body_size 4G; server_name _; keepalive_timeout 5; # Your Django project's media files - amend as required location /media { alias /home/django/app_name/app_name/media; } # your Django project's static files - amend as required location /static { alias /home/django/app_name/app_name/static; } # Proxy the static assests for the Django Admin panel # Warning! This location is highly sensitive to how django is installed sys> location /static/admin { alias /usr/local/lib/python3.8/dist-packages/django/contrib/admin/static> } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; proxy_buffering off; proxy_pass http://127.0.0.1:8000/; } } When we restart nginx with: sudo service nginx restart We get control process exited with error code. After debugging with journalctl -xe we get: The unit nginx.service has entered the 'failed' state with result 'exit-code'. Failed to start … -
django.db.utils.DataError: integer out of range
I have a Postgres Database in my django project. I have a model called enquiry class Enquiry(models.Model): product_name = models.CharField(max_length = 100) product_id = models.ForeignKey(List, on_delete = models.CASCADE) user_name = models.CharField(max_length = 100) user_email = models.CharField(max_length = 50) user_address = models.CharField(max_length = 200) user_mobile = models.IntegerField(default=0) And I createed a ffunction to create a new enquiry Enquiry.objects.create( product_name = product_name, product_id = product_id, user_name = user_name, user_email = user_email, user_address="None", user_mobile = user_mobile ) But I get an error django.db.utils.DataError: integer out of range how to solve this? -
how to store user details into database using serializers
def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
how to run python file from flask and see the console output on the browser itself?
I have a python script suppose a+b=c. I want to run this script using flask from the browser and how to get the output of the python script in the browser itself. like a console in the browser.