Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ckeditor donst apply styles to text in template
I use ckeditor in Django project. Ckeditor work correctly on site but when I give styles to texts in ckeditor it dosnt applied to text in template for exmaple I set blockquotes style for some text but in tempalte there shown as simple text Only base HTML tag styles loads in my temlate what should I do? -
Django: Need to check for QuerySet existence before looping through it
I have observed in several Django projects the following common pattern: queryset = MyModel.objects.filter(...) if queryset: for obj in queryset: do_something() I realize that by checking queryset Django is already populating its cache so we don't hit the DB again when executing the for loop. According to the documentation, the queryset is also evaluated when looping through it. So my question is: Is there any benefit in including the queryset check before the loop? I am also aware of exists(), but let's consider for this particular case I am not going to use it. Thank you in advance for your answers. -
How to pass dictionary from Django view to JavaScript and access dictionary value with keys
I want to pass a dictionary to JavaScript/jQuery from Django view. In JavaScript i want to access my send dictionary values with the keys. Here I provided my view and JS code. View: def student(request): data={ { 'name': "Joe", 'age' :15, }, { 'name': "Jay", 'age' :16, }, { 'name': "Jeff", 'age' :14, }, } return HttpResponse(data) JS: $(document).on("click","#button",function(e){ e.preventDefault(); $.ajax({ method:"POST", url: "{% url 'student' %}", data: { csrfmiddlewaretoken:'{{csrf_token}}', }, success: function(response){ console.log(response[0].name); console.log(response[0].age); }, error: function(){ console.log("error occur"); }, }); }); With this code i didn't accomplish what i wanted to. -
I want to write the json response in my html table but can't update all .Only updates the first row
Here is my html code Here is my Javascript code And when i click any minus the value is updated in only the first row how to fix it? -
Saving with ajax BUT recent saved item is showing only of id=1
I am building a BlogApp and I made a feature of save form without refresh using Ajax. AND I am trying to show recently created item using Ajax with Inline script HTML, AND saving blog is successfully showing, BUT when i click on save button then blog link is showing below form BUT recent link is of Blog 1 NOT the one i created, It is showing that blog link every time i save blog. models.py class Blog(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30,default='') description = models.CharField(max_length=30,default='') def get_absolute_url(self): return reverse('blogapp',kwargs={'pk':self.pk}) blog_list.html <form id="blog-form"> {% csrf_token %} {{ form|crispy }} <div class="col text-center"> <input type="submit" value="Create Blog" /> </div> </form> <script> $(document).ready(function () { $("#blog-form").submit(function (e) { e.preventDefault(); var serializedData = $(this).serialize(); $.ajax({ type: 'POST', url: "{% url 'blogapp:create_blog_ajax' %}", data: serializedData, //{% for blog in blogs %} success: function (response) { var instance = JSON.parse(response["instance"]); var fields = instance[0]["fields"]; $("#content_shower tbody").prepend( ` <div class="blogs"> <br> <a href="{{ blog.get_absolute_url }}">${fields["title"] || ""}</a></li> </div>` ) }, //{% endfor %} error: function (response) { alert(response["responseJSON"]["error"]); } }) }) }) </script> <div class="container-fluid"> <table class="table table-striped table-sm" id="content_shower"> <tbody> </tbody> </table> </div> views.py def blog_list(request): groups = Group.objects.all() if request.method == 'POST': … -
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.