Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
django-mathfilters: How to calculate totals with mathfilters
I need to calculate and display a sum total of maintenance and sinking funds listed on a page. My template is as follows: {% extends "base.html" %} {% load mathfilters %} <div class="container"> <div class="col-md-10 offset-md-1 mt-5"> <div class="jumbotron"> <h1 class="display-4">Unit List</h1> <hr class="my-4"> {% block content %} <form class="d-flex" role="search" action="{% url 'billing-list' %}"> <input class="form-control me-2" type="search" placeholder="Search for OWNER, PROPERTY, BLK or UNIT NUMBER" aria-label="Search" name="search"> <button class="btn btn-outline-success" type="submit">Search</button> </form> <table class="table table-borderless"> <thead class="border-bottom font-weight-bold"> <tr> <td>Property Name</td> <td>Block</td> <td>Floor Number</td> <td>Unit Number</td> <td>Owner</td> <td>Share Value</td> <td>Ownership Start Date</td> <td>Monthly Maintenance Fee Payable</td> <td>Monthly Sinking Fund Payable</td> <td> <a href="{% url 'pdf-list' %}" class="btn btn-outline-success"> <i class="fa-thin fa-file-pdf"></i> PDF </a> <a href="{% url 'email' %}" class="btn text-secondary px-0"> <i class="fa-solid fa-envelope"></i> Email </a> </td> </tr> </thead> <tbody> {% for unit in unit_list %} <tr> <td>{{unit.property}}</td> <td>{{unit.block}}</td> <td>{{unit.floor}}</td> <td>{{unit.unit_number}}</td> <td>{{unit.owner}}</td> <td>{{unit.share_value}}</td> <td>{{unit.ownership_start_date}}</td> {% with unit.maintenance_fee_monthly as maint %} {% with unit.share_value as share %} <td>{{maint|mul:share|div:100}}</td> {% endwith %} {% endwith %} {% with unit.sinking_fund_monthly as sink %} {% with unit.share_value as share %} <td>{{sink|mul:share|div:100}}</td> {% endwith %} {% endwith %} </tr> {% endfor %} </tbody> </table> {% endblock content %} </div> </div> </div> Line items were … -
Use Django ORM in locust
I'm using locust to load test my Django application. I'm currently hardcoding certain values in my locustfile.py: GROUP_UUID = "6790f1e6-64f9-4707-aa82-d4edd64c9cc7" @task def get_single_group(self): self.client.get(f"/api/groups/{GROUP_UUID}/") This obviously fails if GROUP_UUID is not in the database, which occurs whenever I reseed my database so I'm constantly having to change these hardcoded values. It would be much better if I could dynamically fetch a group at runtime: from myapp.models import Group @task def get_single_group(self): group = Group.objects.first() self.client.get(f"/api/groups/{group.id}/") However, I'm getting the following error, which makes sense because locust doesn't know anything about Django: ModuleNotFoundError: No module named 'myapp' Is there anyway to use the Django ORM in locustfile.py or do I need to continue hardcoding data all over the place? -
Apache error "Truncated or oversized response headers received from daemon process" when using Django
We have a Django application using mod_wsgi working fine on our Ubuntu 16 instance. When we spun up a new Ubuntu 18 instance, and attempt to log into our application, we get: [Tue Jan 10 22:12:00.930300 2023] [wsgi:error] [pid 11481:tid 140103479047936] [client 10.61.23.144:61958] Truncated or oversized response headers received from daemon process 'server': /home/.../wsgi.py, referer: https://application/login/?next=/application/ [Tue Jan 10 22:12:00.931998 2023] [core:notice] [pid 6523:tid 140103626501056] AH00052: child pid 11479 exit signal Segmentation fault (11) In searching for answers, we've seen several posts suggesting that we add this line to our apache2.conf file, which we did: WSGIApplicationGroup %{GLOBAL} However, this did not address the problem. Also tried the suggestions noted on https://serverfault.com/questions/844761/wsgi-truncated-or-oversized-response-headers-received-from-daemon-process, but this also did not solve the problem. We increased Apache logging to info but aside from the "Truncated or oversized response headers" and "Segmentation fault" no other information was logged. Hoping we may have missed a trick or two. -
Django: ProfileSerializer() takes no arguments
I am trying to get the logged in user profile using django restframework api_view, i have written a simple logic to do that but it keeps showing this error that says TypeError at /api/my-profile/2/ ProfileSerializer() takes no arguments, i cannot really tell what is wrong with the code that i have written. This is the code here class MyProfileView(APIView): # queryset = Profile.objects.all() serializer_class = ProfileSerializer permission_classes = [permissions.IsAuthenticated] def get_object(self, pk): try: return Profile.objects.get(pk=pk) except Profile.DoesNotExist: raise Http404 def get(self, request, pk ,format=None): profile = self.get_object(pk) serializer = ProfileSerializer(profile) return Response(serializer.data) urls.py path("my-profile/<int:pk>/", MyProfileView.as_view(), name="my-profile"), -
Can't import value from .env file / Django
I got a file .env with 4 values to hide sensitive data: DATABASE_PASSWD=Password1 SECRET_KEY=Password2 VAR3=Password3 VAR4=Password4 All of above values are properly imported in Django code except the DATABASE_PASSWORD. When the DATABASES configuration is as follows: # settings.py from decouple import config # ... DB_PASSWORD=config('DATABASE_PASSWD') SECRET_KEY=config('SECRET_KEY') VAR3=config('VAR3') VAR4=config('VAR4') DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': "database_name", 'USER': "database_test_admin", 'PASSWORD': DB_PASSWORD, 'HOST': "localhost", 'PORT': "5432", } } The django outputs: raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option)) decouple.UndefinedValueError: DATABASE_PASSWD not found. Declare it as envvar or define a default value. If I hardcode password that is just the same in .env the problem is gone - the password is correct since it's my private project. Other variables works well with the same config('VAR#') function in views for example. I have no clue what could be wrong here. -
Django Template changes not reflecting
I am trying to make changes in template. everything was going fine from 1 month but now the changes are not reflecting. I have multiple apps in my project and this is just happening for one app only. Please help. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] I am trying to make changes in template. everything was going fine from 1 month but now the changes are not reflecting. I have multiple apps in my project and this is just happening for one app only. Please help. -
Django AWS S3 Storages: SignatureDoesNotMatch
My settings: AWS_ACCESS_KEY_ID = 'xxx' AWS_SECRET_ACCESS_KEY = 'xxx' AWS_STORAGE_BUCKET_NAME = 'xxx' AWS_S3_REGION_NAME = 'eu-west-2' AWS_S3_ADDRESSING_STYLE = "virtual" AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' What I get: <Error> <Code>SignatureDoesNotMatch</Code> <Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message> I've tried changing access keys multiple times to no avail. Why am I getting this error? -
I got ValueError: Related model 'useraccount.user' cannot be resolved in my django app when I tried to migrate AbstractUser?
This error occurred when I try to migrate. └─$ python3 manage.py migrate 130 ⨯ Operations to perform: Apply all migrations: admin, auth, blogapp, contenttypes, forumapp, sessions, token_blacklist, useraccount Running migrations: Applying useraccount.0001_initial...Traceback (most recent call last): File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/manage.py", line 22, in <module> main() File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 349, in handle post_migrate_state = executor.migrate( File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 135, in migrate state = self._migrate_all_forwards( File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 167, in _migrate_all_forwards state = self.apply_migration( File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 252, in apply_migration state = migration.apply(state, schema_editor) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/migrations/migration.py", line 130, in apply operation.database_forwards( File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/migrations/operations/models.py", line 96, in database_forwards schema_editor.create_model(model) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/backends/base/schema.py", line 442, in create_model sql, params = self.table_sql(model) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/backends/base/schema.py", line 216, in table_sql definition, extra_params = self.column_sql(model, field) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/backends/base/schema.py", line 346, in column_sql field_db_params = field.db_parameters(connection=self.connection) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/models/fields/related.py", line 1183, in db_parameters target_db_parameters = self.target_field.db_parameters(connection) File … -
Django M2M Form
i try to do checkboxes in form for M2M field, but have this error, have no idea how to fix it. Google didn't help me, i tried. When i render objects as list, i can select few objects and save it, so problem is not in views.py ,but it doesn't work with checkboxes. error: “on” is not a valid value My code: forms.py class CheckoutForm(forms.ModelForm): class Meta: model = Checkout fields = ('dishes', 'user') def __init__(self, *args, **kwargs): super(CheckoutForm, self).__init__(*args, **kwargs) self.fields["dishes"].widget = CheckboxSelectMultiple() self.fields["dishes"].queryset = Dish.objects.all() -
Serialize Multiple Lists Django
I am very new to Django and I am unable to understand via documentation and online research the following problem on how to Serialize the data to the database. I have a complex JSON (trimmed) [ { "CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents": [ { "decimals": "-6", "unitRef": "usd", "period": { "instant": "2021-09-25" }, "value": "35929000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "instant": "2020-09-26" }, "value": "39789000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "instant": "2019-09-28" }, "value": "50224000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "instant": "2022-09-24" }, "value": "24977000000" } ], "NetIncomeLoss": [ { "decimals": "-6", "unitRef": "usd", "period": { "startDate": "2021-09-26", "endDate": "2022-09-24" }, "value": "99803000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "startDate": "2020-09-27", "endDate": "2021-09-25" }, "value": "94680000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "startDate": "2019-09-29", "endDate": "2020-09-26" }, "value": "57411000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "startDate": "2021-09-26", "endDate": "2022-09-24" }, "segment": { "dimension": "us-gaap:StatementEquityComponentsAxis", "value": "us-gaap:RetainedEarningsMember" }, "value": "99803000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "startDate": "2020-09-27", "endDate": "2021-09-25" }, "segment": { "dimension": "us-gaap:StatementEquityComponentsAxis", "value": "us-gaap:RetainedEarningsMember" }, "value": "94680000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "startDate": "2019-09-29", "endDate": "2020-09-26" }, "segment": { "dimension": "us-gaap:StatementEquityComponentsAxis", "value": …