Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python, Django: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'accounts.Usuarios' that has not been installed
Good morning! Although questions similar to this have been posted here, I have not been able to resolve my issue yet. I have tried all proposed solutions. The problem started after I put, or at least tried to put, "email" as the username, removing the username from the model. I will share the points that I think are relevant. If you need more, you can ask. problem: PS C:\SocialFacil\socialfacil_web> python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\SocialFacil\lib\site-packages\django\apps\config.py", line 235, in get_model return self.models[model_name.lower()] KeyError: 'usuarios' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\SocialFacil\lib\site-packages\django\contrib\auth\__init__.py", line 170, in get_user_model return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) File "C:\SocialFacil\lib\site-packages\django\apps\registry.py", line 213, in get_model return app_config.get_model(model_name, require_ready=require_ready) File "C:\SocialFacil\lib\site-packages\django\apps\config.py", line 237, in get_model raise LookupError( LookupError: App 'accounts' doesn't have a 'Usuarios' model. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Victor\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\Victor\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\SocialFacil\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\SocialFacil\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\SocialFacil\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\SocialFacil\lib\site-packages\django\core\management\__init__.py", line … -
Please how to solve NoReverseMatch
Reverse for 'student_detail' with keyword arguments '{'student_id': 'STUD/1/230922'}' not found. 1 pattern(s) tried: ['students/STUD/(?P<student_id>[0-9]+)/(?P<current_date>[0-9]+)/\Z'] this is how I set my urls.py path('STUD/int:student_id/int:current_date/', views.StudentDetailView.as_view(), name='student_detail'), -
Is it possible to save a class using django redis cache to use it after the user reconnects
I need to save a class to use it if the websocket disconnects and assign it to the websocket again if it reconnects. But when saving i get this error: "Exception inside application: Can't pickle local object" which i think is because i cant save a class to the cache. Is it possible to overcome this and save the class in the cache? -
How can I give input with getpass to a Django app when deploying using Nginx, Gunicorn and systemd?
I have a Django app that has key on disk which is encrypted using AES Cypher, and must be unencrypted in memory for use during the processes. I have this line in settings.py: AES_CIPHER_KEY = getpass("Enter AES cipher key: (leave blank if you don't need decryption)") This is my gunicorn.socket: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target This is my gunicorn.service: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=www-data WorkingDirectory=/root/samir/src/samirpy ExecStart=/root/samir/venv/bin/gunicorn --access-logfile --workers 3 --bind unix:/var/log/gunicorn/samir.sock samir.wsgi:application [Install] WantedBy=multi-user.target This is my nginx.conf: server { listen 80; server_name example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /var/www; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } This is wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'samir.settings') application = get_wsgi_application() What I would like to happen is when I update the code and restart the service using: sudo systemctl restart gunicorn it prompts for the key before starting the main process. -
Daphne websocket stop responding after somtime
Project Specs: Django 3.2.4 , Channels 3.0.5 , Channel-redis 3.4.1 , Daphne 3.0.2. I setup a chat system, which communicate using websocket. On page load, everything works fine, but after few seconds only (~20-30 sec), data sending and receiving halt. On refresh page, it again start working. I am not sure, this issue araise from Consumers file or Daphne from my server. below is my --access-log of daphne enter image description here I tried debugging consumers.py and found nothing, but not sure how to debug daphne or server side issue. Please guide me some checklist to trace issue. I want the connection stay ALIVE for 30 minutes atleast. For setting up daphne on nginx, i followed this tutorial. -
Django threaded comments (MPTT) optimization issue
I'm using MPTT model to build a nested comments system in my Django Rest project. Everything works so far but I experience a huge performance issue when querying a database for API response. The schema of comments layout: Root Comment / \ Comment Comment / \ Child Child Whenever I'm querying all comments as an array in API response recursively: { "comments": [ { "id": 1, "children": [ "id": 4, "children": [ "id": 5, "children": ... ] ] } In this case even with "prefetch_related" and "select_related" I'm getting over 50 queries for 2 parent(root) comments (which have children comments and so on). Is there an efficient way to optimize this query? Even 2 levels comments system is acceptable for me but I can't figure out the right implementation for this: Comment \ Child1, Child2, Child3, Child4 My code for reference: class Comment(MPTTModel): profile = models.ForeignKey(Profile, related_name="comments", on_delete=CASCADE) post = models.ForeignKey(Post, related_name="comments", on_delete=CASCADE) parent = TreeForeignKey("self", related_name="children", null=True, on_delete=models.CASCADE) text = models.TextField(max_length=350) date_published = models.DateTimeField(auto_now_add=True, verbose_name="Date published") comments = Comment.objects.filter(level=0) \ .select_related("profile", "post", "profile__specialization") \ .prefetch_related("children", "parent") \ .order_by("-date_published") -
Python Django Updating object IntegrityError, NOT NULL constraint failed
I'm trying to create view for my Food Tracking App where I can first pick a given date and then add items to the FoodLog object, however while viewing macros work after picking date, I can't really add any new other objects becuase of the following error: django.db.utils.IntegrityError: NOT NULL constraint failed: accounts_foodlogfooditem.food_log_id [23/Sep/2023 13:56:08] "POST /accounts/food-log/ HTTP/1.1" 500 153768 I want to make it so that first I'll be able to pick a date and then either show what's in the FoodLog or be able to add new objects to it. My View: def food_log(request): food_log = None total_macros = {} if request.method == 'POST': date_form = DateForm(request.POST) food_item_form = FoodLogFoodItemForm(request.POST) if date_form.is_valid(): selected_date = date_form.cleaned_data['date'] food_log, created = FoodLog.objects.get_or_create(user=request.user, date=selected_date) total_macros = food_log.calculate_total_macros_log() if food_item_form.is_valid(): food_log_food_item = food_item_form.save(commit=False) food_log_food_item.food_log = food_log food_log_food_item.save() else: today = timezone.now().date() food_log = FoodLog.objects.filter(user=request.user, date=today).first() date_form = DateForm(initial={'date': today}) if food_log: total_macros = food_log.calculate_total_macros_log() food_item_form = FoodLogFoodItemForm() return render(request, 'food_log.html', {'food_log': food_log, 'date_form': date_form, 'food_item_form': food_item_form, 'total_macros': total_macros}) Models I have: class FoodLog(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) foods = models.ManyToManyField(FoodItem, blank=True, through='FoodLogFoodItem') meals = models.ManyToManyField(Meal, blank=True, through='FoodLogMeal') date = models.DateField() def calculate_total_macros_log(self): log_total_kcal = 0 log_total_carbohydrates = 0 log_total_fats = 0 log_total_proteins = … -
Why i can't use migrations with user_account in my INTERNAL APPS
When creating a custom model, when I register the app in INTERNAL APPS, the program doesn't allow me to perform migrations and throws an error: "ModuleNotFoundError: No module named 'user_account'." (Python Django). I have tried cleaning the database as we did in the class and recreating it, but with the 'user_account' line in INTERNAL APPS, it refuses to perform the migration, and without it, it says that 'user_account' is uninstalled. -
What options are available for performance tuning a soundx query?
I was recently asked about improving website performance for a peers website. What options are typically used for performance tuning sites enabled with Soundx? Overview Using the homophones Smith/Smythe, I was able to reproduce the behavior of the website query response time described. These are measured at the browser so there's a lot that could go into the number, but generally speaking the values were what we would expect, less for the non-Soundex search and more for Soundex search. Smith - Not Soundex - (1705 results) - 6.62s server wait Smythe - Not Soundex - (8 results). - 5.51s server wait Smith - Soundex - (4446 results) - 9.47s server wait Smythe - Soundex - (4446 results) - 10.85s server wait Technical Stack language - python - 2.7.5 framework - Django - 1.3 database - not yet known - not yet known NOTE: Database type and version will most likely play a role in what solutions are viable. Sources Performance: Put soundex in DB or translate it after the query? https://support.ancestry.com/s/article/Searching-with-Soundex Similar Questions Using soundex feature w/django search engine -
Using django_debug_toolbar alongside drf_spectacular
I'm using drf_spectacular as swagger for my django projects since drf_yasg is deprecated. I tried to use django_debug_toolbar alongside drf_spectacular and I followed all of the instructions. The debug_toolbar's icon appears in swagger but when I try to call any api, a 'Not Found' error keeps showing up repeatedly! What is the problem? What should I do? -
join() argument must be str, bytes, or os.PathLike object, not 'NoneType' with Django
I'm running into an issue on my Django app. The issue is when I click on Add a Record the app returns the error: join() argument must be str, bytes, or os.PathLike object, not 'NoneType' but it shouldn't since I'm not doing any joining in my code. The view for this is: def add_job_record(request): add_form = AddJobTrackerForm(request.POST or None) if request.user.is_authenticated: if request.method == "POST": if add_form.is_valid(): add_job_record = add_form.save() messages.success(request, 'Job Tracker added') return redirect('core:home') return render(request, 'applications/add_record.html', {'add_form': add_form}) else: messages.danger(request, "You must be logged in") return redirect('core:home') I found a post here (I forgot to save the link) where the answer was to remove {'add_form': add_form} from my code but the form doesn't show up on the page when I removed it -
Can't integrate dist folder from React+Vite(Frontend) to Django Application(Backend)
I am building a SAAS application and I am using React + Vite as frontend and Django for Backend , I was testing authentication system by integrating build or dist folder after performing npm run build in FRONTEND application and copying it in Django's project directory I have updated my settings.py TEMPLATES constant : TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'dist')], '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 added STATIC FOLDER SETTINGS : STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_root') STATICFILES_DIRS = [BASE_DIR / "static"] I ran python manage.py collectstatic command I updated my project's urls.py file rom django.contrib import admin from django.urls import path,include,re_path from django.views.generic import TemplateView from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.jwt')), ] urlpatterns+=[re_path(r'^.*',TemplateView.as_view(template_name='index.html'))] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Not sure when I do python manage.py runserver , I am getting this in console and my frontend is not loaded localhost/:12 Refused to apply style from 'http://localhost:8000/assets/index-229ba335.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. index-bb014e79.js:1 Failed to load module script: Expected a JavaScript module script … -
i keep having an error in the {{ form|crispy }} line how to fix it?
`{% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4"> Join today </legend> {{ form|crispy}} </fieldset> <div class ="form-group"> <button class="btn-outline-info " type="submit">Sign Up</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted">Already have an account<a class="ml-2" href="#">Sign in</a> </small> </div> </div> {% endblock content %}` i tried the {% crispy form %} as well but still there is an error i did all these steps : Check Crispy Forms Configuration: Ensure that you have properly configured django-crispy-forms to use Bootstrap. In your project's settings.py, make sure you have set the CRISPY_TEMPLATE_PACK to 'bootstrap4' if you are using Bootstrap 4: python Copy code CRISPY_TEMPLATE_PACK = 'bootstrap4' Check Installed Apps: Verify that 'crispy_forms' is included in your INSTALLED_APPS list in settings.py. It should look like this: python Copy code INSTALLED_APPS = [ # ... 'crispy_forms', # ... ] Check Template Load Tags: Ensure that you have loaded the crispy_forms_tags at the top of your template file: html Copy code {% load crispy_forms_tags %} Correct Template Tag Usage: Double-check that you are using the {{ form|crispy }} filter correctly to render your form with Crispy Forms: html Copy code {{ … -
My value violates not-null constraint when its not null
I encountered an exception while saving the model django.db.utils.IntegrityError: null value in column "city" of relation "price_shop" violates not-null constraint DETAIL: Failing row contains (<id>, <name>, <address>, <ratings>, <owner__id>, <contacts>, <categories>, null, <city>). I don't know what is null means, maybe this counted as city My models.py file: from django.db import models from django.contrib.auth.models import User from django.contrib.auth import get_user_model class City(models.Model): readonly_fields = ('lower_name',) exclude = ('name_lower ',) name = models.CharField(max_length=100, unique=True) name_lower = models.CharField(max_length=100, unique=True, editable=False) def save(self, *args, **kwargs): self.name_lower = self.name.lower() super().save(*args, **kwargs) class Shop(models.Model): readonly_fields = ('ratings',) exclude = ('ratings ',) name = models.CharField(max_length=50) address = models.CharField(max_length=100) ratings = models.FloatField(default=0.0, editable=False) contacts = models.JSONField(default=dict, null=True, blank=True) categories = models.JSONField(default=dict, null=True, blank=True) city = models.ForeignKey(City, models.PROTECT, to_field='name', null=True, blank=True) owner = models.ForeignKey(User, on_delete=models.DO_NOTHING, null=True, blank=True) def __str__(self): return self.name class Item(models.Model): readonly_fields = ('name_lower',) exclude = ('name_lower ',) name = models.CharField(max_length=50) name_lower = models.CharField(max_length=50, editable=False) price = models.IntegerField() sale = models.IntegerField(default=0) in_stock = models.BooleanField(default=True) category = models.IntegerField() image = models.ImageField(upload_to='static', null=True, blank=True) markdown = models.TextField(null=True, default="Магазин не оставил описания") tags = models.JSONField() shop = models.ForeignKey(Shop, on_delete=models.CASCADE) def save(self, *args, **kwargs): self.name_lower = self.name.lower() super().save(*args, **kwargs) def __str__(self) -> str: return f"{self.shop.name}: {self.name}" class Review(models.Model): author = … -
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 …