Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How to navigate between multiple apps
I'm a beginner in Django and don't understand how the templates "dirs" in setup.py works In my project directory, I have 2 apps. I want to reach them via a navigation bar. In the Navigation bar, I have "Home" "Manipulation" "Visualization" I can reach Home and Manipulation page, but when I try to reach the Visualization page, the browser shows me the Manipulation page again. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'manipulation/templates/manipulation'), os.path.join(BASE_DIR, 'visualization/templates/visualization'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Somebody can help me please? Thank you very much In Dirs : [], when I swap the order and put the "Visualization" path before the "Manipulation" path, I get the Visualization page instead of the Manipulation page -
GraphQL file uploads and cURL: json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 188 (char 187)
I have a graphql-server that is running at localhost:3001 I want to send files to a python flask server together with some variables in a cURL request. Here is what i'm sending curl http://localhost:3001/graphql/ -F operations='{ "query": "mutation ConvertDocToPDF($input: ConvertWordDocToPDFInputType!){ convertDocToPDF(input: $input){ success } } ", "variables": { "input" : { "file": null, "saveName": "hello" } ] } }' -F map='{ "0": ["variables.input.file"] }' -F 0=@README.md Surprisingly I'm getting an error which says: json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 188 (char 187) [11/Jan/2023 09:38:31] "POST /graphql/ HTTP/1.1" 500 107387 What may be the problem in this request. Any help input will be appreciated -
Django share common permission across django app
I would like to know if there is a better way to implement common permission that is very similar across django app. For example, app1 need permission_x, app2 need permission_x, and app3 need permission_x too. In order to satisfy this i made permissions.py and create permission_x class which inherits from BasePermission on each app. app1/permissions.py from rest_framework.permissions import BasePermission, SAFE_METHODS class ReadOnly(BasePermission): """Object-level permission to only allow read-only operations.""" def has_permission(self, request, view): # Read permissions are allowed to any request, # hence allow GET, HEAD, or OPTIONS requests. return request.method in SAFE_METHODS app2/permissions.py from rest_framework.permissions import BasePermission, SAFE_METHODS class ReadOnly(BasePermission): """Object-level permission to only allow read-only operations.""" def has_permission(self, request, view): # Read permissions are allowed to any request, # hence allow GET, HEAD, or OPTIONS requests. return request.method in SAFE_METHODS app3/permissions.py from rest_framework.permissions import BasePermission, SAFE_METHODS class ReadOnly(BasePermission): """Object-level permission to only allow read-only operations.""" def has_permission(self, request, view): # Read permissions are allowed to any request, # hence allow GET, HEAD, or OPTIONS requests. return request.method in SAFE_METHODS As you can see, neither app1, app2, nor app3 need these basic permissions. They are exactly the same as each other. I implemented it as above, but is there … -
creating logging for django rest framework
I'm creating a logger for my application. It should create a file day wise and if the file size is cross 100MB it will create a new file for that this is my logger_config.py import logging from logging.handlers import TimedRotatingFileHandler logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # Use a TimedRotatingFileHandler to log to a file that rotates every day handler = TimedRotatingFileHandler('loggerFiles', when='D', interval=1, backupCount=30) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) # Logging levels logger.debug("This is a debug message") logger.info("This is an info message") logger.warning("This is a warning message") logger.error("This is an error message") import os filepath = None def check_log_file_size(filepath): """ Check if the log file has exceeded the maximum size """ size = os.path.getsize(filepath) if size > 100000000: # 100000000 bytes = 100MB new_filepath = f'{filepath}_1' os.rename(filepath, new_filepath) that is how I'm using it. class MyView(APIView): def get(self, request): try: # some code that may raise an exception 1/0 except Exception as e: logger.exception("An exception occurred: %s", e) return Response({"error": "An exception occurred"}, status=status.HTTP_400_BAD_REQUEST) but the problem is it is not creating fils as I want. -
Bootstrap not allows to post data from html in django
{% csrf_token %} User name </div> <div class="form-group"> <label class="form-label" for="form2Example2">Password</label> <input type="password" id="form2Example2" class="form-control" name="password" required/> </div> <button type="button" class="btn btn-primary btn-block mb-4">Sign in</button> i try to post data like email id and password in post method , but it sent through get method . I think there may be problem with bootstrap. can u tell me what are the modifications to be done in the bootstrap for post data method. thanks -
Bulk insert on multi-column unique constraint Django
Suppose we have a model from django.db import models class Concept(models.Model): a = models.CharField(max_length=255) b = models.CharField(max_length=255) c = models.CharField(max_length=255) d = models.CharField(max_length=255) class Meta: constraints = [ models.UniqueConstraint( fields=('a', 'b'), name='first_two_constraint'), ] I want to execute bulk_create on this model such that, on a unique constraint violation of 'first_two_constraint', an update would be performed. For sqlite3, the features https://github.com/django/django/blob/main/django/db/backends/sqlite3/features.py#L44 forces that unique_fields be passed to the bulk_create function. However, it's non-obvious to me what that should be. https://github.com/django/django/blob/829f4d1448f7b40238b47592fc17061bf77b0f23/django/db/models/query.py#L701 I tried the constraint's name, however that failed. Tracing, that occurs since this list of unique_fields is specifically the field names, and there wouldn't be a field name for a constraint . https://github.com/django/django/blob/829f4d1448f7b40238b47592fc17061bf77b0f23/django/db/models/query.py#L768 As a result, I'm at a loss of how to approach this issue. Based off of the sqlite3 documentation, https://www.sqlite.org/lang_conflict.html sub-heading 'REPLACE', the functionality should be possible as, even if it's multiple columns, the violation would still be a unique constraint violation "When a UNIQUE or PRIMARY KEY constraint violation occurs..." Does anyone have any insight as to how to deal with multiple column constraints with the bulk_create function or confirmation that the only approach to this is with raw SQL? I don't believe it's to have unique_fields=('a', … -
When I host the code navigation bar is not showing properly, but when I run it in pycharm it works fine. Is anyone know what is the problem?
this is when I run this code at pycharm this is when I host the code -
Django Rest Framework - Why am I getting an error when the function isn't even supposed to do anything
Have this URL: path("products/product/<int:product>/rating/", ProductRating.as_view()), and this view to handle the URL: class ProductRating(APIView): permission_classes = [permissions.IsAuthenticated] serializer_class = ProductRatingSerializer def get(request): breakpoint() In the URL the product in int:product is just the id of the product in question. No matter what I put there whether it be int:pk or int:id I get the same error every time: TypeError: get() got an unexpected keyword argument 'product' I have tried using generic view RetrieveAPIView and just an APIView and i get the same error. Why am I getting an error and not the breakpoint? -
I'm using cv2 in django to open the camera, but there's a problem when refreshing or opening multiple windows
from django.http import HttpResponse from django.shortcuts import render,get_object_or_404,redirect from django.http import StreamingHttpResponse import cv2 import time import threading from queue import Queue import numpy as np import platform from django.views.decorators import gzip class Vis_camera(object): def new(cls) : if not hasattr(cls,'instance'): cls.instance = super(Vis_camera,cls).new(cls) return cls.instance def __init__(self): # self.video = cv2.VideoCapture(0,cv2.CAP_ANY) self.video = cv2.VideoCapture(0) (self.grabbed, self.frame) = self.video.read() self.status = True self.thread = threading.Thread(target=self.update, args=()) self.thread.start() def __del__(self): self.video.release() def get_frame(self): image = self.frame _, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() def update(self): while True: (self.grabbed, self.frame) = self.video.read() def gen(camera): while True: frame = camera.get_frame() yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') @gzip.gzip_page def detect_vis(request): camera = Vis_camera() return StreamingHttpResponse(gen(camera), content_type="multipart/x-mixed-replace;boundary=frame") Every time I turn the page, I run self.video.release() function, but it doesn't seem to work properly. Error : error: (-215:Assertion failed) !image.empty() in function 'cv::imencode' -
I want test an Api endpoint with post request with image file but not seems working
I have uploaded image of my code when I run my test it says object type of bytes is not serializable response = self.client.post(reverse('update_profile_picture/'), data=json.dumps({"user_uuid":str(newdata.user_uuid),'profile_picture':open('../server/api/tests/test.jpg', 'rb').read()}), files={'profile_picture':open('../server/api/tests/test.jpg', 'rb')}, content_type='application/json', **{'HTTP_AUTHORIZATION': f'Bearer {test_access_token}'}, headers={"Content-Type":"multipart/formdata"}) class UpdateProfilePicture(APIView): serializer_class = UpdateProfilePictureSerializer def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) authmeth, auth = request.META["HTTP_AUTHORIZATION"].split(" ", 1) payload = jwt.decode(auth, settings.SECRET_KEY, algorithms=['HS256']) token_user_uuid = payload.get('user_uuid') if serializer.is_valid(): user_obj = User.objects.get(user_uuid=serializer.data['user_uuid']) if str(token_user_uuid) != str(user_obj.user_uuid): return return_response.APIResult(False, "session_id_miss_match", {}, errors["session_id_miss_match"], status.HTTP_400_BAD_REQUEST).to_json() return return_response.APIResult(True, "profile_success", {"user": {"user_uuid":user_obj.user_uuid, "profile_picture":user_obj.profile_picture.url}}, success["profile_success"], status.HTTP_200_OK).to_json() else: error_msg = get_error_message(serializer.errors) return return_response.APIResult(False, "validate_error", {}, errors[error_msg], status.HTTP_400_BAD_REQUEST).to_json() class UpdateProfilePictureSerializer(serializers.ModelSerializer): user_uuid = serializers.UUIDField(label=("uuid"), required=True, error_messages={ "invalid": "uuid_require", "required": "uuid_require", "blank": "blank_uuid"}) profile_picture = serializers.ImageField( label=("Profile Picture"), required=True, error_messages={ "invalid": "invalid_profile", "required": "profile_required", "blank": "blank_profile"}) -
Can't create migrations with Django
I'm trying to create migrations for my pet project. However, I'm experiencing an Error that can't google an answer for: it says: `vincent@master-PC:/media/vincent/82944C77944C6FA9/Users/Ghost/Desktop/Python/PB/lesson 40/meeting_planner$ python3 manage.py makemigrations Traceback (most recent call last): File "/media/vincent/82944C77944C6FA9/Users/Ghost/Desktop/Python/PB/lesson 40/meeting_planner/manage.py", line 22, in <module> main() File "/media/vincent/82944C77944C6FA9/Users/Ghost/Desktop/Python/PB/lesson 40/meeting_planner/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/vincent/.local/share/virtualenvs/lesson_40-49hQCJIK/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/vincent/.local/share/virtualenvs/lesson_40-49hQCJIK/lib/python3.10/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/home/vincent/.local/share/virtualenvs/lesson_40-49hQCJIK/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/vincent/.local/share/virtualenvs/lesson_40-49hQCJIK/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/vincent/.local/share/virtualenvs/lesson_40-49hQCJIK/lib/python3.10/site-packages/django/apps/config.py", line 193, in create import_module(entry) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django.contrib.cont enttypes' P.S. I'm using SQLite database I DID define my app in the settings correctly (checked it twice), tried to restart my VScode and restart pipenv too. However, it didn't work. -
if in nested loop statement not working in django pythong
{% for data in empattern %} {% for data1 in payout_db %} {% if data.company==data1.company and data.name==data1.name %} <tr> <td>{% widthratio data1.basic_rate 1 data.Add_on_Premium %} </td> </tr> {% endif %} {% endfor %} {% endfor %} here I tried nested loop and I need a if statement also but both loop working fine when I put if its not working , didnot show any error but also not giving anything -
how to use update_or_create in django createview
I want to update_or_create object by django CreateView. my class problem is update object but create duplicate of updated object class CardexCreateView(LoginRequiredMixin, CreateView): model = Cardex fields = '__all__' template_name = 'cardex_add.html' def get_success_url(self): return reverse('cardexes-list') def form_valid(self, form): product = Stock.objects.get(pk=1) self.object, _ = Cardex.objects.update_or_create( product=product, defaults={'standard_weight': 10} ) return super(CardexCreateView, self).form_valid(form) -
how to access the Django view with the @login_required decorator?
I am puzzled as to how to access the view associated with login_required decorator. I am trying to use the requests library. Here is the relevant code: view: @login_required def user_list(request): users = User.objects.filter(is_active=True) serializer = ContactSerializer(users) return Response(serializer.data) urls: path('', views.dashboard, name='dashboard'), path('', include('django.contrib.auth.urls')) path('users/', views.user_list, name='user_list') settings: LOGIN_REDIRECT_URL = 'dashboard' LOGIN_URL = 'login' LOGOUT_URL = 'logout' For example, I am trying to access the view like this right now and I can't do it: import requests response = requests.get(url, auth = HTTPBasicAuth('user', 'pass')) where user and pass are the username and password respectively. And where url is: 'http://127.0.0.1:8000/api/users/' I get the following error: django.urls.exceptions.NoReverseMatch: Reverse for 'login' not found. 'login' is not a valid view function or pattern name. [11/Jan/2023 04:24:11] "GET /api/users/ HTTP/1.1" 500 71617 -
Django rest framework: All fields for a model not visible in the browseable interface
I am trying to learn django rest framework by making a simple CRUD expense tracker app. I want to add expenses from the DRF browse-able interface. All the fields required for adding the expense are not visible in the browse-able interface, which then is not allowing me to add new expense objects. My serializers file: from rest_framework import serializers from .models import Expense, Category class ExpenseSerializer(serializers.ModelSerializer): created_by = serializers.ReadOnlyField(source='created_by.username') category = serializers.ReadOnlyField(source='category.name') class Meta: model = Expense fields = ['created_by', 'amount', 'category', 'created_at', 'updated_at'] class CategorySerializer(serializers.ModelSerializer): created_by = serializers.ReadOnlyField(source='created_by.username') class Meta: model = Category fields = ['created_by', 'name', 'description', 'created_at', 'updated_at'] My models: from django.db import models # Create your models here. class Category(models.Model): created_by = models.ForeignKey('auth.User', related_name='category', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) name = models.CharField(max_length=256, null=False, blank=False) description = models.CharField(max_length=256, null=False, blank=False) # maybe add bill photo option here class Expense(models.Model): created_by = models.ForeignKey('auth.User', related_name='expense', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=False, blank=False) amount = models.DecimalField(decimal_places=2, null=False, blank=False, default=0.00, max_digits=10) And my views: from django.shortcuts import render from expenses.models import Category, Expense from expenses.serializers import CategorySerializer, ExpenseSerializer from rest_framework import generics from rest_framework import permissions from .permissions import IsOwnerOrReadOnly # Create your … -
Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request. while making requests in ghcs
I am using React for my Frontend and Django for my Backend. I am developing it in Github code space. I am getting this error when ever I try to make request. Access to XMLHttpRequest at 'backend url' from origin 'frontend url' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request. --------------------------------------------------------------------------------------------- AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …} code : "ERR_NETWORK" config : {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …} message : "Network Error" name : "AxiosError" request : XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: true, upload: XMLHttpRequestUpload, …} stack : "AxiosError: Network Error\n at XMLHttpRequest.handleError ( frontend url /node_modules/.vite/deps/axios.js?v=0ba92fbe:1361:14)" [[Prototype]] : Error ----------------------------------------------------------------------------------------------- xhr.js:247 POST backend url /api/token/refresh/ net::ERR_FAILED This is my Frontend url https://goameer030-organic-potato-pw66w6q7r7qcxpj-5173.preview.app.github.dev/ This is my Backend url https://goameer030-organic-potato-pw66w6q7r7qcxpj-8000.preview.app.github.dev/ Backend Settings: # Settings.py # Cors Origin Settings CORS_ALLOWED_ORIGINS = ['frontend url'] CORS_ALLOW_CREDENTIALS = True # CORS_ALLOW_ALL_ORIGINS = True Frontend Settings: # axios.py import axios from "axios"; const BASE_URL = "backend /api/"; export default axios.create({ baseURL: BASE_URL, withCredentials: true, }); export const axiosPrivate = axios.create({ baseURL: BASE_URL, headers: { "Content-Type": "application/json" … -
How to set task_id in forhand to query the task state later on?
I have a celery task which looks like this: @app.task(name="Run Command", queue='high_priority_tasks', bind=True) def exec_task_command(command_string): """ Simple run interface for Celery to run a command """ # get the celery task by id log('DEBUG', f'[Command] {command_string}') task_command = subprocess.Popen(command_string, shell=True, stdout=subprocess.PIPE) task_command.wait() current_task.update_state(state='SUCCESS', meta={'status': 'Task Completed'}) return "Command has been completed." Now I want to call this task within another task and display some details about it, especially I want to know if the state of the task has changed: render_tasks = [] for command in encode_commands: task_id = uuid() exec_task_command.apply_async( args=(command,), task_id=f"{task_id}" ) render_tasks.append(task_id) # wait for all tasks to finish while True: time.sleep(60) for task_id in render_tasks: task = AsyncResult(task_id) print("Waiting for render Task: " + str(task_id) + ", Current state is: " + str(task.state)) # check for every task in a for loop if it is finished. if all tasks have finished, break the loop for task_id in render_tasks: task = AsyncResult(task_id) if task.state == "SUCCESS": print("Task: " + str(task_id) + " has finished") # if all tasks in the list have reached the state "SUCCESS", break the loop if all([AsyncResult(task_id).state == "SUCCESS" for task_id in render_tasks]): break actually I would expect that my command can get … -
Boto3: faster S3 Bucket Tag matching possible?
Target: Get all S3 buckets tagged with owner=dotslashshawn Firstly, I'd like to say any help will be greatly appreciated. I have working code allowing me to do this but there doesn't seem to be a way, unlike with EC2 and RDS resources, that will allow me to pull only buckets where that tag exists. I have to pull all buckets and then loop through each to get their tags, then make the comparison unless I've missed something. It takes 12 seconds to do this operation and I'm thinking, there must be a faster way. I'm keeping in mind that it'll only get slower the more buckets that are found. Question: Is this something I could speed up using parallel processing? I have cross account permissions set up because I'm looking in 5 separate accounts for matches. Example Code: accounts = [ '123', # Account 1 '456', # Account 2 '789', # Account 3 '987', # Account 4 '654', # Account 5 ] s3_data = [] owner = 'dotslashshawn' # Loop through roles for account in accounts: # Assume each role assumed_role = sts.assume_role( RoleArn= f'arn:aws:iam::{account}:role/custom-role', RoleSessionName="DotSlashShawnSession" ) # Assign credentials assumed_role_credentials = assumed_role['Credentials'] client = boto3.client('s3', aws_access_key_id=assumed_role_credentials['AccessKeyId'], aws_secret_access_key=assumed_role_credentials['SecretAccessKey'], aws_session_token=assumed_role_credentials['SessionToken'], region_name … -
django make query related name through anther related name
i have models class Payee(models.Model): name = models.CharField(unique=True,max_length=30,default='',verbose_name="اسم المستفيد") class expenses(models.Model): # المصروفات name = models.CharField(unique=True,max_length=40,default='',verbose_name="اسم البند") default_value = models.IntegerField(help_text="القيمة الأفتراضية ",blank=True,null=True,verbose_name="القيمة المفروضة") # سعر متوقع للبند payee_name = models.ForeignKey ( Payee, to_field='id', on_delete=models.CASCADE , blank=True, null=True, verbose_name="المستفيد", related_name='expenses_payee_name' ) expenses_type = models.ForeignKey ( expenses_types, to_field='id', on_delete=models.CASCADE , blank=True, null=True, verbose_name="نوع المعاملة", related_name='expenses_expenses_type' ) description = models.TextField (blank=True, null=True, max_length=300, default='', verbose_name="ملاحظات") active= models.BooleanField(default=True,) class monthly(models.Model): # الشهور month_date = models.DateField( help_text="إضافة شهر جديد", unique=True, verbose_name="شهر/ سنة") month_salary = models.IntegerField( blank=True, null=True, verbose_name="راتب الشهر ") description = models.TextField( blank=True, null=True, max_length=400, default='', verbose_name="ملاحظات") expenses = models.ManyToManyField(expenses ,related_name='monthly_expenses') # changeable_expenses = models.ManyToManyField(changeable_expenses) remaining_value = models.IntegerField( default="0", blank=True, null=True, verbose_name="المتبقي يتم حسابه تلقائي ") active= models.BooleanField(default=True,) class month_expenses(models.Model): month = models.ForeignKey ( monthly, to_field='id', on_delete=models.CASCADE , blank=True, null=True, verbose_name="الشهر", related_name='month_real_value' ) exp_name = models.ForeignKey ( expenses, to_field='id' , on_delete=models.CASCADE , blank=True, null=True, verbose_name="المعاملة", related_name='exp_real_value' ) real_value = models.IntegerField(default=0 ,blank=True, null=True, verbose_name="القيمة الفعلية ") active= models.BooleanField(default=True,) i wont to do query like this class monthly(models.Model): # الشهور ...... def total_real (self , type , payee_name, active=True) : total_real _value = self.month_real_value.filter(expenses_type__in=type , payee_name__in=payee_name, active=active ).values_list('real_value' , flat=True) return sum (total_real _value) the issue for me ( payee_name , active , expenses_type ) are … -
How to fix `Connection refused Is the server running on host "db" (172.23.0.3) and accepting TCP/IP connections on port 5433?` Docker
I had some error code in my docker. I tried connecting multiple containers. I had Django and PostgreSQL but in different containers. I checked the Logs Django container and had these errors. django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "db" (172.23.0.3) and accepting TCP/IP connections on port 5433?\ I checked the connection using ping in container django to container db and the connection was successful. This config docker-compose.yml version: "3.9" services: db: container_name: database image: postgres ports: - "5433:5432" environment: - POSTGRES_PASSWORD=123456 - POSTGRES_USER=postgres - POSTGRES_DB=db_uploader restart: always networks: - uploaderfile_external-name django: container_name: django build : . command: python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" environment: - DB_NAME=db_uploader - DB_PORT=5433 - DB_USERNAME=dimas - DB_PASSWORD=123456 volumes: - .:/usr/src/app depends_on: - db networks: - uploaderfile_external-name restart: always networks: uploaderfile_external-name: this config Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 WORKDIR /usr/src/app ADD requirement.txt requirement.txt RUN pip install -r requirement.txt CMD ["python", "manage.py", "makemigrations"] CMD ["python", "manage.py", "migrate" COPY . . this config django setting.py is part of the database connection. DATABASES = { 'default': { #'ENGINE': 'django.db.backends.postgresql_psycopg2', #'NAME': os.path.join(BASE_DIR, 'db.sqlite3') 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': env('DB_NAME'), 'USER': env('DB_USERNAME'), 'PASSWORD': env('DB_PASSWORD'), 'HOST': 'db', 'PORT': env('DB_PORT'), } } I thought has … -
djongo JSONField rename causes "Cannot alter field" error
I have a Django application with djongo as a database engine. There's a JSONField in one for the models: my_field = JSONField(default=list) I modified the model and renamed my_field in Database like this my_field = JSONField(default=list, db_column="myField") Now when I create migrations: makemigrations I got an error: ValueError: Cannot alter field my_app.MyModel.my_field into my_app.MyModel.my_field - they do not properly define db_type (are you using a badly-written custom field?) Djongo version: "^1.3.6" Django version: "^4.1.1" How to fix the error? -
django function call class and return template to show result issue
I now have a function in views.py that determines the user input options and uses multi-threaded new a class views.py try: poc_instance = None upload_file = request.FILES['file'] ext = upload_file.name.split('.')[-1] poc = request.POST.get('poc_list') input_payload = request.POST.get('input_payload') if upload_file.size != 0 and poc != "" and input_payload != "": if ext in ['txt']: uuid_str = uuid.uuid4().hex upload_file.name = uuid_str + '.txt' filename = os.path.join('upload/',upload_file.name) saveFile(upload_file,filename) with open(filename,'r') as f: line = f.read().split() if poc == "test": poc_instance = test(line,input_payload) poc_t = Thread(target=run_test,args=(poc_instance,)) poc_t.start() result = poc_instance.get_data() Suppose I have a test class that returns a response after url requests and sends it back to the front-end template, but since the thread is running in the background, I can't use get_data to return the result of the response, what can I do to solve this problem? class test: def __init__(self,ip,payload): self.ip = ip self.payload = payload self.result = [] def entry(self): headers={ "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3", } url = "https://xxxxx.com" res = requests.get(url=url,headers=headers,verify=False,proxies=proxies) def get_data(self): return self.result I tried not to use thread when calling the class, but this causes the current user to use it while other users have to wait, … -
Best way to make Django API call take longer
I have a Django application with an functional view API endpoint that returns a response fairly quickly. I would like to make this request intentionally take longer to return, for the purpose of avoiding DDoS attacks. I know it's possible to use throttling through DRF, but I was wondering what would be the best way to make the actual request take longer. Maybe add in a few expensive hashing functions? -
Merge Django models into a view
I am attempting to merge and pull data from three Django models into a view. Players and Events relate to each other in the Details model (a player can attend many events) using models.ForeignKey. In other platforms I would have written a DB View to join tables and the application would query that view. From what I understand Django does not support data views within Models. Looking for help on how I would approach this in Django. class Players(models.Model): firstName = models.CharField(max_length=255) lastName = models.CharField(max_length=255) highSchool = models.CharField(max_length=255) gradYear = models.IntegerField() slug = models.SlugField(default="", null=False) class Events(models.Model): title = models.CharField(max_length=255) location = models.CharField(max_length=255) date = models.DateField() class Details(models.Model): event = models.ForeignKey(Events, on_delete=models.CASCADE) player = models.ForeignKey(Players, on_delete=models.CASCADE) height = models.IntegerField(default=None, blank=True) weight = models.IntegerField(default=None, blank=True) def playerdetail(request,slug): playerinfo = Details.objects.get(id=1) template = loader.get_template('playerdetail.html') context = { 'playerinfo': playerinfo, } return HttpResponse(template.render(context, request)) -
Pytest - Testing Django url with call to external package
HI I need to test my endpoint, it is expecting a json from another call to external library url path("address-lookup/<str:id>", views.address_lookup, name="address_lookup") views def address_lookup(request, id): try: response = get_address_by(id) // an imported method from external library except Exception as e: return JsonResponse({"response": [], 'error': True, 'message': e.message}) return JsonResponse({"response": response}) tests import pytest from django.urls import reverse def test_address_route(client): url = reverse('address_lookup', kwargs={'id': 123}) response = client.get(url) print(f" response {response}") assert response.status_code == 200 assert response contains json // expecting json So obviously it would fail since the external method from library is being called with wrong id AttributeError: 'JSONDecodeError' object has no attribute 'message' // from try catch How to test in this scenario without actually running the imported external method from a library?