Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i get the uploaded file from the dropzone hidden input and send it to the socket?
I have a chatting application. I downloaded its template online (HTML, CSS, JS) and It uses Dropzone for file uploads, but I’m having a problem retrieving the file. When I upload the file, it creates a hidden input and previews it. but, when I unhide the input, no file is selected. I’m not sure if I should edit its JS file, but I don’t understand it since I barely know JavaScript. I just want to get the file and send it to my Django consumer. I don’t have any ideas on what to do // Messenger.js function toggleGroupConversation(group_id) { const conversationThread = document.getElementById('group-conversation-thread-' + group_id); const wsProtocol = window.location.protocol === "https:" ? "wss://" : "ws://"; const wsURL = wsProtocol + window.location.host + '/' + 'ws/messenger/group/' + group_id + '/'; offcanvasElements.forEach(element => { element.style.visibility = 'hidden'; element.classList.remove('show'); }); groupThreads.forEach(thread => { thread.classList.add('d-none'); }); conversationThreads.forEach(thread => { thread.classList.add('d-none'); }); if (conversationThread) { conversationThread.classList.remove('d-none'); } if (chatSocket !== null && chatSocket.readyState !== WebSocket.CLOSED) { chatSocket.close(); } chatSocket = new WebSocket(wsURL); chatSocket.onopen = function (e) { console.log('WebSocket connection established.'); }; chatSocket.onmessage = function (e) { const data = JSON.parse(e.data); const senderId = conversationThread.dataset.senderId; if (data.action === 'send_message') { let MessageContainer = conversationThread.querySelector('.py-6.py-lg-12'); let chatEmpty … -
configuring django with apache2
I have been working on my first django, which is a portfolio website. The site was working as intended when running on the django server, however when configuring it with apache on the linux server I few things have stopped working. I think it is is the way I have configure default.conf. this inculdes a button for downloading a rtf files and the CSS styling for the admin pages has not loaded. I have duplicated the 000-default.conf and called it django_project.conf and disabled the former and enabled the later. this is whats in that file: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/bashaar/rp-portfolio/static <Directory /home/bashaar/rp-portfolio/static> Require all granted </Directory> Alias /uploads /home/bashaar/rp-portfolio/uploads <Directory /home/bashaar/rp-portfolio/uploads> Require all granted </Directory> <Directory /home/bashaar/rp-portfolio/personal_portfolio> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/bashaar/rp-portfolio/personal_portfolio/wsgi.py WSGIDaemonProcess django_app python-path=/home/bashaar/rp-portfolio python-home=/homebashaar/. rp-portfolio/venv WSGIProcessGroup django_app I have also given apaches permission to these files: bashaar@portfolio:~$ ls -la total 52 drwxr-xr-x 6 bashaar bashaar 4096 Apr 23 10:19 . drwxr-xr-x 3 root root 4096 Apr 16 14:42 .. -rw------- 1 bashaar bashaar 9669 Apr 24 09:00 .bash_history -rw-r--r-- 1 bashaar bashaar 220 Apr 16 14:42 .bash_logout -rw-r--r-- 1 bashaar bashaar 3771 Apr 16 … -
Build a pre-decorated class with override_settings for faster client.login?
This makes a Django test using the test client run very much faster, where login security is not an important part of the test from django.test import TestCase, Client, override_settings @override_settings( PASSWORD_HASHERS = [ "django.contrib.auth.hashers.MD5PasswordHasher" ]) class Test2(TestCase): ... Is there any way to create my own TestCase subclass with the decorator built in, so I can code like this? (I keep having to look up that setting to override when I find my new test running slow! ) from myproject.utils import FastLoginTestCase class Test2( FastLoginTestCase): ... -
Trying to connect Django api to my local sql server databse but it returns the table as empty when testing it in insomnia
I have an sql server database that has mainly 3 tables and I want to create a crud web interface to manage it and I started with creating a Django api for the backend I followed some online guides to do it since I have never done something like this and after successfully getting the Django server running without errors I sent a GET request with insomnia to fetch a specific table named "memoire" and I got an empty string as a result when that table is filled with some data in my database and I don't where the problem might be I will attach the database settings in settings.py, the model.py file and views.py and if any further details are needed I will add them. this is database settings: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'MyDatabase', 'USER': 'django', 'PASSWORD': 'rayen1', 'HOST': 'localhost', # 'PORT':'', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', 'Trusted Connection': 'yes', }, } } this is models.py from django.db import models class NdfItem(models.Model): OrgShortName = models.CharField(max_length=255, null=True) prod_long_name = models.CharField(max_length=255, null=True) prod_short_name = models.CharField(max_length=255, null=True) pack_description = models.CharField(max_length=255, null=True) Category = models.CharField(max_length=255, null=True) Sub_Category = models.CharField(max_length=255, null=True) ret_price = models.FloatField(null=True) ImageSrc = … -
'DeferredAttribute' object has no attribute
im newbie in django.. i dont know why it's raise an error its models.py codes class PublishManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status=Post.Status.Draft) # Create your models here. # First Model class Post(models.Model): class Status(models.TextChoices): Draft = 'Dr', "Draft" Released = 'RL', "Released" Rejected = 'RJ', "Rejected" # Managers objects = models.Manager() Publishedss = PublishManager() # Author Author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="up") # information title = models.CharField(max_length=200) description = models.TextField(max_length=9000) Slug = models.SlugField(max_length=250) # Timing published = models.DateTimeField(timezone.now) created = models.DateTimeField(auto_now_add=True) Updated = models.DateTimeField(auto_now=True) # Status Status = models.CharField(max_length=2, choices=Status.choices, default=Status.Draft) # Sorting class Meta: ordering = ["-published"] indexes = [ models.Index(fields=['-published']) ] def __str__(self): return self.title raise an error and it's detail codes def post_detail(request, id): print(id) posts1 = get_object_or_404(Post, id=id, status=Post.Status.Draft) context = { "Post": posts1 } return render(request, "blog/detail.html", context) AttributeError at /blog/post/1 'DeferredAttribute' object has no attribute 'Draft' Request Method: GET Request URL: http://127.0.0.1:8000/blog/post/1 Django Version: 5.0.4 Exception Type: AttributeError Exception Value: 'DeferredAttribute' object has no attribute 'Draft' Exception Location: D:\Python\Python\Projects\project1\blog\views.py, line 24, in post_detail Raised during: blog.views.post_detail Python Executable: D:\Python\Python\Projects\project1\venv\bin\python.exe Python Version: 3.11.7 Python Path: ['D:\Python\Python\Projects\project1', 'C:\Program Files\JetBrains\PyCharm ' '2023.3.5\plugins\python\helpers\pycharm', 'D:\Python\Python\Projects\project1', 'C:\msys64\ucrt64\lib\python311.zip', 'C:\msys64\ucrt64\lib\python3.11', 'C:\msys64\ucrt64\lib\python3.11\lib-dynload', 'D:\Python\Python\Projects\project1\venv\lib\python3.11\site-packages'] Server time: Thu, 25 Apr 2024 08:14:02 +0000 -
views takes the values from template before making the post method
I'm creating a odd one out game. Basically user are presented with four pics , one being the odd one when user selects the odd picture score gets increased by 1. The problem I'm having is I'm sending 4 pics with one odd picture to the template . the template picks the same ids of 3 pictures but the id of odd picture is random (i want odd picture's id to be same as odd picture id). view.py is: def odd_one_out_game(request): # Get a random country country = random.choice(Country.objects.all()) print("Selected country:", country) # Get three random pictures from the selected country pictures = list(Picture.objects.filter(country=country).order_by('?')[:3]) print("Pictures from selected country:", pictures) # Get one random picture from a different country other_country = random.choice(Country.objects.exclude(pk=country.pk)) other_picture = random.choice(Picture.objects.filter(country=other_country)) other_picture_id = other_picture.id print(other_picture_id) print("Random picture from other country:", other_picture) # Add the other picture to the list of pictures pictures.append(other_picture) print("All pictures:", pictures) # Shuffle the pictures to mix up the order random.shuffle(pictures) print("Shuffled pictures:", pictures) #get the ids of the pictures picture_ids = [picture.id for picture in pictures] print("Picture IDs:", picture_ids) odd_score = request.session.get('odd_score', 0) total_guesses = request.session.get('total_guesses', 0) message = "" # Initialize message variable print("Initial score:", odd_score, "Initial total guesses:", total_guesses) if … -
For Django, 'sql_server.pyodbc' isn't an available database backend or couldn't be imported
I'm new to Django and trying to set up a DB Connection with SQL server db. Earlier we had mysql which was working fine, I'm having trouble connecting to sql server DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'AAAAA', 'USER': 'AAAAA', 'PASSWORD': 'AAAAA', 'HOST': 'AAAAA', 'PORT': '1433', } } Error: django.core.exceptions.ImproperlyConfigured: 'sql_server.pyodbc' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' Tried https://learn.microsoft.com/en-us/sql/connect/odbc/linux-mac/install-microsoft-odbc-driver-sql-server-macos?view=sql-server-ver16 doesn't work. Also, I have 2 question Is it a good idea to use third party library/drivers for SQL server? will it affect the performance compared to Mysql? -
UnboundLocalError: cannot access local variable 'form' where it is not associated with a value
I can't pass the form value into my template file, my views.py file: def Home(request): chat_group = get_object_or_404(GroupChat,group_name='TalkAboutPython') chat_message = chat_group.chat_message.all()[:30] if request.method == "POST": form = ChatMessageCreateForm(request.POST) if form.is_valid(): chat =form.save(commit=False) chat.auther = request.user chat.group = chat_group chat.save() return redirect('home') context = {"chat_message":chat_message,"form":form} return render(request, 'a_realchat/chat.html',context) form.py: class ChatMessageCreateForm(ModelForm): class Meta: model = GroupMessage fields = ['body'] I am passing the form to my .html file <form id="chat_message_form" method='POST' class="w-full"> {% csrf_token %} {{ form }} </form> when I try to send a message in the form Iam getting this error "cannot access local variable 'form' where it is not associated with a value" error showing here context = {"chat_message":chat_message,"form":form} -
How can I update data in vue.js?
I am new to vue.js and I try to update data. I write this code for pencil icon <i class="mdi mdi-pencil" v-b-modal.updateHolidayType ></i> I write this for modal <b-modal id="updateHolidayType" title="Update holiday" centered hide-footer> <ModalForm cardTitle="Update holiday" description="Update holiday" :holiday="holiday" @holidayUpdated="holidayUpdated"/> </b-modal> and this for form EditForm() { const holidayTypesId = this.holidayTypes .filter((e) => e.title === this.holidayTypeValue) .map((item) => item.id); session .put(`api/person/holiday/${this.holidayId}/update/`, { holidays_start_date: this.startDate, holidays_end_date: this.endDate, comments: this.comments, person: this.$route.params.id, holiday_type: holidayTypesId, }) .then(() => { this.alertShow = !this.alertShow; this.alertVariant = 'success'; this.alertMsg = 'Updated'; setTimeout(() => { this.$emit('holidayUpdated'); }, 1500); }) .catch((e) => { this.alertShow = !this.alertShow; this.alertVariant = 'danger'; this.alertMsg = e.response.data; }); } But when I click on pencil I go in empty page. When I click on pencil I want the page to show a modal which have the data and I can edit them. How can I do this? -
what is the meaning of this query in django
I am working on a django project, and taking over the project from other developers as they have left the project. I came across a query which I am not able to understand how it works, This is the query in question. provider_evaluations = ProviderEvaluation.objects.filter( customer_provider_relation_id__projectproviders__project_id=project_id, customer_provider_relation_id__provider_id=provider_id, and these are the models included in the query. class ProviderEvaluation(models.Model): provider_evaluation_criterias_id = models.ForeignKey(ProviderEvaluationCriterias, on_delete=models.CASCADE, null=True) evaluation = models.CharField(max_length=255, null=True) comment = models.TextField(null=True, blank=True) created_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, null=True) workflow_step = models.ForeignKey(WorkflowStep, on_delete=models.CASCADE, default=None, null=True) customer_provider_relation_id = models.ForeignKey(CustomerProviderRelation, on_delete=models.CASCADE, null=True, default=None) def __str__(self): return f"{self.provider_evaluation_criterias_id} - {self.evaluation}" class CustomerProviderRelation(models.Model): customer_tenant_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, related_name='customer_tenant', limit_choices_to={'model__in': ['customer']}, ) provider_tenant_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, related_name='provider_tenant', limit_choices_to={'model__in': ['provider']}, ) customer_tenant_id = models.PositiveIntegerField() provider_tenant_id = models.PositiveIntegerField() customer_tenant = GenericForeignKey('customer_tenant_type', 'customer_tenant_id') provider_tenant = GenericForeignKey('provider_tenant_type', 'provider_tenant_id') customer_id = models.ForeignKey(Customer, on_delete=models.CASCADE) provider_id = models.ForeignKey(Provider, on_delete=models.CASCADE) def save(self, *args, **kwargs): # Assign values to content type and object ID fields based on the instance being saved if isinstance(self.customer_tenant, Customer): self.customer_tenant_type = ContentType.objects.get_for_model(Customer) self.customer_tenant_id = self.customer_tenant.id if isinstance(self.provider_tenant, Provider): self.provider_tenant_type = ContentType.objects.get_for_model(Provider) self.provider_tenant_id = self.provider_tenant.id super().save(*args, **kwargs) def __str__(self): return f"CustomerProviderRelation ID: {self.id}" class ProjectProviders(models.Model): STATE_CHOICES = [ ('searched', 'Searched'), ('initiated', 'Initiated'), ('completed', 'Completed'), ('closed', 'Closed'), ('rejected', 'Rejected'), ] project_id = … -
django with order by receiving duplicate data
I don't know what is happening here already. I can't figured this out. I am using a pagination and fetching a lot of data in my Person model. I have sort from descending order and ascending order but when the data is returned and i go to other pages of my pagination, i keep receiving multiple duplicates of data from the other pages. Why? Can anyone explain or solution for this? Here is my code: def get_queryset(self, *args, **kwargs): if self.request.user.team: queryset = self.request.user.team.leads.all() else: queryset = super().get_queryset(*args, **kwargs) ordering = self.request.query_params.get("ordering", "") if ordering == "total_email_sent": queryset = ( queryset.annotate( total_email_sent=Count( "prospectsequenceevent__scheduledEmail", filter=Q( prospectsequenceevent__status="scheduled", prospectsequenceevent__scheduledEmail__status=0, ), ) ) .distinct() .order_by("total_email_sent") ) elif ordering == "-total_email_sent": queryset = ( queryset.annotate( total_email_sent=Count( "prospectsequenceevent__scheduledEmail", filter=Q( prospectsequenceevent__status="scheduled", prospectsequenceevent__scheduledEmail__status=0, ), ) ) .distinct() .order_by("total_email_sent") ) elif ordering == "total_opened": queryset = ( queryset.annotate( total_opened=Count( "emails", filter=models.Q( emails__trackings__opened=True, emails__created_by=self.request.user, ), ) ) .distinct() .order_by("total_opened") ) elif ordering == "-total_opened": queryset = ( queryset.annotate( total_opened=Count( "emails", filter=models.Q( emails__trackings__opened=True, emails__created_by=self.request.user, ), ) ) .distinct() .order_by("-total_opened") ) elif ordering in ["total_click_count", "-total_click_count"]: # Use conditional aggregation to calculate total click count queryset = queryset.annotate( total_click_count=Coalesce( Sum( Case( When( emails__created_by=self.request.user, then=F("emails__click_tracking__click_count"), ), default=Value(0), output_field=IntegerField(), ) ), Value(0), ) ).distinct() … -
Heroku: H18 right before my app should download .mp4
I'm having trouble with my app that generates 5-8sec videos. The entire request takes about 15 seconds, the app does all the steps required, but when it's time to download the video file it fails. I'm deploying the same python version as I run locally python-3.11.5. I'm running the app right now as we speak locally with no issue. Web console returns this error: generate-reel/:1 Failed to load resource: net::ERR_CONTENT_LENGTH_MISMATCH (index):562 Error in generating reel: TypeError: Failed to fetch Headers have both Content-Length and Content-Type correctly, but when I go to "Response" theres nothing... I copied header: Request: POST /generate-reel/ HTTP/1.1 Accept: */* Accept-Encoding: gzip, deflate, br, zstd Accept-Language: en-GB,en-US;q=0.9,en;q=0.8 Connection: keep-alive Content-Length: 14 Content-Type: application/json Cookie: sessionid=lcjfb0cgcd0fzth59hd95wg7g4jcl9m5; csrftoken=DcqP62fbGQkoyKTdR1tWnUrF2degrOLD; lastReset=Thu Apr 25 2024; usageCount=3 Host: vast-everglades-19722-937b6a99a857.herokuapp.com Origin: https://vast-everglades-19722-937b6a99a857.herokuapp.com Referer: https://vast-everglades-19722-937b6a99a857.herokuapp.com/ Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: same-origin User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 X-CSRFToken: DcqP62fbGQkoyKTdR1tWnUrF2degrOLD sec-ch-ua: "Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99" sec-ch-ua-mobile: ?0 sec-ch-ua-platform: "macOS" Response: HTTP/1.1 200 OK Report-To: {"group":"heroku-nel","max_age":3600,"endpoints":[{"url":"https://nel.heroku.com/reports?ts=1714013226&sid=e11707d5-02a7-43ef-b45e-2cf4d2036f7d&s=yq0l506BqIrW%2F3MHhVj%2Bj2D7GdjU4YvL1xFQNDkYycQ%3D"}]} Reporting-Endpoints: heroku-nel=https://nel.heroku.com/reports?ts=1714013226&sid=e11707d5-02a7-43ef-b45e-2cf4d2036f7d&s=yq0l506BqIrW%2F3MHhVj%2Bj2D7GdjU4YvL1xFQNDkYycQ%3D Nel: {"report_to":"heroku-nel","max_age":3600,"success_fraction":0.005,"failure_fraction":0.05,"response_headers":["Via"]} Connection: keep-alive Server: gunicorn Date: Thu, 25 Apr 2024 02:47:23 GMT Content-Type: video/mp4 X-Frame-Options: DENY Content-Length: 8478634 Vary: Cookie X-Content-Type-Options: nosniff Referrer-Policy: same-origin Cross-Origin-Opener-Policy: same-origin Set-Cookie: sessionid=lcjfb0cgcd0fzth59hd95wg7g4jcl9m5; expires=Thu, 09 … -
When i press edit profile i get value error
trying to make an edit page where you can upload a profile picture and add various things to your profile, but when i click on edit profile i get "ValueError at /profile/ The 'profile_image' attribute has no file associated with it." models.py from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=50, null= True) designation = models.CharField(max_length=100, null= True) profile_image = models.ImageField(null=True, blank = True, upload_to="static/images/") profile_summary = models.TextField(max_length=300, null= True) city = models.CharField(max_length=100, null= True) state = models.CharField(max_length=100, null= True) county = models.CharField(max_length=100, null= True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() urls.py from .views import HomeView, UserProfile, register, user_login, user_logout from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path("", HomeView.as_view(),name="home-page"), path("profile/", UserProfile.as_view(), name="user-profile"), path("register/", register, name="register"), path("login/", user_login, name="login"), path("logout/", user_logout, name="logout"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate, logout from .forms import RegisterForm from django.contrib.auth.forms import AuthenticationForm from django.contrib import messages from .models import Profile from django.core.files.base import ContentFile class HomeView(View): def get(self, request): return render(request, "home.html") def register(request): … -
ModuleNotFoundError: No module named 'project_name'
I tried to make 'load_data.py' file, but error confound me. Traceback (most recent call last): File "/Users/name/Downloads/Dev/culture/culture/api/load_data.py", line 4, in <module> from models import Theatre File "/Users/name/Downloads/Dev/culture/culture/api/models.py", line 4, in <module> class Theatre(models.Model): ... ModuleNotFoundError: No module named 'culture' The project has only one app 'api' and 'load_date.py' in it. Project name is 'culture'. settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api.apps.ApiConfig', ] i tried export DJANGO_SETTINGS_MODULE=culture.settings but it didnt help. -
Single dropdown with values from two tables
I may be going about this entirely wrong. I'm new to Django, so sometimes the way I think of things doesn't seem to be the easy Django way to do it. I've got two tables: class LocationGroup(models.Model): #Fields ##Location Group ID - auto generated ID field id = models.AutoField('Location Group ID', primary_key = True) ##Location Group Name name = models.CharField('Location Group Name', max_length=200, help_text='Location Group name') def __str__(self): """String for representing the Model object.""" return self.name class Meta: verbose_name = "Location Group" verbose_name_plural = "Location Groups" and class Location(models.Model): #Fields ##Location ID - auto generated ID field id = models.AutoField('Location ID', primary_key = True) ##Location name name = models.CharField('Location Name', max_length=200, help_text='Location name') ##Location Group - link location to a Location Group group = models.ManyToManyField('LocationGroup', verbose_name='Location Group', blank=True, help_text='...') ...etc Then I have my forms.py calling as follows: class MyForm(forms.ModelForm): class Meta: model = Call fields = ['location', ...etc] This all works well and I can pick a location and add it to the database with the other values that are on that form/model. But what I'd like to do, is include the values from the locations plus the location groups. And to go further, if a value is picked … -
Django: how to store email credentials when sending email from a Django application
What is a standard or safe way to store my Google Workspace email credentials in my first Django project? I've tried to store the password in an .env file, but I get all kinds of error messages (e.g., "decouple module not recognized"--despite my alternately using pip install decouple and pip install python-decouple). But more importantly, I suspect it's not the best approach anyway. My research seems to whittle the options down to eliminating my password altogether and to somehow API into Google from within my app (to send out emails to my customers from my Google Workspace email). Is that would you recommend? Is there an simpler/better way? -
StreamingHttpResponse redirect it Django
I am facing problem in showing the status in the scanned this basically scans the QR of a Coupon and tells that weather the coupon is valid or not i have stored the status of each coupon in the database along with coupon id i have figured out the comparison part and to update the database But I'm not able to display the status of the i.e weather the coupon is valid or not the below is the camera.html code {% include 'header.html' %} <div class="w3-main" style="margin-left:300px;margin-top:60px;"> <div> <img src="/cameraOn/"> {{print}} kjhjvh </div> </div> {% include 'footer.html' %} The below is the views.py code def scan_qr(request): return render(request, 'camera.html') @gzip.gzip_page def cameraView(request): stat = False cam = qr_scanner.VideoCamera() return StreamingHttpResponse(gen(cam, stat), content_type = "multipart/x-mixed-replace;boundary=frame") def gen(camera, stat): while not stat: frame, stat = camera.get_frame() if stat: yield b'--text \r\n' + b'Content-Type: text/plain\r\n\r\n' + b'Hello\r\n\r\n' yield (b'--frame \r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') The below is my qr_scanner.py import cv2 import threading from pyzbar.pyzbar import decode from services.models import Service class VideoCamera(object): thread_flag = True scanned_otp = 'no_data' def __init__(self): self.video = cv2.VideoCapture(0) _, self.frame = self.video.read() self.qr_scanned = False threading.Thread(target=self.update, args=()).start() def release_camera(self): self.video.release() self.thread_flag = False def get_frame(self): … -
Operating AI program by using WebODM plugin
I created an AI Python program and made the program screen visible through a plug-in. I try to run a program written in Python on that screen, but it doesn't work. How do I get it to run? To run an AI program, you must run Anaconda 3, run a virtual environment inside it (if it does not exist, create it and run it), and run it after completing the installation of the required programs. These must be included in the implementation process. I added new url ''' url(r'^airesults/$', app_views.aiwork, name='results') ''' in \WebODM\app\urls.py and create new function 'aiwork' in \WebODM\app\views\app.py and make new coreplugin 'aiwork' by copying and modifying the 'cloudimport'. -
How can I use stored procedures in Django with MySQL and run 'python manage.py migrate' without issues?
Context: I'm working on a project using Django with the Django REST framework to build an API. My database is MySQL, and I'm using XAMPP as my local development environment. Problem: I need to use stored procedures in my Django application to perform specific operations in my MySQL database. However, I'm facing difficulties integrating the stored procedures with Django, and I'm also experiencing issues when running python manage.py migrate. Additional Details: I have created stored procedures directly in my MySQL database using phpMyAdmin. I'm using Django's ORM to interact with the database in other parts of my application. I would like to be able to call the stored procedures from my Django application and run python manage.py migrate without errors to ensure that my database is properly synchronized with Django's models. Relevant Files and Code: utils.py - File containing the calls to the stored procedures. models.py - File where I define Django models representing my database schema. Questions: What is the best way to use stored procedures in Django, particularly with a MySQL database? How can I ensure that the stored procedures are compatible with Django's migration process (python manage.py migrate)? Are there any special considerations I should be aware … -
Seeing yellow lines below django.shortcuts in VS CODE
I'm new in Django, And I'm seeing yellow lines below everything I include from Django like django.db import models Seeing yellow lines on Django.db and model also in app.djando In all of the Django imported stuff The food is working totally fine but whenever i see a video there is nothing like this And as much as I know it generally shows when you haven't installed a Library or package When I hover on it, it shows "Import "django.shortcuts" could not be resolved from sourcePylancereportMissingModuleSource (module) shortcuts" I have tried like many solutions shown in Google result and also on chatgpt like Reinstalling the Django checking the typho mistakes Reinstalling python Updating all two latest version But I'm unable to find a solution -
Persistent storage in a Python app hosted in Heroku
I have an app that I recently deployed to Heroku. I wrote the app in Python utilizing the Django framework. When I create user accounts via my admin dashboard in the app I see the user accounts after being created. After a while has passed, I check and the new user accounts I created has disappeared. My thoughts are that this is down to allocated resources/dynos and everything is stored only for a session and once the session ends all changes are reverted to the state the app was in when first uploaded. The database is SQLite. I am trying to determine how I can have new users stay in the database or how other apps hosted on the platform (Heroku) allow user registration without the user accounts disappearing after a session ends. I have searched and read documentation on Heroku, Googled the problem and found nothing that matches my situation. One issue I read about mentioned an issue uploading static files that would disappear after sessions ended and how integrating 3rd party storage could resolve that. I understand that solution, but for user creation and registration, this would not be feasible. Thanks in advance! -
Django default connections.cursor() not parsing JSONB into DICT despite using PSYCOPG3
I am switching an old codebase from Django ~2 to Django 4.2.1. Along side this switch, I upgraded psycopg2 to psycopg (also known as psycopg3), but this switch has caused my cursor to incorrectly fetch rows from my PostgreSQL database. I am receiving STR instead of DICT when selecting JSONB objects in my database Important: When I use psycopg.connect directly, all of the behavior returns to what I expected. It is only when I am using the default django connection. from django.db import connection Here I fetch some json objects and check the type. with connection.cursor() as cursor: cursor.execute("select json_file from json_file") # These are of type jsonb for row in cursor.fetchall(): type(row[1]) This usually returns dict but is now returning str Here is my DATABASES variable in settings: 'default': {'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432, 'CONN_MAX_AGE': None, 'CONN_HEALTH_CHECKS': False, 'ENGINE': 'django.db.backends.postgresql', } Here is Django's Connection + Cursor > connections['default'].connection <psycopg.Connection [IDLE] (host=db database=postgres) at 0x...> > connections['default'].connection.cursor() <django.db.backends.postgresql.base.Cursor [no result] [IDLE] (host=db database=postgres) at 0x...> Here is psycopg's Connection + Xursor > psycopg.connect("...") <psycopg.Connection [IDLE] (host=db database=postgres) at 0x...> > psycopg.connect("...").cursor() <psycopg.Cursor [no result] [IDLE] (host=db database=postgres) at 0x...> -
The problem with arabic language in xhtml2pdf django
Im useing xthml2pdf for generate invoice with arabic language. I searched a lot to solve the problem and followed all the steps, but I don't know why it doesn't work. Utils code: def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), dest=result, encoding='UTF-8') if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') View code: pdf = render_to_pdf('pdf/invoice.html'), context) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "invoice-%s.pdf" % invoice_number content = "inline; filename= %s" % filename response['Content-Disposition'] = content return response And finally the HTML code: <!DOCTYPE html> <html lang="ar" dir="rtl"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta charset="UTF-8"> <style> @font-face{font-family:samim; src: url('/assets/fonts/Shabnam-FD.ttf') } body{ background: #fff; font-family: samim !important; direction: rtl !important; } </style> </head> <body> <div> <pdf:language name="arabic"/> <p>سلام</p> </div> </body> </html> But what is generate in the end -
The problem of not generic refresh and access token for users
I have a problem with the code written with Python and Django framework I wrote a custom model and used Abstrcatuser in it, and instead of the username field, I used the phone number field. Now, when I enter the login address in the api I wrote and want to get the access token and refresh token, it creates only these things for the superuser and tells the other users that the phone number or password is wrong if they are also correct. I also use jwt. I tried to make some changes in the code, but I didn't find anything important -
clickable label for radio in django
i want to have clickable labels for my radio buttons in django but i cant click and the values are not registered in the database , its like just text <div class="probprior"> <div class="radio-container"> <label for="id_is_observer"> {{register_user_form.is_observer}} Observer </label> <label for="id_is_technician"> {{register_user_form.is_technician}} Technician </label> <label for="id_is_self_service"> {{register_user_form.is_self_service}} Self Service </label> <label for="id_is_staff"> {{register_user_form.is_staff}} Staff </label> </div> </div> and im using this style too in css file .radio-container input[type="radio"] {display: none;} .radio-container input[type="radio"]:checked + label {background: #F7B1AB;border: 1px solid rgba(0,0,0,.1);}