Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
form.label is not showing in django
this is my code and I try to show the label but it is not displaying this is my form file forms.py class ReviewForm(ModelForm): class Meta: model = Review fields = ['value', 'body'] labels = {'value': 'Place your vote', 'body': 'Add a comment with your vote'} def __init__(self, *args, **kwargs): super(ReviewForm, self).__init__(*args, **kwargs) for name, field in self.fields.items(): field.widget.attrs.update({'class': 'input'}) this is my views file and the function for this form views.py def project(request, pk): projectObj = Project.objects.get(id=pk) form = ReviewForm() context = { 'project': projectObj, 'form': form } return render(request, 'projects/single-project.html', context) this is the model for the review section models.py class Review(models.Model): VOTE_TYPE = ( ('up', 'Up Vote'), ('down', 'Down Vote') ) owner = models.ForeignKey(Profile, on_delete = models.CASCADE, null=True) project = models.ForeignKey(Project, on_delete=models.CASCADE) body = models.TextField(null=True, blank=True) value = models.CharField(max_length=200, choices=VOTE_TYPE) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default = uuid.uuid4, unique=True, primary_key=True, editable=False) class Meta: # every user can only have single comment on each project unique_together = [['owner', 'project']] def __str__(self): return self.value and the html file to display the form html file <form class="form" action="{% url 'project' project.owner.id %}" method="POST"> {% csrf_token %} {% for field in form %} <div class="form__field"> <label for="formInput#textarea">{{field.label}}</label> {{field}} </div> {% endfor … -
Python - Django Rest Framework - Count total row from tables in the database with a single call
I just switched to python and Django-rest-framework from java spring-boot, and I have a question below Let's say I have some tables: class table1(CommonModel): class table2(CommonModel): class table3(CommonModel): class table4(CommonModel): .... And I have an API to return total rows in these tables: { "table1": 10, "table2": 10, "table3": 10, "table4": 10, .... } My code so far is to count the total on each table with Model.objects.all().count() or Model.objects.filter(some_filter).count() And the problem here is obvious, if I have 10 tables, I will have to call 10 count query, which I think is not a good way to go because it spams too many queries to the database. I want to limit the number of the query to the database. The best would be to return all rows count for each table in a single query. I have looking for a solution like creating a custom query or so but nothing seems to solve my issue. Edit: I'm using Postgresql database -
django set initial value in form
class UserEditFormView(FormView): template_name = "edit.html" form_class = UserEditForm def get_initial(self): return {'nickname': self.request.user.nickname} class UserEditForm(forms.Form): nickname = forms.CharField(required=False, max_length=120) I tried to set initial value(placeholder) of the form but it's not working. The input field on the page is empty. -
i have created models and my views function to add the attendance of employee. But data data is not saving in database. and no error comes up
class AttendanceForm(forms.ModelForm): class Meta: model = Attendance fields = '__all__' These are he models and please let me know if nay changes are required : Models: class Employee(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) eid = models.IntegerField(primary_key=True) salary = models.IntegerField() gender = models.CharField(max_length=6, choices=GENDER_CHOICES, default=1) contactno = models.CharField(max_length=10) email = models.CharField(max_length=30) country = models.CharField(max_length=30) city = models.CharField(max_length=20) pincode = models.IntegerField() address = models.CharField(max_length=60) def __str__(self): return self.user.first_name + ' ' + self.user.last_name class Attendance(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, default=1) attendancedate = models.DateField() in_time = models.TimeField() out_time = models.TimeField() description = models.TextField() def __str__(self): return str(self.employee) These is the Views . Please let me know if any changes is required @csrf_exempt def addattendance(request): form = AttendanceForm() emp_list = Employee.objects.all() if request.method == 'POST': form = AttendanceForm(request.POST) if form.is_valid(): form.save(commit=True) return redirect('employee/detail_attendance') return render(request, 'employee/addattendance.html', {'form': form, 'emp_list': emp_list}) I tried everything but i dont know why data is not saving into database . also models are created fine and main thing is there is not error coming up. -
DFR Serializers vs. Forms, and handling of ImageField() as optional field, problem not working
My target is how to make ImageField() as optional in case user does not want to submit an image. When I use django Forms, then the ImageField() will work fine where the field will be treated as optional. Whereas, when I use Django "class FleetSerializer(serializers.ModelSerializer):" then the ImageField() will not be treated as optional. Any solution for this huge problem of mine? Thanks a million. Here is the complete code: MODELS, SERIALIZERS, VIEWS where my objective is to have REST API with field 'licRegImage' as optional. This code is aimed towards Flutter/Dart frontend why I prefer to use SERIALIZERS. For over two weeks now I have not been able to find a solution. I suspect it may be related to compatibility issues, or worst bugs. From Requirements.txt: Django==3.2.16 djangorestframework==3.13.1 djongo==1.3.6 pymongo==3.12.1 djangorestframework==3.13.1 Pillow==9.2.0 etc., etc. MODELS: from djongo import models class Fleet(models.Model): usrRegId = models.CharField(max_length=28) fleetId = models.CharField(max_length=13) vinNr = models.CharField(max_length=35) licRegNr = models.CharField(max_length=35) licRegExpire = models.CharField(max_length=10) licRegImage = models.ImageField(null=True, blank=True, upload_to='astfleet/imglicReg/', default = 'sys_global/images/no_image.png') objects = models.DjongoManager() class Meta: db_table = "ast_fleet" def __str__(self): return self.usrRegId SERIALIZERS: class FleetRegistrationSerializer(serializers.ModelSerializer): class Meta: model = Fleet fields =( 'usrRegId', 'fleetId', 'vinNr', 'licRegNr', 'licRegExpire', 'licRegImage', ) extra_kwargs = { 'usrRegId':{'write_only':True}, 'fleetId':{'write_only':True}, 'licRegImage':{'required':False}, … -
Python asyncio link body and response from it in aiohttp asyncio
I have async requests, i send 100 requests and get response from them I send body to get resonse, the problem is i caanot join request body with response, sometime there is no response i collect requests into a list def __gaterTasks(self, session, total_schets): _tasks = [] _updates = [] for schet in total_schets: _payload_objct = PayloadParams.objects.using('analytic_db').get(payload=schet['payload']) _payload_objct.status = True _updates.append(_payload_objct) _tasks.append( session.get(url=self.url, body=schet['payload']) ) PayloadParams.objects.using('analytic_db').bulk_update(_updates, ['status']) return _tasks i need to link body=schet['payload'] with the response with i get from it the function with runs async def get_data(self, total_schets): async with aiohttp.ClientSession(trust_env=True, auth=aiohttp.BasicAuth()) as session: tasks = self.__gaterTasks(session=session, total_schets=total_schets) responses = await asyncio.gather(*tasks) for each in responses: _each = await each.json() -
Django - if condition always return True
I have a condition which call an update function if is_approved= True @api_view(['POST']) @permission_classes([IsStaff]) def update_company_info(request): request_qs = CompanyUpdateRequests.objects.filter(id=request.data["request_id"],is_approved=None) serializer = CompanyUpdateRequestSerializer(request_qs[0], data=request.data, partial=True) approved = request.data['is_approved'] if serializer.is_valid(): if approved: print(request.data['is_approved']) update_info(request_qs[0].company, request_qs[0]) serializer.save() No matter the boolean value the if approved: gets executed. Any suggestions? -
How do I activate a django view as a scheduled task on pythonanywhere?
I am about to deploy my Django app to PythonAnywhere. I have a view (below) that cleans up all guest accounts older than a time period. I can activate this by manually going to the url (/cleanup/), however it would be nice to schedule this automatically. I see PythonAnywhere handles scheduled tasks that ask for a path to a .py file. Is it possible to separate this view into it's own .py file? MAX_GUEST_ACCOUNT_DAYS = 30 def cleanup(request): """ Deletes all guest user accounts and their media if older than MAX_GUEST_ACCOUNT_DAYS """ # Get all guest accounts created before the limit expired_guests = User.objects.filter(guest=True).filter(date_joined__lt=timezone.now()-timedelta(days=MAX_GUEST_ACCOUNT_DAYS)) for guest in expired_guests: guest.delete() print(f"Deleted guest account(s) older than {MAX_GUEST_ACCOUNT_DAYS} days.") return HttpResponse(f"Deleted guest account(s) older than {MAX_GUEST_ACCOUNT_DAYS} days.") -
how to click button second time after 1st time click using JS
here my code: function report(){ setTimeout(function () { var mehran = new URL('http://example.com'); window.open(mehran); /* alert("h") */ }, 5000); } <span><button type="submit" id="reportclick" style="color:white; background-color:coral; border: 1 px sloid black; width:100px; margin: auto;" onclick="report()">Get Report</button></span> I want to open open this link automatically after 5 seconds when i click on button first time. -
python/django database connection issue
Database settings DATABASES = { 'default': { 'ENGINE': os.environ.get('DB_ENGINE', "mysql"), 'NAME': os.environ.get('DB_NAME', "django_db"), 'USER': os.environ.get('DB_USER', "root"), 'PASSWORD': os.environ.get('DB_PASS', "123456798"), 'HOST': os.environ.get('DB_HOST', "localhost"), 'PORT': os.environ.get('DB_PORT'), } } error django.core.exceptions.ImproperlyConfigured: 'mysql' 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' Connecting with mysql to generate migration but facing issue Its my first time and facing following above issue please guide. -
How to implement NGINX file storage and STORJ cloud?
Django media app + Nginx. And Storj cloud as content file cold storage. nginx.conf location /media { root /var/www/html/media;} I need to avoid to download file from storj, if this file already in /media. User requests mysite/file.mp4. Django download it from storj to /media and show to user. User requests mysite/file.mp4 second time. Nginx shows it from /media I have script for storj. session = boto3.session.Session() s3 = session.client(service_name="s3", aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY, endpoint_url=URL) response = s3.download_file(BUCKET_NAME, OBJECT_NAME, FILE_NAME) Do I need to work with Django with this function or make it like system service and check events if Nginx has file in /media? -
VS Code does not see virtual environment variables in .env file when running django
I am trying to set up a postgres connection and use virtual environment variables for the first time. I created a .env file and placed it in my settings folder but my database variable is missing each time I try to use manage.py runserver. Is there a way to get this to run on windows? Moving the .env file next to my virtual environment did not work either. I also tried typing set DATABASE_URL='postgres://username:password@localhost:5432/authors-live' did not work either. Folder Structure: MASTERDJANGOWITHDOCKER -env (virtual environment folder) -authors-src --manage.py --.env --authors_api ---settings ----base.py ----.env (both .env files are exactly the same) settings/base.py import environ env = environ.Env() ROOT_DIR = Path(__file__).resolve().parent.parent.parent # need three to get to manage.py level # points django to where the apps are stored APPS_DIR = ROOT_DIR / 'core_apps' BASE_DIR = Path(__file__).resolve().parent.parent DATABASES = { 'default': env.db('DATABASE_URL') } .env file DATABASE_URL='postgres://username:password@localhost:5432/authors-live' DJANGO_SECRET_KEY="django-insecure" error message ... File "C:\Python39\lib\os.py", line 679, in __getitem__ raise KeyError(key) from None KeyError: 'DATABASE_URL' ... File "C:\Users\...\authors-haven-api\authors-src\env\lib\site-packages\environ\environ.py", line 371, in get_value raise ImproperlyConfigured(error_msg) django.core.exceptions.ImproperlyConfigured: Set the DATABASE_URL environment variable -
Non persisting data in postgres on docker restart
docker-compose.yml ` version: '3.8' services: web: build: ./app command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/usr/src/app/ ports: - 8000:8000 env_file: - ./.env.dev depends_on: - db db: image: postgres volumes: - db_data:/var/lib/postgresql/data/ env_file: - ./.env.dev volumes: db_data: inspecting the volume dockerized-newsapp_db_data { "CreatedAt": "2022-10-27T10:13:21+05:30", "Driver": "local", "Labels": { "com.docker.compose.project": "dockerized-newsapp", "com.docker.compose.version": "2.12.0", "com.docker.compose.volume": "db_data" }, "Mountpoint": "/var/lib/docker/volumes/dockerized-newsapp_db_data/_data", "Name": "dockerized-newsapp_db_data", "Options": null, "Scope": "local", "CreatedTime": 1666845801000, "Containers": { "ca1449a281d4be86ef9044a4613d27fa4c4debf5806bf0c61d76287ef7b7ae5b": { "Name": "dockerized-newsapp-db-1", "Destination": "/var/lib/postgresql/data" } } } ` Every time I'm restarting the container the database is removed. Commands used: docker compose start docker compose stop Any idea, what might be causing this problem? -
Django Browser back button issue after logout not able to login again. It stay on Logout page only
I am trying to integrate Azure AD with Django. When I login with Azure ad at first time it working fine, than I logout and click Browser Back button from Logout page it is stay on logout page but After that when I try to login from logout page I'm not able to login again. Index content doesn’t load, content remains same as logout page. Also I'm using PWA for this. Index content will load. -
Double linked list in Django models
I am trying to create a music player using Django. on the site I should have playlists with music tracks. I need to create two models: composition and playlist. I have already created the Composition class: class Composition(models.Model): title = models.CharField(max_length=500) artist = models.CharField(max_length=500) playlist = models.ForeignKey('PlayList', on_delete=models.SET_NULL, null=True, blank=False) time_length = models.DecimalField(blank=True, max_digits=20, decimal_places=2) audio_file = models.FileField(validators=[validate_is_audio]) cover_image = models.ImageField() Now I need to create a playlist model class PlayList(models.Model, LinkedList):, which should, by assignment, be inherited from my base class linked_list, realizing a doubly linked list. This class has methods like init(self, first_item=None), append_left(self, item), append_right(self, item), remove(self, item), insert(self, previous, item), etc. On the site, I will have to have several playlists with a choice. This is my first time using django, so I don't know how to implement it. I haven't tried creating this model yet because I don't know where to start. -
How to use schemas in Django using MSSQL?
I don't have 50 reputations to comment on this answer. I want to ask question how can I find the path for mssql\introspection.py as I can't the path in my Django environment. By referring to this question, I have the exact issue which is I need to inspectdb all the tables including tables with custom schemas. I assume this answer will fix my issues OR if anyone have any other solution, I appreciate if you can share with me. -
I have some errors in python django
this is my errors I try but isn`t work :) -
Table inside Django model for Order in E-Commerce site
I am developing a Grocery Store Website using Django for the backend. I have a model named "Order" which contains fields Customer name, date, address, mobile no, payment method, status, etc, and most important Order List (This should be in table format and contains multiple fields product name, price, quantity). I have a products table and this product name, price will be from that products table. I want structure as Customer Name: Mobile No. Date: Address: Order list : | Product Name| Price | Quantity | |:----------- |:-----:| --------:| | Product 1 | 10.20 | 2 | | Product 2 | 15.20 | 5 | | Product 3 | 17.20 | 7 | Payment Method: Payment Status: Order Status: Please help me to get the possible solution to this problem. -
For loop in django template returning same id for specific column
I am trying to write an admin panel where videos can be edited, deleted and reviewed using Django. While the loop I have set up runs smoothly, it only accepts the first value as the id value in the video deletion function. I'm pretty sure I closed the for loop in the right place, I guess there's nothing wrong with it. **This is my template page.** {% extends 'dashboard/main.html' %} {% load static %} {% block content %} <div class="col-sm-12"> <div class="card"> <div class="card-header"> <h5>Edit / Show Videos</h5> </div> <div class="card-block"> <form method="get" action="{% url 'videos' %}"> <div id="zero-configuration_filter" class="dataTables_filter"> <label>Search:<input type="search" class="form-control form-control-sm" placeholder="Type video ID or Title" name="q" aria-controls="zero-configuration"></label> </div> <div class="table-responsive"> <table id="responsive-table-model" class="display table dt-responsive nowrap" style="width:100%"> <thead> <tr> <th>Video ID</th> <th>Video Title</th> <th>Video Create Date</th> <th>Video Status</th> <th>Video From</th> <th>Video IMG</th> <th>Video Duration</th> <th>Video Slug</th> <th> Action </th> </tr> </thead> <tbody> {% autoescape off %} {% for video in videos reversed %} <tr> <td class="tabledit-view-mode" style="cursor: pointer;"><span class="tabledit-span"> {{ video.id }}</span></td> <td>{{ video.video_title|truncatechars:25 }}</td> <td>{{ video.video_create_date }}</td> <td>{{ video.video_status }}</td> <td>{{ video.video_from }}</td> <td> <div class="col-lg-8 col-md-6 col-sm-6"> <img src="{{ video.video_img}}" alt="img" class="img-fluid animation-toggle animated" data-animate="jackInTheBox"> </div></td> <td>{{ video.video_duration }}</td> <td>{{ video.video_slug|truncatechars:25 }}</td> <td> <ul … -
Django Rest Framework - React application although using CSRF token, POST, PUT, and DELETE HTTP requests return 403 error
I am using Django rest framework as my API backend and React as my frontend. What I'd like to do is secure my backend so only the frontend can make "unsafe" requests to it such as post, put, delete, etc. My app is related to the blockchain so I use the user's MetaMask wallet as a means of authentication. As such, each user doesn't have a username or password so I am not equipped to use JWT. Instead, my hope was to pass a CSRF token to the frontend to enable the frontend to make those "unsafe" http requests. I set up an endpoint on my backend to return a CSRF token to the frontend when it is requested. That token is passed fine. When I include that token in the "unsafe" request's headers (i.e. "X-CSRFToken"), however, my backend returns 403 forbidden error. The Django documentation indicates that a 403 error could be the result of not passing the correct CSRF token or that permissions are wrong. In response, I set permissions to "AllowAny" as shown in my settings.py file below. Is this an issue with passing the CSRF token incorrectly, or setting up permission incorrectly (or neither)? My understanding … -
What is the correct way to configure asgi application & channels in djnago?
I've just started to learn about channels and asgi in django .... and in few tutorials that i've seen they do this to configure the asgi apllication asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mywebsite.settings') application = ProtocolTypeRouter({ 'http':get_asgi_application(), }) settings.py INSTALLED_APPS = [ 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'chat' ] ASGI_APPLICATION = 'mywebsite.asgi.application' to check when i run my server it was supposed to be running on asgi/channel server like this Starting ASGI/Channels version development server at http://127.0.0.1:8000/ but mine is still running on the default one Starting development server at http://127.0.0.1:8000/ when i use daphne and put inside installed apps instead of channels 'daphne', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'chat' ] it works fine Starting ASGI/Daphne version 4.0.0 development server at http://127.0.0.1:8000/ can someone tell me what is going on here?and how exactly django works with asgi? -
Problem with Detection in real time using - Yolov5 & Django & React
I am trying to get the detection that displays on the video that I am Streaming to the client and display on a table for every moment and in the same second that detection happening, but for now I get only small parts of the data and it’s happening after a few seconds I using Django to stream a video with detection using yolov5 , I get the video in the client side and display it,now my problem is that I create a function in server that get the detection for the object when it's show in the video and I wanna use it ,the video is displaying in the client and i have also a table beside the video that including the need to include the detection. i need that in every time and in the moment that it's heppning I’ll display it in the table,but now it’s not work for me, it’s only send the data and display it for one/two times , I’m sure that have some problem with detection() function and maybe with the detection_percentage function views.py def stream(): cap = cv2.VideoCapture(source) model.iou=0.5 model.conf=0.15 while (cap.isOpened()): ret, frame = cap.read() if not ret: print("Error: failed to … -
Why is Django saying my template doesn't exist even though it does?
I'm a beginner following this Django tutorial (https://www.w3schools.com/django/django_templates.php) and I'm getting the error bellow after making the html template and modifying the views.py file (name erased for privacy): Internal Server Error: /members Traceback (most recent call last): File "C:\Users\\myproject\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\\myproject\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\\myproject\myworld\members\views.py", line 5, in index template = loader.get_template('myfirst.html') File "C:\Users\\myproject\lib\site-packages\django\template\loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: myfirst.html [26/Oct/2022 16:51:01] "GET /members HTTP/1.1" 500 64964 Tried this: from django.http import HttpResponse from django.shortcuts import loader def index(request): template = loader.get_template('myfirst.html') return HttpResponse(template.render()) Expecting this: <!DOCTYPE html> <html> <body><h1>Hello World!</h1> <p>Welcome to my first Django project!</p> </body> </html> -
How to return respons with redirect in Django views?
I made an api request, took the token, put it into cookie, and to make it work I need return reponse, like is in the end: def reg(request): form = CreateUserForm() if "register-btn" in request.POST: form = CreateUserForm(request.POST) if form.is_valid(): new_user = form.save() login(request, new_user) usr = request.POST.get('username') pss = request.POST.get('password1') url = "http://localhost:8000/api/api-token-auth/" data = {'username': usr, 'password': pss } headers = {'Content-type': 'application/json'} response = requests.post(url, json=data, headers=headers) data = json.loads(response.text) token_ = data.get('token') print(token_) respons = HttpResponse("Cookie Set") respons.set_cookie('token', token_) return respons I need instead of return respons, to make redirect, but if I do so, it doesn't work. Somehow I need to make this code from below work. ... respons = HttpResponse("Cookie Set") respons.set_cookie('token', token_) return redirect('account/') How to make return respons in order to set cookie and redirect to url? -
Multiple dropdown filters on HTML table with javascript
I'm trying to have some dropdowns that will help narrow rows on an html table. I'm new to this so I'm struggling to see how the javascript isn't working. I feel like its close and actually if I change the "!= -1" to "== -1" .... it almost looks like its doing the opposite of what I want. but its still showing odd results. If I had to guess, this is something to do with looping through and I may be missing an IF statement or another conditional somewhere. Also, when I attempt to switch back to No values, it doesn't revert back to the original list Any guidance would be appreciated. var $filterableRows = $('#validtargets').find('tr'), $inputs = $('.filter'); console.log($filterableRows); $inputs.on('change', function() { $filterableRows.hide().filter(function() { return $(this).find('td').filter(function() { console.log(this); // console.log($(this).text().toLowerCase()); // console.log($('#' + $(this).data('input')).val().toLowerCase()); var tdText = $(this).text().toLowerCase(), inputValue = $('#' + $(this).data('input')).val().toLowerCase(); return tdText.indexOf(inputValue) != -1; }).length == $(this).find('td').length; }).show(); }); {% extends 'tf_iac/base/base.html' %} {% load static %} {% block site_css %} <link rel="stylesheet" href="{% static 'tf_iac/styles/run_powershell.css' %}"> {% endblock %} {% block header %} {{ display_r_e }}: Remote Powershell Execution {% endblock %} {% block info %} <select id="project" class="filter"> <option value=" ">No value</option> <option value="TV">TV</option> …