Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AssertionError at /create-user/ Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view
AssertionError at /create-user/ Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'NoneType'> models.py: `class UserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) points_earned = models.PositiveIntegerField(default=0) downloaded_apps = models.ForeignKey(App, on_delete=models.CASCADE, blank=True, null=True) task = models.ForeignKey(Task, on_delete=models.CASCADE, blank=True, null=True) class Task(models.Model): completed = models.BooleanField(default=False) screenshot = models.ImageField(upload_to='screenshots/', blank=True, null=True) class App(models.Model): app_name = models.CharField(max_length=30) icon = models.ImageField(upload_to='icons/', blank=True, null=True) points = models.PositiveIntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True, blank=True)` Serializers: `class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'password'] class UserProfileSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = UserProfile fields = '__all__'` views.py: @api_view(['POST']) def create_user(request): try: if request.method == 'POST': data = request.data serializer = UserProfileSerializer(data=request.DATA) if serializer.is_valid(): serializer.save() return Response({'message': f"user {data['username']} created"}, status=status.HTTP_201_CREATED) except Exception as e: return Response({'message': f'{e}'}, status=status.HTTP_400_BAD_REQUEST) json data for post request: {"username": "user1", "password": "dummyPass@01"} after I provide this data, it returns me the above mentioned error Why does it happen? I checked other similar questions where I found that return was missing for most of the cases before Response(). -
How to mock DjangoREST framework RawQuery?
I'm developing BBS API with Django REST framework. I tried to mock RawQuery because Django test database doesn't work, but my mock code also doesn't work. models.py from django.db import models # Converts snake_case to camelCase here because clients use camelCase. class Board(models.Model): boardID: models.IntegerField = models.IntegerField(primary_key=True) name: models.CharField = models.CharField(max_length=32) path: models.CharField = models.CharField(max_length=64) @staticmethod def get(lang): q = ''' SELECT board_id AS boardID, name, path FROM bbs.boards WHERE language = %s ORDER BY order_in_lang ''' return Board.objects.raw(q, [lang]) serializers.py from bbs_api.bbs_api import models from rest_framework import serializers class BoardSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.Board fields = '__all__' views.py from bbs_api.bbs_api import models, serializers from rest_framework import viewsets from rest_framework.response import Response class EnBoardsViewSet(viewsets.ModelViewSet): def get(self, request): raw_query_set = models.Board.get('en') boards_serializer = serializers.BoardSerializer(raw_query_set, many=True) return Response(boards_serializer.data) tests.py from django.db.models.query import RawQuerySet from django.http import HttpRequest from django.test import TestCase from bbs_api.bbs_api import models, serializers, views from rest_framework.request import Request from rest_framework.serializers import BaseSerializer, ListSerializer from rest_framework.utils.serializer_helpers import ReturnList from unittest.mock import patch, PropertyMock import traceback class EnBoardsViewSetTest(TestCase): @patch('rest_framework.serializers.BaseSerializer.data') def test_get_returns_en_boards(self, mocked_data): expected = [ {'lang': 'en', 'name': 'News', 'path': '/boards/en/news', 'minutes_to_live': 1440, 'order_in_lang': 1}, {'lang': 'en', 'name': 'Politics', 'path': '/boards/en/politics', 'minutes_to_live': 1440, 'order_in_lang': 2}, ] mocked_data = PropertyMock(return_value=expected) req … -
Error in uploading django project on pythonanaywhere.com
I am uploading django project on pythonanywhere.com but it is showing 2023-09-23 07:19:34,723: Error running WSGI application 2023-09-23 07:19:34,731: ModuleNotFoundError: No module named 'crispy_forms' 2023-09-23 07:19:34,732: File "/var/www/abhishekk_pythonanywhere_com_wsgi.py", line 29, in 2023-09-23 07:19:34,732: application = get_wsgi_application() 2023-09-23 07:19:34,732: 2023-09-23 07:19:34,732: File "/home/Abhishekk/.virtualenvs/blog/lib/python3.9/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2023-09-23 07:19:34,732: django.setup(set_prefix=False) 2023-09-23 07:19:34,732: 2023-09-23 07:19:34,732: File "/home/Abhishekk/.virtualenvs/blog/lib/python3.9/site-packages/django/init.py", line 24, in setup 2023-09-23 07:19:34,732: apps.populate(settings.INSTALLED_APPS) 2023-09-23 07:19:34,733: 2023-09-23 07:19:34,733: File "/home/Abhishekk/.virtualenvs/blog/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate 2023-09-23 07:19:34,733: app_config = AppConfig.create(entry) 2023-09-23 07:19:34,733: 2023-09-23 07:19:34,733: File "/home/Abhishekk/.virtualenvs/blog/lib/python3.9/site-packages/django/apps/config.py", line 193, in create 2023-09-23 07:19:34,733: import_module(entry) this error i have installed crispy_forms and written it in the installed_apps in setting.py and it is running perfectly on the localhost what is the problem? I expected it to run perfectly and also i have Debug = False it -
Challenges Encountered When Implementing Filtering Using Django's Filter Backends in Python Django
I attempted to implement filtering using Django Filter Backends in order to filter my class-based view, but I encountered difficulties. I am unable to retrieve the desired values in my search. this is my Setting.py REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS':['django_filters.rest_framework.DjangoFilterBackend'], 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle' ], 'DEFAULT_THROTTLE_RATES': { 'anon': '3/day', 'user': '5/day', 'jack': '10/day' }, } and this is my views.py:- from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework_simplejwt.authentication import JWTAuthentication from rest_framework.permissions import IsAuthenticatedOrReadOnly from .models import Student from .serlizer import StudentSerlilizer from rest_framework.throttling import AnonRateThrottle,UserRateThrottle from . import thorttle class StudentInfo(APIView): authentication_classes = [JWTAuthentication] # Apply JWTAuthentication permission_classes = [IsAuthenticatedOrReadOnly] # Apply IsAuthenticatedOrReadOnly permission throttle_classes = [AnonRateThrottle,thorttle.JackRateThrottle] filterset_fields = ['city'] def get(self, request, format=None): stu = Student.objects.all() serlizer = StudentSerlilizer(stu,many=True) return Response(serlizer.data) def post(self,request,format=None): request_data = request.data serlizer = StudentSerlilizer(data=request_data) if serlizer.is_valid(): serlizer.save() msg = {'msg':'Your data has been saved'} return Response(msg) msg = {'msg':serlizer.errors} return Response(msg,status.HTTP_400_BAD_REQUEST) and this is my urls:- from django.urls import path from . import views from rest_framework_simplejwt.views import TokenObtainPairView,TokenRefreshView,TokenVerifyView urlpatterns = [ path('gettoken/',TokenObtainPairView.as_view(),name="get_token"), path('refreshtoken/',TokenRefreshView.as_view(),name="refresh_token"), path('verifytoken/',TokenVerifyView.as_view(),name="verify_token"), path('studentinfo/',views.StudentInfo.as_view(),name="studentlist"), path('studentinfo/<int:pk>/',views.StudentRUD.as_view(),name="StudentRUD") ] this is what i tried to get all the querie's with the city="Bhopal":- http://127.0.0.1:8000/studentinfo/?city=Bhopal I am receiving … -
Django Session not properly storing
Please I've been trying to fix this for hours now, I need help please. It keeps creating new cart upon each add. I discovered its not getting the session "guest_cart_id". How do I go about it please. @action(detail=False, methods=['post']) def add_to_cart(self, request): serializer = AddCartItemSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = request.user if user.is_authenticated: # Authenticated user cart, _ = Cart.objects.get_or_create(user=user) else: # Guest user - Check if there's a guest cart in the session guest_cart_id = request.session.get('guest_cart_id') print(guest_cart_id) if guest_cart_id: cart = Cart.objects.get(pk=guest_cart_id) else: cart = Cart.objects.create() request.session['guest_cart_id'] = str(cart.id) request.session.save() guest_cart_id = request.session.get('guest_cart_id') print(guest_cart_id) product_id = serializer.validated_data["product_id"] quantity = serializer.validated_data["quantity"] try: cart_item = CartItem.objects.get(product_id=product_id, cart=cart) cart_item.quantity += quantity cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create(cart=cart, product_id=product_id, quantity=quantity) cart_item_serializer = CartItemSerializer(cart_item) response_data = { "cart_item": cart_item_serializer.data, "cart_id": str(cart.id) # Convert UUID to string } return JsonResponse(response_data, status=status.HTTP_201_CREATED) -
ModuleNotFoundError: No module named 'fcntl' , when I try to make virtual environment in django
I have a windows 10 system. I'm trying to run Django project there. So installed virtual environment. But when try to make virtual environment directory face some issue. I have go through many solution but doesn't work. pip install virtualenvwrapper-win this code run ok mkvirtualenv envname here comes the error as ModuleNotFoundError: No module named 'fcntl' Install packages pip list altgraph 0.17.3 asgiref 3.6.0 auto-py-to-exe 2.36.0 autopep8 1.7.0 Babel 2.12.1 bottle 0.12.25 bottle-websocket 0.2.9 cachetools 5.3.1 certifi 2023.5.7 cffi 1.15.1 charset-normalizer 3.1.0 colour 0.1.5 cycler 0.11.0 distlib 0.3.6 Eel 0.16.0 filelock 3.9.0 fonttools 4.38.0 future 0.18.3 gevent 22.10.2 gevent-websocket 0.10.1 google-api-core 2.11.0 google-api-python-client 2.87.0 google-auth 2.19.0 google-auth-httplib2 0.1.0 google-auth-oauthlib 1.0.0 googleapis-common-protos 1.59.0 greenlet 2.0.2 httplib2 0.22.0 idna 3.4 importlib-metadata 5.2.0 kiwisolver 1.4.4 macholib 1.16.2 matplotlib 3.5.3 modulegraph 0.19.5 mysql-connector-python 8.0.33 numpy 1.21.6 oauthlib 3.2.2 packaging 23.1 pandas 1.3.5 pefile 2023.2.7 Pillow 9.5.0 pip 23.2 platformdirs 2.6.2 playsound 1.3.0 protobuf 3.20.3 py2app 0.28.6 pyasn1 0.5.0 pyasn1-modules 0.3.0 pycodestyle 2.9.1 pycparser 2.21 pygame 2.1.2 pyinstaller 5.11.0 pyinstaller-hooks-contrib 2023.3 PyMySQL 1.0.3 pyparsing 3.0.9 python-dateutil 2.8.2 pytz 2023.3 pywin32 306 pywin32-ctypes 0.2.0 requests 2.31.0 requests-oauthlib 1.3.1 rsa 4.9 setuptools 67.8.0 six 1.16.0 sqlparse 0.4.4 tkcalendar 1.6.1 tkmacosx 1.0.5 toml 0.10.2 typing_extensions 4.4.0 uritemplate 4.1.1 … -
trouble in admin pages showing name in select for foreign key instead of id
I have two models Client and Master. Master has a foreign key to client. I am trying to get the select for the foreign key to display the name in the admin pages but getting an error. Here is the client model class Client(models.Model): id = models.BigAutoField(primary_key=True), name = models.CharField(max_length=200, blank=False, null=True) clientEmail = models.CharField(max_length=200, blank=False, null=True) clientPhone = models.CharField(max_length=200, blank=False, null=True) clientCompany = models.CharField(max_length=200, blank=False, null=True) def __str__(self): and here is an abbreviated Master class Master(models.Model): id = models.BigAutoField(primary_key = True) client = models.ForeignKey(Client, on_delete=models.CASCADE,null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) user_metadata = models.JSONField(max_length=500, null=True, blank=True) user_id = models.CharField(max_length=500, blank=False, null = True) user_name = models.CharField(max_length=500, blank=False, null = True) #abbreviated def __str__(self): return self.user_name def c_name(self): return self.client.name and the admin.py class MasterDataAdmin(admin.ModelAdmin): list_display = ( 'id', 'c_name','user_name', 'account_status') admin.site.register(Master, MasterDataAdmin) Now when I go to the Master in admin pages I get... OperationalError at /admin/kdconnector/master/ no such column: kdconnector_master.client_id Request Method: GET Request URL: http://localhost:8000/admin/kdconnector/master/ Django Version: 4.1.7 Exception Type: OperationalError Exception Value: no such column: kdconnector_master.client_id Exception Location: C:\Users\MikeOliver\KDConnectorSite\venv\Lib\site-packages\django\db\backends\sqlite3\base.py, line 357, in execute Raised during: django.contrib.admin.options.changelist_view Python Executable: C:\Users\MikeOliver\KDConnectorSite\venv\Scripts\python.exe Python Version: 3.11.3 I tried the following example that works. class Author(models.Model): name = models.CharField(max_length=100) def __str__(self): … -
Profile() got unexpected keyword arguments: 'id_user'
I cant seam to figure out why this error occurs when 'user_id' is on the Profile model. Help! The Profile is getting a FK from the Django user form and the id_user is on the Profile model. Im following a code along it works fine for the instructor but not for me. I want to see a profile in the admin portal. Here is my models from django.db import models from django.contrib.auth import get_user_model User = get_user_model() # Create your models here. class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) id_user = models.IntegerField bio = models.TextField(blank=True) profileimg = models.ImageField(upload_to='profile_images', default='book-icon.png') location = models.CharField(max_length=100, blank=True) def __str__(self): return self.user.username here is my views def signup(request): if request.method == 'POST': username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] password2 = request.POST['password2'] if password == password2: if User.objects.filter(email=email).exists(): messages.info(request, 'Email Taken') return redirect('signup') elif User.objects.filter(username=username).exists(): messages.info(request, 'Username Taken') return redirect('signup') else: user = User.objects.create_user(username=username, email=email, password=password) user.save() #log user in and redirect to settings page #create a Profile object for the new user user_model = User.objects.get(username=username) new_profile = Profile.objects.create(user=user_model, id_user=user_model.id) new_profile.save() return redirect('settings') else: messages.info(request, 'Password Not Matching') return redirect('signup') else: return render(request, 'signup.html') Here are my Urls from django.urls import path from . … -
Why is Invoke task reexecuted on code change?
I have defined Invoke task that runs foo function and then starts my Django app. Whenever I change the code, the whole task is reexecuted. I don't understand why reload mechanism triggers the task. I want foo function to be called only on docker-compose up. Can somebody explain? Setup: docker-compose.yml: version: '3' services: backend: entrypoint: ["invoke", "my_task"] volumes: - .:/code tasks.py: from invoke import task import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings") django.setup() @task def my_task(context): foo() management.call_command("runserver", "0.0.0.0:8000") -
Error message "Forbidden you don't have permission to access this resource "
I want to deploy a django app using ubuntu 22.04 as a wsl package on windows laptop and i am using an ec2 instance to host, i've made all configurations and settings but when i try to access the website on chrome using it's public IP i get error "Forbidden, you don't have permission to access this resource. Apache/2.4.52 (Ubuntu) Server at 54.81.101.238 Port 80 I've tried different solutions found online, even the ones found on stackoverflow i've given apache permissions to my app folder, made various changes to my apache2.conf and virtualhost file but i still get the same error my virtualhost conf file: <VirtualHost *:80> #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /home/rotisary/postly #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined #Include conf-available/serve-cgi-bin.conf Alias /static /home/rotisary/postly/static <Directory /home/rotisary/postly/static> Require all granted </Directory> Alias /media /home/rotisary/postly/media <Directory /home/rotisary/postly/media> Require all granted </Directory> <Directory /home/rotisary/postly/postly> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/rotisary/postly/postly/wsgi.py WSGIDaemonProcess django_app python-path=/home/rotisary/postly:/home> WSGIProcessGroup django_app apache has access to all my folders, from the root directory (home) to the directory of my django app -
How to change user password from Cognito Forgot Password using Lambda and triggers?
I'm building an SSO process to integrate an app with Cognito. For that I'm using Django (the app), Mozilla OIDC (for integration with Cognito) and AWS Cognito. I'm able to migrate users from the already existing app to Cognito User Pool. I need to contemplate the situation where a user clicks on "Forgot Password", which should trigger a Lambda, and allows me to update the user's password (hashing it) into the Database by writing the lambda_handler code. Now I don't understand how to achieve this. More specifically, the flow and which trigger to use. So far, when a user clicks on Forgot Password, it sends an email with a confirmation code, which the user has to enter along with the new password and new password confirmation. I need that when the user CONFIRMS that new password, I would capture that event and that new password I would hash it and update the database. All the hashing and updating the database, I know how to do. This is what I'm doing: Push a docker image that contains Django, boto3 and psycopg2 to an AWS ECR. This image gets pulled up when the lambda gets triggered (I think there are generic triggers … -
What is the best way to publish my django application in azure
I have a Django + Celery + AI application, and I want to publish it to Azure App Service using Docker. My question is simple. What are the best practices to do it? I've read a little about it, and in some cases they use Nginx and Gunicorn. Should I do it too? Are both necessary? -
Django SSL Operations Causing Slow API Response - How to Improve Performance?
I am a beginner at Django , I made a read request to an Api endpoint in a django appliation, it takes about 15 seconds to retrieve its content, which is a very long time, I profilled the django application and got this back, , I know it is related to SSL operations, What can I do to reduce the SSL-related latency and improve the response time of my Django application when making API requests over SSL? What I've Tried: I profiled my Django application using a profilling module and found that a significant amount of time is spent on SSL operations when making API requests to the server. I noticed that SSL handshakes and some other SSL related functions are taking a long time. I expected the API requests to be processed much faster, like very much faster, 15 seconds is too -
<script src="https://js.stripe.com/v3/"></script> stripe submit button not working in django
html code <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{{ transaction_id }} Payments setup</title> {% load bootstrap5 %} {% bootstrap_css %} {% bootstrap_javascript %} <style> .bill-details-container { height: fit-content; padding: 1rm; } tr { border-bottom: 1px solid gray; } </style> <script src="https://js.stripe.com/v3/"></script> </head> <body> <div class="container"> <div class="row"> <div class="col-md-12 text-center"> <h1>Order details</h1> <hr> </div> <div class="col text-center mt-3"> <div class="row"> <div class="col"> <h5 class="fw-bold" style="color: #404145;">{{ package_name }}</h5> </div> <div class="col"> <h5 class="fw-ligh" style="color: #404145;">₹{{ actual_price }}</h5> </div> <div class="col-md-12"> <p>{{ package_discription }}</p> </div> </div> <div class="row"> <div class="col" style="background-color: #f5f5f5;"> <center> <div class="bill-details-container col"> <table width="100%"> <tr> <td style="text-align: center; padding-top: 10px; padding-bottom: 10px;">Service fee</td> <td style="text-align: left; padding-top: 10px; padding-bottom: 10px;"> {{ service_fee }}</td> </tr> <tr> <td style="text-align: center; padding-top: 10px; padding-bottom: 10px;">Package payment</td> <td style="text-align: left; padding-top: 10px; padding-bottom: 10px;">{{ actual_price }}</td> </tr> <tr> <td class="fw-bold" style="text-align: center; padding-top: 10px; padding-bottom: 10px;">Total payment</td> <td class="fw-bold" style="text-align: left; padding-top: 10px; padding-bottom: 10px;"> {{ actual_price_fee_added }} </td> </tr> </table> </div> </center> </div> <div class="col-md-12 mt-3"> <div class="container mt-5"> <div class="row justify-content-center"> <div class="col-md-6"> <div class="card"> <div class="card-header"> Payment Information </div> <div class="card-body"> <form action="{% url 'success' transaction_id request.user.username %}" id="payment-form"> <div id="card-element"> </div> <script> … -
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect:VSCode Terminal Python Interpretter - Miniconda environment
I am on Windows 10 OS, using VSCode, Miniconda environment with python 3.10 and django 4.1. I encountered the following error after installing an VSCode extension to view .xlsx files in VSCode. I uninstalled it since it did not work. The problems started after this. The following error displays in VSCode Python Interpreter virtual environment enabled terminal after typing in command: conda env list Also, no other 'conda' commands work without '--no-plugins' option. The highlighted text in below block is the error message: ERROR REPORT <<<<<<<<<<<<<<<<<<<<<< Traceback (most recent call last): File "C:\Users\jkcod\miniconda3\lib\site-packages\conda\exception_handler.py", line 17, in __call__ return func(*args, **kwargs) File "C:\Users\jkcod\miniconda3\lib\site-packages\conda\cli\main.py", line 54, in main_subshell parser = generate_parser(add_help=True) File "C:\Users\jkcod\miniconda3\lib\site-packages\conda\cli\conda_argparse.py", line 127, in generate_parser configure_parser_plugins(sub_parsers) File "C:\Users\jkcod\miniconda3\lib\site-packages\conda\cli\conda_argparse.py", line 354, in configure_parser_plugins else set(find_commands()).difference(plugin_subcommands) File "C:\Users\jkcod\miniconda3\lib\site-packages\conda\cli\find_commands.py", line 71, in find_commands for entry in os.scandir(dir_path): **> OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:\\Users\\jkcod\\AppData\\Local\\Programs\\Microsoft VS Code\\binC:\\Program Files\\Python310\\Scripts\\'** C:\Users\jkcod\miniconda3\Scripts\conda-script.py env list` environment variables: CIO_TEST=<not set> CONDA_DEFAULT_ENV=base CONDA_EXE=C:\Users\jkcod\miniconda3\condabin\..\Scripts\conda.exe CONDA_EXES="C:\Users\jkcod\miniconda3\condabin\..\Scripts\conda.exe" CONDA_PREFIX=C:\Users\jkcod\miniconda3 CONDA_PROMPT_MODIFIER=(base) CONDA_PYTHON_EXE=C:\Users\jkcod\miniconda3\python.exe CONDA_ROOT=C:\Users\jkcod\miniconda3 CONDA_SHLVL=1 CURL_CA_BUNDLE=<not set> HOMEPATH=\Users\jkcod LD_PRELOAD=<not set> PATH=C:\Users\jkcod\miniconda3;C:\Users\jkcod\miniconda3\Library\mingw- w64\bin;C:\Users\jkcod\miniconda3\Library\usr\bin;C:\Users\jkcod\minic onda3\Library\bin;C:\Users\jkcod\miniconda3\Scripts;C:\Users\jkcod\min iconda3\bin;C:\Users\jkcod\miniconda3\condabin;C:\Program Files\Python310\Scripts;C:\Program Files\Python310;C:\Program Files\Common Files\Oracle\Java\javapath;C:\Windows\system32;C:\Windows ;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0;C :\Windows\System32\OpenSSH;C:\Program Files\Java\jdk-17.0.1\bin;C:\Program Files\Git\cmd;C:\Users\jkcod\AppD ata\Local\Microsoft\WindowsApps;C:\Users\jkcod\AppData\Local\Programs\ Microsoft VS Code\binC:\Program Files\Python310\Scripts\;C:\Program Files\Python310\;C:\Program Files\Common Files\Oracle\Java\javapath;C: \Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\Syste m32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;%JAVA_HOME%\b in;C:\Program Files\Git\cmd;C:\Users\jkcod\AppData\Local\Microsoft\Win dowsApps;C:\Users\jkcod\AppData\Local\Programs\Microsoft VS Code\bin PSMODULEPATH=C:\Program … -
Why when view returns a list of objects from db html file didn't pick the value
def index(request): context = get_all_tasks() return render(request, 'sentixplorerapp/index.html',context) above is my view function when I return this to below html code snippet it return the accepted outcome. {% extends 'sentixplorerapp/base.html' %} {% block content %} <table border="1" style="width: 80%;" class="table table-striped"> <thead> <tr> <th>Id</th> <th>Task Name</th> <th>File Path</th> <th>Result</th> </tr> </thead> <tbody> {% for task in tasks %} <tr> <td>{{ task.id }}</td> <td>{{ task.taskName }}</td> <td>{{ task.filepath }}</td> <td>{{ task.result }}</td> </tr> {% endfor %} <!-- You can add more rows as needed --> </tbody> </table> {% endblock %} but when I change my view function as below It didn't get any values to html view. Can you help me to understand why? def index(request): context = {'tasks': get_all_tasks()} return render(request, 'sentixplorerapp/index.html',context) I'm expecting to get table data that return from get_all_task() view in html when it look like this, def index(request): context = {'tasks': get_all_tasks()} return render(request, 'sentixplorerapp/index.html',context) -
How to make Django tree view
html {% for acc in accs %} <ul class="tree" id="tree"> <li> <details> <summary>{{acc.acc_id1}} {{acc.E_name1}} </summary> <ul> <details> <summary> {{acc.acc_id2}} {{acc.E_name2}}</summary> <ul> <details> <summary>{{acc.acc_id3}} {{acc.E_name3}}</summary> <ul> <li>{{acc.acc_id4}} {{acc.E_name4}}</li> </ul> </details> </ul> </details> </ul> </details> </li> </ul> {% endfor %} models.py from django.db import models class Mainacc (models.Model): acc_id1 = models.IntegerField(unique=True) E_name1 = models.CharField(max_length=10) A_name1 = models.CharField(max_length=10) def __str__(self): return f'{self.acc_id1} {self.E_name1}' class Aacc (models.Model): acc_id1 = models.ForeignKey(Mainacc, on_delete = models.CASCADE) acc_id2 = models.IntegerField( db_index=True, unique=True) E_name2 = models.CharField(max_length=50) A_name2 = models.CharField(max_length=50) def __str__(self): return f' {self.acc_id2} {self.E_name2}' class Bacc (models.Model): acc_id2 = models.ForeignKey(Aacc, on_delete =models.CASCADE) acc_id3 = models.IntegerField( db_index=True, unique=True) E_name3 = models.CharField(max_length=100) A_name3 = models.CharField(max_length=100) def __str__(self): return f' {self.acc_id3} {self.E_name3}' class Cacc (models.Model): acc_id3 = models.ForeignKey(Bacc, on_delete=models.CASCADE) acc_id4 = models.BigIntegerField( db_index=True, unique=True) E_name4 = models.CharField(max_length=100) A_name4 = models.CharField(max_length=100) def __str__(self): return f' {self.acc_id4} {self.E_name4}' views.py def Acc(request): mainacc_list = Mainacc.objects.all() aacc_list = Aacc.objects.all() bacc_list = Bacc.objects.all() cacc_list = Cacc.objects.all() acc_list = list(chain(mainacc_list, aacc_list,bacc_list,cacc_list)) return render (request,'templates\\acc\\acc.html',{'accs':acc_list}) -
Deploy Django with TailwindCSS on Elastic Beanstalk
Good day, I recently deployed a Django project to Elastic Beanstalk using the following tutorial: https://testdriven.io/blog/django-elastic-beanstalk/ This is the website: http://gmoonline4-dev.us-east-1.elasticbeanstalk.com/ The website works fine, including the admin and database, except for the CSS, which gives an error This template loads properly in development, but you can see the end product after deployment. I tried including the container_command "python3 manage.py tailwind start", but this fails the deployment. Can anyone assist me with this? I am not sure if this is an error in my django application or my EB configuration. Thanks! If you need any code, I'll post it here -
why i get None instead of the model id in django ImageField path
When attempting to add a new event through the Django admin panel, the image is incorrectly being stored at the path "media/events/None/poster/file.png" instead of the intended path "media/events/{instance.id}/poster/file.png." I have added a print(...) statement to the get_poster_image_path function for testing purposes. : def get_poster_image_path(instance, filename): print(f""" from get_poster_image_path ==================\n type :{type(instance)}\n instance :{instance}\n instance.id :{instance.id}\n instance.name :{instance.name} """) return f'events/{instance.id}/poster/{filename}' class Event(models.Model): name = models.CharField(max_length=50) poster = models.ImageField(upload_to=get_poster_image_path,null=True,blank=True) .... the result: from get_poster_image_path ============================= type :<class 'events.models.Event'> instance :myevent instance.id :None instance.name :myevent -
Custom Session backend for Django using firestore
We are tryng to create a custom backend session engine using firestore. The autentication methodology is FireBase Auth. We have created the following code for the custom session and while we are abl to create collections in Firestore , data with session_key and uid is not being written to docs in the collection. We are hoping to eliminate the use of SQLite or any other sql for production -
python: can't open file '/Users/hillarytembo/Desktop/studybudy/manage.py': [Errno 2] No such file or directory
I made this command “python manage.py runserver” I got this error “ python: can't open file '/Users/hillarytembo/Desktop/studybudy/manage.py': [Errno 2] No such file or directory” how can i fix this I tried to check if the file was there and I found the file was there -
get_absolute_url does not work in my django app
in my django app, i have used get_absolute_url in model. from django.db import models from django.urls import reverse class nm(models.Model): name = models.CharField(max_length=50) no = models.IntegerField() def __str__(self): return f"\n{self.name}|{self.no}\n" def get_absolute_url(self): return reverse("number-str-url", args=[self.name]) but in django template when i want to link that, it does not work {% extends "base.html" %} {% block title %}Numbers{% endblock title %} {% block content %} <ul> {% for number in numbers %} <li><a href="{{number.get_absolute_url}}">{{number|title}}</a></li> {% endfor %} </ul> {% endblock content %} i want to show list of numbers one, two, three, four and five. when user clicks on one of them, the link navigate user to dedicated page of the number. something like this: One Two Three Four Five -
Django Python+Ajax : how to update variable from frontend to back end? My ajax function isn't working
When the user submits this form I want to save the rgb color code as a variable to be stored on the back end (using django), so whenever the card is loaded (the colour picked on this page) will be loaded. I asked GPT, which suggested using ajax (I've never used it before). This is a snippet from my js : function updateSetColor(color) { console.log(color); $.ajax({ type: "POST", url: "/Flashcard/", beforeSend: function(xhr, settings) { xhr.setRequestHeader("X-CSRFToken", getCookie("csrftoken")); }, data: { color: color }, error: function(error) { console.log("Error updating color"); }, cache: false, }); } This is a snippet from my view that uses the color variable sent from the data : def flashcard(request): form = Flashcard_verif(request.POST) if request.method == "POST" and form.is_valid() and request.accepts('main/Flashcard.html'): print(request.POST) color = request.POST.get("color") # Get the color from the AJAX request print(color) As you can see I've got the console to output the color picked by the user and on the backend I've got the server to output the color that should've been recieved. The output from the console is correct but the output from the server is 'None'. I suspect its due to the ajax function. Any help would be appreciated or new ways of … -
Django Serializer with Many To Many fileld returns empty list, How to fix it?
I have two models Product and Lessons. I join them in one Product serializer. But I get empty list in lesson fileld. This is what I am getting now: { "id": 1, "name": "Python", "owner": 1, "lessons": [] # here should be lessons }, my modelds.py class Product(models.Model): name = models.CharField(max_length=250) owner = models.ForeignKey(User, on_delete=models.CASCADE) class Lesson(models.Model): name = models.CharField(max_length=255) video_link = models.URLField() duration = models.PositiveIntegerField() products = models.ManyToManyField(Product, related_name='lessons') My serializers.py class LessonSerializer(serializers.ModelSerializer): class Meta: model = Lesson fields = ('id', 'name', 'video_link', 'duration') class ProductSerializer(serializers.ModelSerializer): lessons = LessonSerializer(read_only=True, many=True) class Meta: model = Product fields = ['id', 'name', 'owner', 'lessons'] And my view.py class LessonListView(ListAPIView): serializer_class = ProductSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): lesson_view = Product.objects.all() return products_view I can see many topics in the internet about that but I it is not working for me at all. How can I resolve it and get my data that I have for lessons field ? -
Django: How to enable app usage for different societies
I have a django project that has many apps. There is a core app that has all the main models that other secondary apps will use. One model in the core app is called SocietyEntity: class SocietyEntity(models.Model): id = models.AutoField(primary_key=True) referenceName = models.CharField(max_length=200, verbose_name="Nombre") members = models.ManyToManyField(get_user_model()) administrator = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, verbose_name="Administrator") As shown, the societies can have one o more users as members. What I want to achieve is some kind of relation between societies and the other secondary apps of the project, that enable that society to make use of the app. Something like a manytomany kind of relation between SocietyEntity and app names? I'm not sure but I think I need some way to relate societies to apps, if that is even possible. If a society doesn't have permission to use an app, this shouldn't be listed in the admin interface for example. Any suggestion is well received! Thanks