Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What are the effects of using Django models as global variables in views?
Here I have written 2 views functions. If there is any difference between these, could you please explain which one will be fast? #Views1.py def myview1(request): q=mymodel.objects.all() . . #rest of the code return response #Views2.py x=mymodel.objects.all() def myview2(request): q=x . . #rest of the code return response Suppose 'mymodel' is not updating, in this case using queryset as a global variable so that multiple view functions can use it without hitting the database for each request is a good idea?? Any kind of extra help/idea will be highly appreciated. -
Class based view permission with multiple actions
I want to write a callable Permission class for a generic class view to check multiple actions inside the view. -
How do I access another model's database to carry out some calculation in my current model field in Django?
First of all, this sample project is available here in order for anyone to take a look at it and let me know where I am going wrong. I have two models, Package and Receivables there. In Package, there is a field total_package and in Receivables, there are two fields initially, discount and approved_package. I want to access total_package and from that I want to subtract discount to auto-populate approved_package field. If you look into the project's test.js file, I tried to achieve the same using JS, but that doesn't fulfil my intention. I do not know where I went wrong there. I also want to learn how I can achieve that using pure django way. Can someone help me? The models: class Package(models.Model): rt_number=ForeignKey(Patient, on_delete=CASCADE) diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE) treatment=ForeignKey(Treatment, on_delete=CASCADE) patient_type=ForeignKey(PatientType, on_delete=CASCADE) date_of_admission=models.DateField(default=None) max_fractions=models.IntegerField(default=None) total_package=models.DecimalField(max_digits=10, decimal_places=2) class Receivables(models.Model): rt_number=ForeignKey(Patient, on_delete=CASCADE) discount=models.DecimalField(max_digits=9, decimal_places=2, default=None) approved_package=models.DecimalField(max_digits=10, decimal_places=2, default=None) proposed_fractions=models.IntegerField() done_fractions=models.IntegerField() base_value=models.DecimalField(max_digits=10, decimal_places=2) expected_value=models.DecimalField(max_digits=10, decimal_places=2) Hope to receive some help with this issue. Thanks in advance. -
Value Error : Cannot assign "<ContentType: config>": the current database router prevents this relation
I am using multiple databases in Django and connected default SQLite and PostgreSQL db in the settings.py. setting.py : DATABASE_ROUTERS = ['routers.db_routers.AppRouter'] DATABASE_APPS_MAPPING = {'product': 'product_db',} DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'postgres': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'product', 'USER': 'postgres', 'PASSWORD':'password', 'HOST':'localhost' } } And also made the db_routers.py in the routers folder: class AppRouter: """ A router to control all database operations on models in the product application. """ def db_for_read(self, model, **hints): """ Attempts to read user models go to product_db. """ if model._meta.app_label == 'product': return 'product_db' return 'default' def db_for_write(self, model, **hints): """ Attempts to write user models go to product_db. """ if model._meta.app_label == 'product': return 'product_db' return 'default' def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the user app is involved. """ if obj1._meta.app_label == 'product' or \ obj2._meta.app_label == 'product': return True return False def allow_migrate(self, db, app_label, model_name='default', **hints): """ Make sure the auth app only appears in the 'product_db' database. """ if app_label == 'product': return db == 'product_db' return None here, it's model.py: class Product(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2) weight = models.DecimalField(max_digits=10, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) updated_at … -
Submitting multiple django forms with the user model
I’m out of ideas and really need some help Does anyone know an expert django dev or is an expert in django? I need some help with submitting multiple django forms whilst using the built in User model. Thanks -
Python Flask | How to pass results from a background task to a currently active html page
To setup a simple html front-end and python flask back- Create a html script (index.html) and save D:\Projects\test_backgroundtask\templates\views <html> <section> <div> <h>Test background task</h> </div> </section> </html> Create a python script and save D:\Projects\test_backgroundtask: from flask import Flask, render_template, request import pandas as pd app = Flask(__name__) @app.route('/', methods=['GET']) def index(): return render_template('views/index.html') @app.route('/post', methods=['POST']) def post(): return "recived: {}".format(request.form) if __name__ == "__main__": app.run( port = '5004') To create a background task, flask has a package called flask_executor Updated python script using excutor to create a background from flask import Flask, render_template, request import pandas as pd from flask_executor import Executor global input_val app = Flask(__name__) def background_task_func(input_val): if input_val==1: data = {'Name': ['Tom', 'Joseph', 'Krish', 'John'], 'Age': [20, 21, 19, 18]} test_val= pd.DataFrame(data) print(test_val) @app.route('/', methods=['GET']) def index(): global input_val input_val=1 executor.submit(background_task_func,input_val) return render_template('views/index.html') @app.route('/post', methods=['POST']) def post(): return "recived: {}".format(request.form) if __name__ == "__main__": executor = Executor(app) app.run( port = '5004') Required Output: Once the results are completed, a button called view must be enabled and when the user clicks on it, the table containing test_val will be displayed. Additional Info NB: I use Django within ... in my html script. An example of how I used … -
Django Drop down with user input
Hi I am developing an application using django framework, where I have an use case where in a form user have to type the identification number which should have autocomplete suggestions in dropdown. if the number is in the database it should be populated in the dropdown and user can select it and submit the form. else if the identification number is not in the database then user should be able to enter the number manualy and should be able to submit the form. Also the newly entered identification number should be added in the database. So what is the best approach to achieve this purrely in django not using Jquery Ajax. -
Camera Not Opening when Deployed On server Django/Python
Unable to open Camera On server, where its the same copy with Same settings cam = cv2.VideoCapture(0) Used this to initialise camera (webcam) and below code for processing the data stream and below image shows the error on server click here to view the error def identify_faces(video_capture): buf_length = 10 known_conf = 6 buf = [[]] * buf_length i = 0 process_this_frame = True while True: ret, frame = video_capture.read() small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25) rgb_frame = small_frame[:, :, ::-1] if process_this_frame: predictions = predict(rgb_frame, model_path="folder/folder/models/trainedmodel.clf") process_this_frame = not process_this_frame face_names = [] for name, (top, right, bottom, left) in predictions: top *= 4 right *= 4 bottom *= 4 left *= 4 cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2) cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED) font = cv2.FONT_HERSHEY_DUPLEX cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1) identify1(frame, name, buf, buf_length, known_conf) face_names.append(name) buf[i] = face_names i = (i + 1) % buf_length cv2.imshow('Video', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break video_capture.release() cv2.destroyAllWindows() -
submit order and redirect to an individual platform
i am trying to develop a django webapp .i want the user to be able to submit other and get redirected to the user's platform where the user sees all his orders . i want a system where the user can make orders and get redirected to a page where will see all his orders client form: {% extends 'base.html' %} {% load static %} {% load crispy_forms_tags %} {% block content %} {% if user.is_authenticated %} <div class="container" style="width: 50rem;"> <div class="col-md-10 offset-md-1 mt-5"> <div class="jumbotron"> <!--<h3 id="form-title">Job Specification </h3>--> <h3 class="display-4" style="text-align: center;">Service Request</h3> <p id="form-title" style="color: #343a40; text-align: center;">Please provide us with the following information</p> <hr class="my-4"> <form action="{% url 'clients:add_item' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="row"> <div class="col-md-4"> {{ form.job_name|as_crispy_field }} </div> <div class="col-md-8"> {{ form.text_description|as_crispy_field }} </div> </div> <div class="row"> <div class="col-md-4"> {{ form.location|as_crispy_field }} </div> <div class="col-md-8"> {{ form.address|as_crispy_field }} </div> </div> <div class="row"> <div class="col-md-6"> <!--{{ form.phone|as_crispy_field }}--> <input style="height: 2.5rem;margin: 0 0 8px 0; width: 100%; text-align: center; position: relative; " type="text" name="phone" value="{{ user.details.phone }}" readonly><br> </div> <div class="col-md-6"> <input style="height: 2.5rem;margin: 0 0 8px 0; width: 100%; text-align: center; position: relative; " type="text" name="email" value="{{user.email}}" placeholder=" email " … -
How to do Windows Authentification for Python servers like Cherrypy and Django?
Web are developing web servers in python. At first we usually have a cherrypy server serving the static files and a django server over WSGI. The django server is serving the application logic over a REST interface. With this infrastructure we would like to write a website that does Windows authentification. How to do that? Does a browser automatically sends some header information that we can verify against an active directory? -
how to give condition to annotation django
i'm trying to give condition to an annotate field to return a BooleanField from django.db.models import Case,When,BooleanField def lists(request): lists = Employee.objects.annotate(is_expire=Case(When( date_of_expire__lte=timezone.now() ),output_field=BooleanField())).order_by('-date_of_expire') #others but it doesnt work , still return all existing data even some of object's date_of_expire is less than current time is there something else i should try please ? -
Populate Django Form field-labels from a database model when calling this Form thru a sidebar menu item
I am new to Python, Django and web programming, so may be this is a dumb question or conceptually a wrong logic. I am trying to call an entry Form from sidebar menu item and want this Form fields to have labels from a database model, so that same form/database model can be used for different purposes. This sidebar menu is populated using Django-MPTT. This form pop ups normally with it's original labels when clicking the menu item, but if I try to set it's field labels from database model containing relative labels, it gives error: 'QuerySet' object has no attribute 'task_t3'. Following is code lines from views.py where this error occur: ctlobj = TaskControl.objects.filter(task_group_no=5) taskdetail_form = TaskDetailForm() taskdetail_form.task_3.label = ctlobj.task_t3 -
edit and update user model in django
i have registration and login forms that work well, but I am trying to edit the user profile but i don't seem to make it work, below are my codes, can you please point me the mistake i am making? /views.py @login_required() def profile(request): if request.method == 'POST': # current_user = UserProfile.objects.get(username=request.user) form = UserDetailsUpdate(request.POST, instance=request.user) if form.is_valid(): form.save(commit=True) return redirect('profile') form = UserDetailsUpdate(instance=request.user) return render(request, 'profile.html', {'form': form}) /models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) sex = models.CharField(max_length=20, blank=True) website = models.URLField(blank=True) image = models.ImageField(blank=True) def __str__(self): return self.user.username /forms.py class UserDetailsUpdate(forms.ModelForm): class Meta: model = UserProfile fields = ('image', 'website', 'sex') -
How to return list of one-to-one relation objects
I have a model named Profile which is OneToOne related to User model. Profile has ManyToMany Field named muting_users. I need to return list of muting_users from API View show below but I only managed to return list of Profiles. How can I return list of users in listed case(code below)? class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) muting_users = models.ManyToManyField('self', blank = True, related_name = 'muted_by', symmetrical = False) class MutingUserListAPIView(generics.ListAPIView): serializer_class = serializers.UserSerializer permission_classes = [IsAuthenticated] def get_queryset(self): request_user = self.request.user return request_user.profile.muting_users.all() # < it returning list of Profile but should return list of Users -
Apache + django + mod_wsgi 503 error for production website
I have created django app on linode vps server and running wordpress & django on same server. everything seems to be working, but django website in production is giving 503 error. I have setup reverse proxy for port 8000 & it works fine with manage.py runserver 0:8000 command. I gave apache permission to django folder as well, but still getting this error. [Mon Jul 12 06:54:15.468278 2021] [proxy:error] [pid 11024] (111)Connection refused: AH00957: HTTP: attempt to connect to 45.79.124.30:8000 (45.79.124.30) failed [Mon Jul 12 06:54:15.468660 2021] [proxy_http:error] [pid 11024] [client 52.95.75.18:27815] AH01114: HTTP: failed to make connection to backend: 45.79.124.30 [Mon Jul 12 06:54:15.636484 2021] [proxy:error] [pid 11122] (111)Connection refused: AH00957: HTTP: attempt to connect to 45.79.124.30:8000 (45.79.124.30) failed [Mon Jul 12 06:54:15.636528 2021] [proxy_http:error] [pid 11122] [client 52.95.75.18:23253] AH01114: HTTP: failed to make connection to backend: 45.79.124.30, referer: https://test.factory2homes.com/ -
Django Deadlock occurring randomly
Running django in python 3.7.9. I am using channels so daphne used but even when I using gunicorn the same results is obtained. The error below is appearing randomly. ERROR 2021-07-12 11:55:07,478 HTTP GET /static/customer/assets/js/jquery.min.js 500 [0.71, 127.0.0.1:55466] ERROR 2021-07-12 11:55:07,479 Exception inside application: Single thread executor already being used, would deadlock Traceback (most recent call last): File "/home/x/.pyenv/versions/3.7.9/lib/python3.7/site-packages/channels/http.py", line 192, in __call__ await self.handle(body_stream) File "/home/x/.pyenv/versions/3.7.9/lib/python3.7/site-packages/asgiref/sync.py", line 410, in __call__ "Single thread executor already being used, would deadlock" RuntimeError: Single thread executor already being used, would deadlock I don't think this error has much do with deadlock, but at times they are appearing together. ERROR 2021-07-12 11:55:07,478 HTTP GET /static/customer/assets/js/jquery.min.js 500 [0.71, 127.0.0.1:55466] Could someone please tell me the possible cause and solution? If I've missed out anything, over- or under-emphasized a specific point, let me know in the comments. Thank you so much in advance for your time. -
Pass context when serializing queryset in django
I'm new to Django and I'm trying to serialize a queryset using DjangoSerializer but one of a SerializerMethodField requires user instance. So how can I pass user instance in a context? projects = Project.objects.all().order_by('name') serializer = ProjectSerializer(projects, context={'request': request}, many=True) You can assume that request has user in it. Thanks for helping. -
Postgresql not working showing fatal error
I am trying to work with Postgresql as my database for website that i am making in django. However, the postgresql and the pg-admin tool is installing without any eror I am unable to open the database. First i thought it was compatibility issue as I my os is windows 7 ultimate bbut then i tried to install all the previous versions of the database and it still doesn't open. the error i am getting is: -------------------------------------------------------- Python Path: "C:\Program Files\PostgreSQL\13\pgAdmin 4\python\python.exe" Runtime Config File: "C:\Users\Intel\AppData\Roaming\pgadmin\runtime_config.json" pgAdmin Config File: "C:\Program Files\PostgreSQL\13\pgAdmin 4\web\config.py" Webapp Path: "C:\Program Files\PostgreSQL\13\pgAdmin 4\web\pgAdmin4.py" pgAdmin Command: "C:\Program Files\PostgreSQL\13\pgAdmin 4\python\python.exe -s C:\Program Files\PostgreSQL\13\pgAdmin 4\web\pgAdmin4.py" Environment: - ALLUSERSPROFILE: C:\ProgramData - APPDATA: C:\Users\Intel\AppData\Roaming - C:\Program Files\Java\jdk-16.0.1: C:\Program Files\Java\jdk-16.0.1\bin - CHROME_CRASHPAD_PIPE_NAME: \\.\pipe\crashpad_3400_DAGOSZHYAFRGHRAW - CHROME_RESTART: NW.js|Whoa! NW.js has crashed. Relaunch now?|LEFT_TO_RIGHT - CommonProgramFiles: C:\Program Files\Common Files - CommonProgramFiles(x86): C:\Program Files (x86)\Common Files - CommonProgramW6432: C:\Program Files\Common Files - COMPUTERNAME: INTEL-PC - ComSpec: C:\Windows\system32\cmd.exe - FP_NO_HOST_CHECK: NO - HOMEDRIVE: C: - HOMEPATH: \Users\Intel - JAVA_HOME: C:\Program Files\Java\jdk-16.0.1 - JAVA_HOME: C:\Program Files\Java\jre1.8.0_291\bin\server\jvm.dll: PATH: C:\Program Files\Java\jre1.8.0_291\bin - LOCALAPPDATA: C:\Users\Intel\AppData\Local - LOGONSERVER: \\INTEL-PC - NUMBER_OF_PROCESSORS: 2 - OS: Windows_NT - Path: C:\Program Files\Common Files\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\; C:\Program Files\Java\jdk-16.0.1\bin;C:\Users\Intel\AppData\Local\Programs\Python\Python37;C:\Users\Intel\AppData\Local\Programs\Python\Python37\Scripts;C:\Program Files\PostgreSQL\13\bin;;C:\Program Files\JetBrains\PyCharm 2021.1.2\bin;;F:\Microsoft VS Code\bin - PATHEXT: .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC - PGADMIN_INT_KEY: … -
Django channels + send websocket message after with post request
i have a problem with my app. My django channels and websocket works absolutely fine, when i send a message from JS(inside rendered html) the message is going into websocket and after that to the data base(asynchronously). But when i am trying send the message before POST request Render, it throws an error. #here everything works fine: def room(request, room_name): messages = message.objects.all() texts = [] for i in messages: texts.append(i.text) last_lines = texts[-20:] vars = { "room_name": room_name, "messages": last_lines, } print() if request.method == "POST": vars["post_d"] = request.POST.get("desc") print(vars["post_d"]) # ws = create_connection("ws://127.0.0.1:8000/ws/chat/loobby/") # time.sleep(2) # ws.send(json.dumps({"message": message})) return render(request, "chat/room.html", vars) return render(request, "chat/room.html", vars) #======================================================= System check identified no issues (0 silenced). July 12, 2021 - 08:26:23 Django version 3.1.3, using settings 'onionChat.settings' Starting ASGI/Channels version 3.0.3 development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Post request from c# console app HTTP POST /chat/loobby/ 200 [0.10, 127.0.0.1:3261] My test.py file that sends python websocket message (also works well) changes shows in the db and websocket in the web browser. import json import time import asyncio from websocket import create_connection async def send(message): ws = create_connection("ws://127.0.0.1:8000/ws/chat/loobby/") time.sleep(2) ws.send(json.dumps({"message": message})) print("here") if __name__ == "__main__": asyncio.run(send("nothing")) #================================================================== … -
Client side encryption in Django. Encrypt files in client as well as server before storing
A beginner I’m building a Django project in which I’m trying to store files (any data type upto 1GB) on my heroku server. But I want to encrypt it before sending and then encrypt again at server before storing it. Decryption will be the same in reverse. I need help finding right client side frameworks and some already built resources to the same for reference. The file isn’t meant to be accessed by any third person as of now, so only working on AES encryption method. RSA encryption ideas are also welcomed for future updates. -
Django can't save form data
I'm working on a django project and faced a weird problem. I am using `model form` for this. Even though I wrote `form.save()` as you can see it below, new data is not saved. # in views.py class ProductUpdateView(self, request, product_id): def get(self, request, product_id): product = get_object_or_404(Product, id=product_id) name = product.name id = product.id form = ProductEditForm(instance=product) context = { "form": form, "name": name, "id": id, } return render(request, "management/product_detail.html", context) def post(self, request, product_id): form = ProductEditForm(request.POST, instance=request.user) product = get_object_or_404(Product, id=product_id) if form.is_valid(): form.save() messages.success(request, f"'{product.name}' is successfully updated!") return redirect("products_list") else: messages.warning(request, "form is invalid") return redirect("products_list") # in forms.py class ProductEditForm(forms.ModelForm): class Meta: model = Product fields = ["name", "description", "price", "is_available", "category"] def __init__(self, *args, **kwargs): super(ProductEditForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs["class"] = "form-control" Thank you in advance. -
Error In Accessing the Camera in Face Recognition Application in Centos server in django application
I have implemented the Face Recognition Module in Django Application As I am not able to access the camera in the application Error occurred while trying to access the camera VIDEOIO ERROR: V4L: can't open camera by index 0 (cv2.VideoCapture(0)) and It is showing as select timeout while accessing the camera in the Html browser Code which i have Implemented it cam = cv2.videocapture(0) img_counter = 0 DIR = f"folder/foldertwo/folderthree/{dirName}_{dirID}" try: os.mkdir(DIR) print("Directory ", dirName, " Created ") except FileExistsError: print("Directory ", dirName, " already exists") img_counter = len(os.listdir(DIR)) while True: ret, frame = cam.read() if not ret: break cv2.imshow("Video", frame) k = cv2.waitKey(1) if k%256 == 27: print("Escape hit, closing...") break elif k%256 == 32: img_name = f"folder/foldertwo/folderthree/{dirName}_{dirID}/image_{img_counter}.png" cv2.imwrite(img_name, frame) print("{} written!".format(img_name)) img_counter += 1 cam.release() cv2.destroyAllWindows() -
Django server stops on multiple requests
I am using Django server with ORM for my backend. When I am running multiple requests in parallel the Django server stops at execute_from_command_line(sys.argv) in manage.py. I can't get actual exception. If anybody knows how to solve, help me. -
Login authentication for react application
I am using Django session based auth for my single page app. I am using below APIs for handling the login and logout functionality. I have used the axios for getting the response from these APIs. url.py from django.urls import path from . import views urlpatterns = [ path('csrf/', views.get_csrf, name='api-csrf'), path('login/', views.login_view, name='api-login'), path('logout/', views.logout_view, name='api-logout'), path('session/', views.session_view, name='api-session'), path('whoami/', views.whoami_view, name='api-whoami'), ] Now I want to add the login/auth logic in my react app, i.e. if user has session then user should redirect to main page otherwise it should redirected to login page. How can i implement the authentication logic for the same? views.py from django.http import JsonResponse from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView class SessionView(APIView): authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] @staticmethod def get(request, format=None): return JsonResponse({'isAuthenticated': True}) class WhoAmIView(APIView): authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] @staticmethod def get(request, format=None): return JsonResponse({'username': request.user.username}) -
Filter parent objects which have no children object using refetch_related
I have three models as following, with Seller as the grandparent, Genre as the parent and Book as the chidlren: class Seller(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Genre(models.Model): seller= models.ForeignKey(Seller, related_name="genre", on_delete=models.CASCADE) name = models.CharField(max_length=20) def __str__(self): return self.name class Book(models.Model): genre= models.ForeignKey(Genre, related_name="book", on_delete=models.CASCADE) name = models.CharField(max_length=20) def __str__(self): return self.name If I use prefetch_related() to fetch the Seller objects along with their Genre and Book as following in one single databse query: sellers = Seller.objects.prefetch_related('genre__book').filter() However, I would like to filter out Seller objects that have no Book objects related to. What would be the syntax for the filter() in this case?