Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Djnago signals how to delete old object if new object created?
I am using django signals for showing notifications. If any post created in my blog then it will notify the blog author and pending for admin approval see the picture: if admin approve the blog post then author will get another new notification. I want to delete old pending notification of post1 if new notification created for post1. see the picture: here is my signals code for create notification: class Blog(models.Model): .....my fields #signals code def blog_notify(sender, instance, *args, **kwargs): blog = instance blog_title = blog.title sender = blog.author if sender == blog.author and blog.is_published == "published": notify = Notifications(blog=blog, sender=sender, user=sender,text_preview = blog_title[:250], notification_type="post approved") notify.save() if sender == blog.author and blog.is_published == "pending": notify = Notifications(blog=blog, sender=sender, user=sender,text_preview = blog_title[:250], notification_type="pending post") notify.save() post_save.connect(Blog.blog_notify, sender=Blog) -
Remote rejected main -> main (pre-receive hook declined)
I'm a beginner with heroku and I require some help. I spent the whole morning trying to solve this issue [remote rejected] main -> main (pre-receive hook declined) but still cant. After i edit something everytime, i will type git add -A git commit -m "Update #" git push origin main After this 3 commands, I check my github and it is all updated. So i type git push heroku main But the output of this is always ! [remote rejected] main -> main (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/whispering-wildwood-75050.git' I redo this part like 4 times already following this guide https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Deployment and sometime when I am lucky i managed to get past the [remote rejected] main -> main (pre-receive hook declined) and I type heroku open I get this error DisallowedHost at /. So following the advice by net i add **whispering-wildwood-75050.herokuapp.com' to ALLOWED_HOSTS under settings.py. Then the issue of [remote rejected] main -> main (pre-receive hook declined) comes again after i git add -A git commit -m "Update #" git push origin main git push heroku main Appreciate if anyone can help me on this -
Overwriting Datetime is not working in Postgresql in Django
So what I need to do is to change few rows in a model DateTime field to 40 days in the past, with Django using a PostgreSQL database. Where I choose all products with an even ID and change the date_uploaded value. This is what I am currently doing... from django.core.management.base import BaseCommand from store.models import Product import datetime class Command(BaseCommand): def handle(self, *args, **options): all_products = Product.objects.all() for product in all_products: if product.pk % 2 == 0: product.date_uploaded = product.date_uploaded - datetime.timedelta(40,2,0,0) product.save() print(product.date_uploaded) And for some reason when I try to save the product it works with no errors but the DateTime value is not changed. Is there anything wrong with what I am doing? this is my models.py class Product(models.Model): image1 = models.ImageField(upload_to="product_images", default="https://eblossomsl.s3-us-west-2.amazonaws.com/logo.png") image2 = models.ImageField(upload_to="product_images", blank=True) image3 = models.ImageField(upload_to="product_images", blank=True) image4 = models.ImageField(upload_to="product_images", blank=True) name = models.CharField(max_length=100, unique=True) category = models.CharField(choices=CATEGORY, max_length=20, default="HRT", db_index=True) price = models.PositiveIntegerField() search_query = models.TextField(blank=True, null=True) date_uploaded = models.DateTimeField(auto_now=timezone.now()) quantity_bought = models.PositiveIntegerField(default=0) Any help would be greatly appreciated since I am not sure what I am doing wrong. -
Customizing Django Admin Search
I want to customize my Django Admin Search form. Like this picture, I want to add select box to choose search fields. Is there any built in parameter in Django? or Is there other way to make this possible? enter image description here -
How do you set the default value for Django's 'on_delete=models.SET_DEFAULT'
In the example below, how--and where--do you set the default value? author = models.ForeignKey('Author', on_delete=models.SET_DEFAULT) -
Deploy Django docker image with Jenkins
I would like to deploy the Django Docker image with Jenkins. I already had this pipeline created with the middle docker registry. For this, I have 2 Jenkins tasks Build the image and transfer to registry Pull from registry to desirable server and start image Now, I would like to avoid the docker registry to speed up the deployment. Right now I have something like this, but it DOESN'T work: --- - hosts: "{{ HOSTS|default('docker') }}" remote_user: "{{ USER }}" vars: deploy_port: "{{ DEPLOY_PORT|default(8080) }}" git_branch: "{{ GIT_BRANCH|default('Development') }}" python_settings: "{{ PYTHON_SETTINGS|default('Development') }}" su_user: "{{ SU_USER|default('test') }}" su_email: "{{ SU_EMAIL|default('test@test.si') }}" su_password: "{{ SU_PASSWORD|default('test') }}" app_container_name: "{{ APP_NAME|default('test') }}" tasks: - name: Remove old image docker_image: name: my-project-name-{{ git_branch }} state: absent force: yes - name: build django image docker_image: path: . name: my-project-name-{{ git_branch }} nocache: yes - name: Start django image docker_container: name: "{{ app_container_name }}" image: my-project-name-{{ git_branch }} state: started restart: yes restart_policy: always ports: - "{{ deploy_port }}:80" env: PYTHONUNBUFFERED: 0 DJANGO_ENV_NAME: "{{ python_settings }}" SU_USER: "{{ su_user }}" SU_EMAIL: "{{ su_email }}" SU_PASSWORD: "{{ su_password }}" tty: yes This give me the error in Jenkins raise errors.APIError(e, response, explanation=explanation)\r\ndocker.errors.APIError: 500 Server Error: Internal Server … -
How to align decimal point of price in django template?
I'm trying to display amount of money a user spent in a table. I want the display amount to look neat, but it looks like below https://i.stack.imgur.com/kOpQ3.png I want their dot to be on the black straight line. Thank you in advance. -
How can i make a website that contains a python algorithm
1.The algorithm : So i just did a python algorithm that allows you from an input list of ingredient print out 2 list one contains recipes that you can make with their ingredient the other list print recipes that you can't make and the ingredient that misses to do it.(i wrote all the recipes with their ingredient in the top of the script) 2.The problem : I want to put this into an aesthetic website or an application on web so my friend and everyone can us it and even for me ill be able to run it from my phone for exemple and even for the aesthetic but i don't know how to do it like should i learn django?? or html??please help N.B: sorry if i made some english mistakes also this is my first project in coding so please help me -
Django template variable conditionals don't evaluate properly?
This makes no apparent sense to me. As you can see in the code below, I am pulling customer subscription data from various page context objects in django. As you can see in the attached screenshot, the variables work, and (unless django template variable values are type casted?) the values do in fact match. Based on the if condition, the customer (user object)'s existing subscription should be classed "active" when the page loads, but it isn't? <div class="card-deck"> {% for product in products %} request.user.is_paysubscribed = {{ request.user.is_paysubscribed }}<br /> product.metadata.tier = {{ product.metadata.tier }}<br /> <div class="card mb-4"> {% for price in product.plan_set.all %} <div class="card-body{% if request.user.is_paysubscribed == product.metadata.tier %} active"{% else %}"{% endif %} id="{{ product.name|slugify }}-card" role="button" onclick="planSelect('{{ product.name|slugify }}-card', '{{ product.name }}', '{{ price.human_readable_price }}', '{{ price.id }}')"> <h5 class="card-title text-center"><label for="{{ product.name }}">redacted product name</label></h5> <p class="text-center">{{ price.human_readable_price }}</p> <p class="card-text">{{ product.description }}</p> </div> {% endfor %} </div> {% endfor %} </div>