Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display additional data
By default the table should only show the first 10 rows of the dataset, by clicking on a button “Load more” additionally 10 rows should be shown - reloading the page is fine. next page = "https://swapi.dev/api/people/?page=2", my code: import requests from rest_framework.views import APIView from rest_framework.viewsets import ModelViewSet from rest_framework import status from rest_framework.response import Response from datetime import datetime from rest_framework import filters from rest_framework.pagination import PageNumberPagination from rest_framework.decorators import action # class StarWarsAPIListPagination(PageNumberPagination): # page_size = 4 # page_size_query_param = 'page_size' # max_page_size = 20 class StarView(APIView): # pagination_class = StarWarsAPIListPagination # filter_backends = (filters.OrderingFilter) # ordering_fields = ('name',) def get(self, request): a = [] page = request.query_params.get('page', 1) url = f'https://swapi.dev/api/people/?page={page}' response = requests.get(url).json() n = response['next'] a.append(n) return Response(response, status=status.HTTP_200_OK) -
How to name Settings model properly in Django?
As we all know the best code style practice to is to name Django models (classes) as singular (Cat, User, Permission, etc.), instead of plural (Cats, Users, Permissions), because it represents the structure of one record of the model. But in case of user settings it become UserSetting. Setting could be interpretted as one key-value pair but we have complete user settings record with multiple key-value pairs. So it's UserSettings. It appearently become confusing. So what should we do in that case? UserSetting UserSettings UserSettingsRecord Other ideas? -
upload a file to a database in Django
I have a button in an HTML file (Upload button): <form method="POST"> {% csrf_token %} <div class="form-group" id="form"> <div class="inputs"> <div style="text-align:center;display:block;"> <input type="submit" id="btnupload" class="button btn btn-primary" value="Upload"> </div> <label for="word1">Word 1</label><br> <input type="text" style="width: 100%;" id="word1" name="word1" placeholder="Enter first word" required><br><br> <label for="word2">Word 2</label><br> <input type="text" style="width: 100%;" id="word2" name="word2" placeholder="Enter second word" required><br><br> <label for="word3">Word 3</label><br> <input type="text" style="width: 100%;" id="word3" name="word3" placeholder="Enter third word" required><br><br> <label for="word4">Word 4</label><br> <input type="text" style="width: 100%;" id="word4" name="word4" placeholder="Enter fourth word" required><br><br> <label for="word5">Word 5</label><br> <input type="text" style="width: 100%;" id="word5" name="word5" placeholder="Enter fifth word" required><br><br> <div style="text-align:center;display:block;"> <input type="submit" id="btnrun" class="button btn btn-primary" name="tp" value="Run"> </div> </div> </div> </form> What I want is that when I click that button upload a CSV file to a DB table that has 5 fields (word1 to word5 and is user attached). I have done something but the button won't work, what am I missing? views.py: def uploadFile(request): if request.user.is_authenticated: if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): usr = User.objects.get(username=request.user) wt = WordsTable() wt.user = usr wt.word1 = form.cleaned_data['word1'] wt.word2 = form.cleaned_data['word2'] wt.word3 = form.cleaned_data['word3'] wt.word4 = form.cleaned_data['word4'] wt.word5 = form.cleaned_data['word5'] wt.save() messages.success(request, "Word added successfully") return redirect("home") context = {'form': … -
What is the command for starting a WSGI server for Django?
I've developed an application in Django that I usually run in development mode: python manage.py runserver I do the same for my deployed instances - obviously a security issue that I now want to resolve. From the Django docs, its not clear to me how to: For simplicity sake, I picked wsgi (over asgi): https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/ . From this page, its not clear to me how my 'runserver' command changes to run the wsgi server over the development server. Should I run the wsgi.py file? That doesn't seem to do anything. From the page above, its not clear whether wsgi is actually a server, or more a platform/type of servers. Do I need to use uwsgi/uvicorn/etc. instead? I'm testing on windows - uvicorn is unix only, so I tried uwsgi, but thats giving me this error message: AttributeError: module 'os' has no attribute 'uname' - I guess its Unix only as well So I'm using the docker image I was already building for deployment - uwsgi is giving me issues again because my docker image has no compiler, so I try now with gunicorn. that should be easy: gunicorn project.wsgi, which gives me: ModuleNotFoundError: No module named 'project/wsgi' my folder structure … -
?! I am working on my graduation project and using deep learning to make image segmentation.When I run server this error raise 👇🏼
File "C:\Users\derar\Desktop\GraduationProject\django_faculty_detector\core\views.py", line 2, in from .ai_model import get_faculity_id_from_image_url File "C:\Users\derar\Desktop\GraduationProject\django_faculty_detector\core\ai_model.py", line 17, in from object_detection.utils import label_map_util File "C:\Users\derar\Desktop\GraduationProject\django_faculty_detector\venv\lib\site-packages\object_detection\utils\label_map_util.py", line 21, in from object_detection.protos import string_int_label_map_pb2 ImportError: cannot import name 'string_int_label_map_pb2' from 'object_detection.protos' (C:\Users\derar\Desktop\GraduationProject\django_faculty_detector\venv\lib\site-packages\object_detection\protos_init_.py) -
Django : Display specific attributes of my ModelMultipleChoiceField Form and get the ID from it
I am Newbee in Django, so I have difficulties to write correctly my form and know how to use it. I have a form that displays a dropdown list depending on the user. So it is why I have queries. Below is my form and my models : models.py class UploadFiles(models.Model): Id = models.IntegerField(db_column='ID') # Field name made lowercase. Filename = models.CharField(db_column='FileName', max_length=255, blank=True, null=True) # Field name made lowercase. PreviousFilename = models.CharField(db_column='FileNameBeforeIndex', max_length=255, blank=True, null=True) # Field name made lowercase. User = models.CharField(db_column='User', max_length=255, blank=True, null=True) # Field name made lowercase. SizeFile = models.IntegerField(db_column='Sizefile') Uploaded_at = models.DateTimeField(db_column='Timestamp', auto_now_add=True) # Field name made lowercase. ID_Customer = models.IntegerField(db_column='ID_Customer', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'tbl_PdfPath' class TblAadJntGroup(models.Model): id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase. id_aadgroup = models.IntegerField(db_column='ID_AADGroup', blank=True, null=True) # Field name made lowercase. id_aaduser = models.IntegerField(db_column='ID_AADUser', blank=True, null=True) # Field name made lowercase. createdon = models.DateTimeField(db_column='CreatedOn', blank=True, null=True) # Field name made lowercase. createdby = models.CharField(db_column='CreatedBy', max_length=255, blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'tbl_AAD_jnt_GroupMember' class TblAadGroups(models.Model): id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase. idcustomer = models.IntegerField(db_column='IDCustomer', blank=True, null=True) # Field … -
count the number of times an order has been approved
I have an application that deals with users making an order but anytime an order is made it needs to be approved before it can be issued or sold out. Is there a way to count the number of times an order has been approved? models class Order(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) pro_name = models.ForeignKey(Product, on_delete=models.CASCADE, null=True,related_name='product') user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) order_quantity = models.PositiveIntegerField(null=True) order_status = models.IntegerField(default=0) timestamp = models.DateTimeField(auto_now_add=False, auto_now=True, null=True) views.py def order_approve(request, order_id): order = Order.objects.get(id=order_id) order.order_status = 1 order.save() return redirect('dashboard-order') I will be grateful for your response. Thank you -
django bulk_create with Null value
models.py class control(models.Model): amount = models.IntegerField() driver = models.ForeignKey(driver, on_delete=models.CASCADE, null=True, blank=True) views.py controlValues = [ (1,1,1), (2,8,None) ] control.objects.bulk_create([ control( id = i[0], amount = i[1], driver = driver(id = i[2]) ) for i in controlValues], ignore_conflicts=True ) I got error: bulk_create() prohibited to prevent data loss due to unsaved related object 'driver'. How can I set Null for driver? I'm using mysql. -
Django - create zip file dynamically and sent it
I'm using python 3.6 and Django 3.2 I managed to create empty zipfile, but after adding files by "writestr" the files is corrupted. How can I add txt files to this zip? here is my view: import zipfile from django.http import HttpResponse def file_generation(request): response = HttpResponse(content_type='application/zip') zip_file = zipfile.ZipFile(response, 'w') zip_file.writestr("filename.txt", "test_inside file") # this line cause error? zip_file.close() zipfile_name = "files.zip" response['Content-Disposition'] = 'attachment; filename={}'.format(zipfile_name) return response -
List past hours of today with django
How do I create a list of past hours of the day? I tried this but it only gets the past 12 hours, and what if the past hour is from yesterday? past_hours = [] for x in range(12): past_hours.append((date - datetime.timedelta(hours=x))) -
django internationalization is not translated to English on the server. Local is normal
python: 3.6 / 3.8 django: 3.2.3 django internationalization is not translated to English on the server. But LanguageCode is correct. Local is normal. # 国际化语言种类 from django.utils.translation import gettext_lazy as _ LANGUAGES = ( ('en-us', _('English')), ('zh-Hans', _('中文简体')), ) DEFAULT_LANGUAGE = 1 # 国际化翻译文件目录 LOCALE_PATHS = (os.path.join(BASE_DIR, 'locale'),) def ocr(request): translateWords = {} translateWords["title"] = _("图片转文字") translateWords["clickButtonWord"] = _("一键转文字") translateWords["txtareaPlaceholder"] = _("输出内容...") translateWords["clickCopy"] = _("点击复制") translateWords["numberOfRrecognizedCharacters"] = _("识别输出文字数:") translateWords["copied"] = _("已复制") translateWords["notes"] = _("注意事项:上传图片最大4兆本应用永久免费使用!") translateWords["aboutUs"] = _("联系我们") print(get_language()) return render(request, 'ocr.html', {"translateWords":translateWords, }) xxx.html {% load i18n %} <h4>OCR {%trans "图片转文字" %}</h4> I tried compiling the mo file on the server's direct command line, but it didn't work. is : python manage.py makemessages -l en_us python manage.py makemessages -l zh_Hans python manage.py compilemessages screenshot -
django.db.utils.InterfaceError: connection already closed
Stack: Ubuntu (20.04 LTS) Nginx Postgresql (v13.3) An AWS load balancer sends traffic to the Ubuntu instance(k8s cluster), which is handled by Nginx, which forwards on to Django (4.0.3) running in gunicorn (19.9.0). Django connects to the database using psycopg2 (2.8.6). The issue I have is that the database connection seems to shut down randomly. Django reports errors like this: `InterfaceError: connection already closed File "django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "contextlib.py", line 79, in inner return func(*args, **kwds) File "django/views/generic/base.py", line 84, in view return self.dispatch(request, *args, **kwargs) File "django/utils/decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) File "django/views/decorators/cache.py", line 62, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "django/views/generic/base.py", line 119, in dispatch return handler(request, *args, **kwargs) File "django/views/generic/detail.py", line 108, in get self.object = self.get_object() File "django/views/generic/detail.py", line 53, in get_object obj = queryset.get() File "django/db/models/query.py", line 492, in get num = len(clone) File "django/db/models/query.py", line 302, in __len__ self._fetch_all() File "django/db/models/query.py", line 1507, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "django/db/models/query.py", line 57, in __iter__ results = compiler.execute_sql( File "django/db/models/sql/compiler.py", line 1359, in execute_sql cursor = self.connection.cursor() File "django/utils/asyncio.py", line 26, in inner … -
Uploading files to Django + Nginx doesn't save it in the media volume in Docker
Basically whenever I try to upload a file using my website, the file doesn't get saved on the media volume. I don't think its a code issue as it works perfectly fine without the container even when paired with nginx. I followed this tutorial to setup my docker containers. Here is my Dockerfile: # pull official base image FROM python:3.9.6-alpine # set work directory WORKDIR /home/azureuser/ecommerce3 # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # fixing alpine related pip errors RUN apk update && apk add gcc libc-dev make git libffi-dev openssl-dev python3-dev libxml2-dev libxslt-dev RUN apk add jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # copy entrypoint.sh COPY ./entrypoint.sh . RUN sed -i 's/\r$//g' ./entrypoint.sh RUN chmod +x ./entrypoint.sh # copy project COPY . . # running entrypoint.sh ENTRYPOINT ["./entrypoint.sh"] docker-compose.yml: version: '3.8' services: web: build: context: ./ dockerfile: Dockerfile command: sh -c "cd DVM-Recruitment-Task/ && gunicorn DVM_task3.wsgi:application --bind 0.0.0.0:8000" volumes: - static_volume:/home/azureuser/ecommerce3/staticfiles:Z - media_volume:/home/azureuser/ecommerce3/mediafiles:Z - log_volume:/home/azureuser/ecommerce3/logs expose: - 8000 depends_on: - db db: image: … -
Make changes to several Django application that have the same root structure
I’m developing a qr menu application that I want to install on several clients. The idea is to have an application per client. These applications will be under the same Django project and will have the same structure, views, models, urls, etc (essentially a copy of the application I’m currently developing but with small changes). My questions are: How can I set up these client applications to inherit / be a copy of the original app? If in the future I make a change to the original app (for example add a new view to visualize a new page on the menu) I would like this addition to be reflected across all the client apps that have already been deployed. Is there a way in which I can do this? I really appreciate the help, thanks! -
PdfFileReader.getFields() returns {} | django
I'm trying to read a pdf form with django. The point is that in another view of my views.py I've succeed into do it by using PyPDF2 and its PdfFileReader.getFields() method. Now the problem is that the reading is not working properly: I've checked with adobe acrobat and the file still is a form with actually fields, so I don't really have any idea of what could be the problem. I'm attaching here the relevant portion of the code: if request.method == "POST": form = Form(request.POST, request.FILES) # the form refer to a model called 'New Request' if form.is_valid(): form.save() File = request.FILES['File'].name full_filename = os.path.join(BASE_DIR, 'media/media', File) f = PdfFileReader(full_filename) fields = f.getFields() fdfinfo = dict((k, v.get('/V', '')) for k, v in fields.items()) k = creare_from_pdf2(request, fdfinfo, pk) # this is a custom function nr = NewRequest.objects.all() #I'm deleting the object uploaded because it won't be useful anymore nr.delete() os.remove(full_filename) If I display print(fdfinfo) it actually shows {}. This of course is leading to error when fdfinfo passes into the 'create_from_pdf_2' function. I don't really know what the problem could be, also because in another view I made exactly the same and it works: if request.method=='POST': form = Form(request.POST, … -
How to sort and count values when they are selected?
I send a request to the site https://swapi.dev/ the received data needs to be sorted: Provide the functionality to count the occurrences of values (combination of values) for columns. For example when selecting the columns date and homeworld the table should show the counts as follows: my code is not very good because I write something like this for the first time: import requests from rest_framework.views import APIView from rest_framework.viewsets import ModelViewSet from rest_framework import status from rest_framework.response import Response from datetime import datetime from rest_framework import filters from rest_framework.pagination import PageNumberPagination from rest_framework.decorators import action # class StarWarsAPIListPagination(PageNumberPagination): # page_size = 4 # page_size_query_param = 'page_size' # max_page_size = 20 class StarView(APIView): # pagination_class = StarWarsAPIListPagination # filter_backends = (filters.OrderingFilter) # ordering_fields = ('name',) def get(self, request): date = datetime.today() page = request.query_params.get('page', 1) url = f'https://swapi.dev/api/people/?page={page}' response = requests.get(url, date).json() return Response(response, status=status.HTTP_200_OK) class StartDateView(APIView): def get(self, request): date = datetime.today() page = request.query_params.get('page', 1) url = f'https://swapi.dev/api/people/?page={page}' response = requests.get(url).json() a = response['results'][0]['name'] # a = response['results'] # for i in range(len(a)): # if a[i]["name"] == "R2-D2": # return Response(a[i]['name'], status=status.HTTP_200_OK) -
why does the csrf token get added to the database in django?
html <form action='order' method='post'> <label for="order">Choose storage size:</label> <!--{% csrf_token %}--> <select name="size" id="size" form="order" required> <option value=4>-</option> <option value=1>Small</option> <option value=2>Medium</option> <option value=3>Large</option> </select> </form> views.py def order(request): price = 0 if request.method == 'POST': size = request.POST;{'size'} duration = request.POST;{'duration'} username = request.POST;{'username'} if size=='1': print('aa') else: storage = Storage.objects.create(size=size, duration=duration, price=price, username=username) storage.save() print('order created') return redirect('/') else: return render(request, 'order.html') class Storage(models.Model): size=models.CharField(max_length=100) duration=models.CharField(max_length=100) price=models.CharField(max_length=100) username=models.CharField(max_length=100) location=models.CharField(max_length=2) whenever i submit the form, the csrf token gets added to all the fields in my database the valeu that gets added is "<QueryDict: {'csrfmiddlewaretoken': ['(series of numbers and letters)']}>" -
Can I get the values from the "GET" parameters as array?
I can get data from url like this. http://127.0.0.1:8000/page/?key=003 I show output as Json. This is view.py def page(request): key = request.GET['key'] data=Device.objects.get(key=key) print(key) data = { "open": data.open, "close": data.close, } return JsonResponse(data, safe=False) I try to get many value in same time like this http://127.0.0.1:8000/page/?key=003&key=004 In terminal it show output like this. [22/Mar/2022 15:19:22] "GET /page/?key=003&key004 HTTP/1.1" 200 64 003 The output show 003 only. Can I get the values from the "GET" parameters as array? -
Joining more than 2 tables for reports in django and extract all the fields from the joined table
I am joining the ClientDetails, AssignmentTable and CallDetails table to get a view as to which telecaller a particular client has been assigned to and get the latest call details as well. However I am unable to accomplish that using django ORM. ISSUE: I am trying to access the fields inside the assignment table and call table but I am getting only the ids and not the other fields. Question: How do I extract all the columns from the assignment and call details table which has the client id as 1? This is the SQL Query that I am trying to come up with: SELECT t1.uid, t1.phone_number, t1.client_name, t1.base, t1.location, t2.assigner, t2.bpo_agent, t2.cro_agent, t3.bpo_status_id, t3.cro_status_id, t3.agent_id_id FROM public.bpo_app_clientdetails t1 LEFT JOIN public.bpo_app_assignmentdetails t2 ON t1.uid = t2.client_id_id LEFT JOIN public.bpo_app_calldetails t3 ON t1.uid = t3.client_id_id; Below is the model file: class ClientDetails(models.Model): uid = models.AutoField(primary_key=True) phone_number = PhoneNumberField(unique=True) client_name = models.CharField(max_length=50, blank=True, null=True) base = models.CharField(max_length=50, blank=True, null=True) location = models.CharField(max_length=50, blank=True, null=True) class Meta: verbose_name_plural = "Client Contact Detail Table" def __str__(self): return f"{self.phone_number}, {self.client_name}" class AssignmentDetails(models.Model): uid = models.AutoField(primary_key=True) client_id = models.ForeignKey( ClientDetails, on_delete=models.PROTECT, related_name='assignment_details' ) date_and_time = models.DateTimeField(auto_now_add=True, blank=True) assigner = models.ForeignKey( User,on_delete=models.PROTECT, related_name='AssignerAgent', db_column='assigner', ) bpo_agent … -
Djnago model instance only update after calling objects.get() again (DRF Test case)
I have an APIView (DRF), where I set the user is_active field to False instead of deleting him, everything works as expected, but I have a wired behavior when I try to make a test case for the view, I try to test if the field 'is_active' is False after calling the ApiView but it remains 'True' if change the code a little bit and call user.objects.get() with the same user email after calling the ApiView, the new instance field is_active is False. I've never encountered this behavior, can someone explain the reason behind it? thanks! this test passes: def test_delete_account(self): self.authentication() # create user and log him in user = User.objects.get(email=self.sample_user['email']) self.assertEqual(user.is_active, True) response = self.client.post(reverse('delete-account')) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) user = User.objects.get(email=self.sample_user['email']) self.assertEqual(user.is_active,False) this test fails: def test_delete_account(self): self.authentication() # create user and log him in user = User.objects.get(email=self.sample_user['email']) self.assertEqual(user.is_active, True) response = self.client.post(reverse('delete-account')) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) self.assertEqual(user.is_active,False) # FAILS HERE delete account ApiView: class DeleteAccountAPIView(GenericAPIView): permission_classes = (permissions.IsAuthenticated,) def post(self, request): user = self.request.user user.is_active = False user.save() return Response(status=status.HTTP_204_NO_CONTENT) -
Failed Python and Django Request
This code refused to work after many attempts and I really need help to get this rectified. check my code below def recharge (request): form = RechargeForm (request.POST or None) if request.method == "POST": url = "https://www.example.com/api/topup/" form = RechargeForm (request.POST or None ) if form.is_valid(): mobile_number = form.cleaned_data['mobile_number'] Ported_number = form.cleaned_data['ported_number'] network_id = form.cleaned_data['idnetwork'] plan_id = form.cleaned_data['idplan'] payload = { "network": network_id.network_id, "mobile_number": mobile_number, "plan":plan_id.plan_id, "Ported_number":True } headers = {'Authorization': 'Token eyeghegge7373c891fe9e7bbe3f9a0a8742d','Content- Type': 'application/json'} response = requests.request("POST", url, headers=headers, data=json.dumps(payload)) info = response.json() info['mobile_number'] = mobile_number info['network_id'] = network_id info['plan'] = plan_id info['Ported_number'] = True i got the below error JSONDecodeError at /file/recharge Expecting value: line 1 column 1 (char 0) I now changes the code to something like this code so i can parse the json but still fails with open("response.json", "r") as write_file: info = json.load(write_file) but didn't work still I did also but still faailes info = json.loads(response) PORTED NUMBER is a boolenfield and i formatted it in this question like this for clarity. can someone help me out ? -
Security Scanning of files other than source code
I have some files that I need to download and then upload to a specific location during execution of code. These files are other than source code files but required by the source code(.yaml, .xml, some .zip folders etc.) I need to scan these files for any security vulnerabilities. Most available approaches look at source code and not at external files. What are some tool(s)/approach(es) that can be used for this? -
How to integrate moment.js into django? [closed]
I know a package by the name of "flask-moment" exists that provides a way to use the moment.js library with flask. Is there anything like that for django? If yes, then how do i use it? -
Advanced Python Scheduler running multiple times in production (Django on DigitalOcean)
I have a simple use of Advanced Python Scheduler to run some django code overnight everyday. The code itself works fine, and locally using manage.py runserver with the --noreload flag everything is spot on. My problem is in production where the APS code is being executed three times; as an example, I receive a status update by email at the end of the process each night, and this email is delivered 3 times within a 10 second period. Where should I be looking to replicate the protections of the --noreload flag in a production set up? -
How to apply different permission classes for different http requests
I have a UserViewSetthat supports get, post, patch, and delete HTTP requests. I have admins with different roles, some of them can delete users, and others cannot. I want to edit my UserViewSet to support this feature. I tried to do something like this: class UserViewSet(ModelViewSet): queryset = User.objects.all() http_method_names = ['get', 'post', 'patch', 'delete'] def get_serializer_class(self): if self.request.method == 'PATCH': self.permission_classes = [CanEdit] return UpdateUserSerializer elif self.request.method == 'DELETE': self.permission_classes = [CanDelete] return UserSerializer I am not sure if this is the best practice to do this.