Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
403 Authentication Credentials not provided NextJS Django
FRONTEND: useEffect(() => { async function fetchProfile() { try { const response = await fetch("/api/user_profile", { headers: { 'Content-Type': 'application/json'}, credentials: 'include' }); const data = await response.json(); setUserProfile(data); } catch(err){ console.error("Error fetching profile data", err); } } fetchProfile(); },[]); useEffect(() => { // Log the user profile state console.log(userProfile); }, [userProfile]); import { cookies } from 'next/headers' export async function GET(request: Request) { const cookieStore = cookies(request); const sessionID = cookieStore.get('sessionid')?.value; const csrfToken = cookieStore.get('csrftoken')?.value; const response = await fetch('http://127.0.0.1:8000/auth/profile/', { headers: { 'Content-Type': 'application/json', 'Cookie': `sessionid=${sessionID}; csrftoken=${csrfToken}`, }, }); const response_data = await response.json(); return Response.json({ response_data }); } BACKEND: class UserProfileView(views.APIView): permission_classes = [permissions.IsAuthenticated] def post(self, request, *args, **kwargs): user_profile, _ = UserProfile.objects.get_or_create(user = request.user) serializer = UserProfileSerializer(user_profile, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request, *args, **kwargs): user_profile = get_object_or_404(UserProfile, user=request.user) serializer = UserProfileSerializer(user_profile) return Response(serializer.data) class LoginView(views.APIView): permission_classes = [permissions.AllowAny] def post(self, request, *args, **kwargs): username = request.data.get('username') password = request.data.get('password') user = authenticate(request, username=username, password=password) if user is None: return Response({'error': 'Invalid Credentials'}, status=status.HTTP_401_UNAUTHORIZED) login(request, user) return Response({'message': 'User logged in successfully'}) The problem is I cannot access my user profile endpoint even with passing the details. I have a … -
Using pytest to test django packages
I have created a Django package (a Django App) that adds functionality to Django when installed and referenced in settings.py INSTALLED_APPS of the Django project. I am familiar with writing tests for Django using pytest, and the pytest-django plugin. As the pytest-django plugin provide fixtures such as a web client to interact with the django project. However I never wrote tests for a Django package. How do I use pytest and pytest-django plugin to test my Django package, without having a real django project that has settings.py that loads the package? -
How can i set dependencies between event after data load in scheduler pro in bryntum?
In Bryntum Scheduler Pro, in project object i load data by a url then i set dependencies between event by dependency_dict(which i pass from my backend) i try this code, but it show error like TypeError: scheduler.dependencies.addDependency is not a function, How can i set dependency between event after load data? project: { transport: { load: { url: path, } }, listeners: { load: function (project) { var response = project && project.response; var dependency_dict = response.dependencies.rows; if (dependency_dict) { dependency_dict.forEach(function (dependency) { scheduler.dependencies.addDependency(dependency.fromEvent,dependency.toEvent); }); } }, }, autoLoad: true, resourceStore: { modelClass: ResourceModel }, eventStore: { modelClass: EventModel, }, } i also try this var dependency_dict = response.dependencies.rows; if (dependency_dict) { dependency_dict.forEach(function (dependency) { project.dependencyStore.add(dependency); }} give me same error TypeError my backend code : https://codefile.io/f/lXVaNcJZ4z my scheduler pro code : https://codefile.io/f/OZFfMIHQ3H -
Set table width with pandas set_table_styles
I'm trying to set the table width using set_table_styles, but it doesn't work. I tried to find information about this in the documentation, but there is no example there. I looked into this issue, but it didn't help either. https://stackoverflow.com/questions/74046791/set-width-to-100-fill-container-with-pandas-set-table-styles Part of my code: turnover = pd.pivot_table(data_for_turnover, columns=['Date'], values=['Turnover', 'Sales', 'Stocks'], aggfunc='sum') table_style = {'selector': 'table','props': [('width', '100%')]} turnover = turnover.style.format('{:.0f}') turnover.set_table_styles([table_style]).to_html() Next I display using Django, but the width (I also tried change border, margin) does not change. If I try to change the th or td styles, they are applied. Please help me find, if not a solution, then a reason. -
Django Channels Web Socket Connection Keeps Closing
I created the following consumers in my django application to handle real time notifications: class NotificationConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = f"notification_{self.scope['url_route']['kwargs']['user_id']}" await self.channel_layer.group_add(self.room_name, self.channel_name) await self.accept() # other methods below and i have my routing to this consumer here: from django.urls import re_path, path from .consumers import NotificationConsumer websocket_urlpatterns = [ path('notification/<int:user_id>/', NotificationConsumer.as_asgi()), ] Then i am connecting to this in the frontend with javascript: const websocketProtocol = window.location.protocol === "https:" ? "wss" : "ws"; const wsEndpoint = `${websocketProtocol}://${window.location.host}/notification/{{request.user.id}}/`; const socket = new WebSocket(wsEndpoint); socket.onopen = (event) => { console.log("WebSocket connection opened!"); }; socket.onclose = (event) => { console.log("WebSocket connection closed!"); }; It works locally on my computer but when i hosted it on a live domain, each time i load the page where this web socket was created, i get the following error in the console: tutor-message-list/:236 WebSocket connection to 'wss://www.youvarsity.org/notification/2/' failed: and then the close event fires off and logs to the console: WebSocket connection closed! It worked locally and i have tried debugging but i do not know how to solve this. Please help -
How to reference to multiple users in Django
I want to create projects page where user can reference multiple users(there no limit to number of users to reference). How can I do that? Is it possible? I thought that i can use for loop but i can't imagine how to do that -
Foreign key constraint failed when changing data form admin panel
i was trying to insert some test data through the admin panel but I keep getting stuck on the FOREIGN KEY constraint failed error. I'm trying to create an Event this is how my class looks: from django.db import models from datetime import datetime, timedelta # Create your models here. class Event(models.Model): title = models.CharField(max_length=20) description = models.CharField(max_length=200) start_time = models.DateTimeField() end_time = models.DateTimeField() email = models.EmailField(blank=False, max_length=254) phone = models.CharField(max_length=15) def get_events_from_weekday(weekday): index_week = weekday.weekday() week_start = weekday - timedelta(days=index_week) week_end = week_start + timedelta(days=6) return Event.objects.filter(start_time__range=[week_start, week_end]) def get_event_from_start_time(start_time): return Event.objects.filter(start_time=start_time) Also for my customer class i cannot create an object through the admin panel. But I can create a customer through my register page. This is my customer model from django.utils import timezone from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, UserManager from django.contrib.auth.models import BaseUserManager from django.core.mail import send_mail from django.conf import settings # Create your models here. class CustomerManager(BaseUserManager): def _create_user(self,name, last_name, email, phone, password, **extra_fields): if not email: raise ValueError('Customers must have an email address') user = self.model( email=email, name=name, last_name=last_name, phone=phone, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self,name, last_name, email, phone, password, **extra_fields): extra_fields.setdefault('is_superuser', False) extra_fields.setdefault('is_staff', False) return self._create_user(name, last_name, email, … -
Getting 504 error around 15 seconds Django IIS
I am running a Django website o windows server using IIS. The problem is that I am getting 504 gateway error at around 15 seconds (15.3 and 15.6) some times. I have increased IIS Connection time-out to 360 seconds. But the error occurs again and some times it occurs at around 100 s. I want to know what settings has been set to 15, and how should I resolve the problem? -
Why doesn't my Django app work, 404 Page not found
I know somebody has asked this question this is the link to it, but none of the solutions there worked for me so I had to open a new question. When I run my code I get this error message: Using the URLconf defined in storefront.urls, Django tried these URL patterns, in this order: admin/ playground/ The empty path didn’t match any of these. here is my storefront urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('playground/', include('playground.urls')), ] and here is my playground urls.py: from django.urls import path from . import views # URL conf module urlpatterns = [ path('hello/', views.say_hello) ] also here is my playground views.py: from django.shortcuts import render from django.http import HttpResponse def say_hello(request): return HttpResponse('Hello World') Can somebody tell me what could be the problem? Thank you. -
Optimizing Video Load Times on Mobile(Django)
I'm currently developing a website for a client, which serves as a platform for uploading and showcasing videos to their customers. The site features seven short videos (each under 1 minute) on the landing page. However, I've encountered a loading speed issue when accessing the site on mobile devices; the videos load quite slowly despite a fast internet connection. This issue doesn't occur on PC. The website is hosted on an Ubuntu VPS and is dockerized. Does anyone have suggestions on how to optimize the loading speed for mobile devices? Any advice would be greatly appreciated. I implemented lazy loading for the videos, hoping this would enhance the loading speed on mobile devices. Despite this implementation, the loading speed on mobile remains considerably slow, which is not the case on desktop. -
Wagtail, can't add settings
I'm trying to add custom settings to wagtail (version 4.0.4). Following the guide from the docs, I added wagtail.contrib.settings to INSTALLED_APPS and added this to models.py: from wagtail.contrib.settings.models import register_setting, BaseGenericSetting from django.db import models @register_setting class Authors(BaseGenericSetting): facebook = models.URLField() Then made makemigrations/migrate. But nothing appeared in Wagtail settings. Then I tried to register model in admin. In wagtail_admin.py from wagtail.contrib.modeladmin.options import ( ModelAdmin, modeladmin_register, ) from .models import Authors @modeladmin_register class AuthorsAdmin(ModelAdmin): model = Authors list_display = ("facebook",) add_to_settings_menu = True menu_label = "Authors" But still the same result. What do I miss? Some extra config or ...? Only after removing add_to_settings_menu = True, Authors appears in the side-menu (but, of course, not in the settings). With this line - nothing. -
How to fix coverage report error in github actions with django?
I am finding the solution for this issue, its getting error on coverage report dependencies installing section without any reason Requirement already satisfied: coverage in /opt/hostedtoolcache/Python/3.8.18/x64/lib/python3.8/site-packages (7.3.4) Collecting run Downloading run-0.2.tar.gz (3.2 kB) Installing build dependencies: started Installing build dependencies: finished with status 'done' Getting requirements to build wheel: started Getting requirements to build wheel: finished with status 'error' error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [17 lines of output] Traceback (most recent call last): File "/opt/hostedtoolcache/Python/3.8.18/x64/lib/python3.8/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 353, in <module> main() File "/opt/hostedtoolcache/Python/3.8.18/x64/lib/python3.8/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 335, in main json_out['return_val'] = hook(**hook_input['kwargs']) File "/opt/hostedtoolcache/Python/3.8.18/x64/lib/python3.8/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 118, in get_requires_for_build_wheel return hook(config_settings) File "/tmp/pip-build-env-nni0_rb_/overlay/lib/python3.8/site-packages/setuptools/build_meta.py", line 325, in get_requires_for_build_wheel return self._get_build_requires(config_settings, requirements=['wheel']) File "/tmp/pip-build-env-nni0_rb_/overlay/lib/python3.8/site-packages/setuptools/build_meta.py", line 295, in _get_build_requires self.run_setup() File "/tmp/pip-build-env-nni0_rb_/overlay/lib/python3.8/site-packages/setuptools/build_meta.py", line 480, in run_setup super(_BuildMetaLegacyBackend, self).run_setup(setup_script=setup_script) File "/tmp/pip-build-env-nni0_rb_/overlay/lib/python3.8/site-packages/setuptools/build_meta.py", line 311, in run_setup exec(code, locals()) File "<string>", line 12, in <module> NameError: name 'file' is not defined [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> See above for output. note: This error originates from a subprocess, and … -
Get the latest input from the model
I wanna the last input to bid_price to be received in the Bid_info model and attributed to bid_max, however it gives this error earliest() and latest() require either fields as positional arguments or 'get_latest_by' in the model's Meta. views: @login_required def page_product(request, productid): bid_max = Bid_info.objects.filter(pk=productid).latest() context={ 'bid_max' : bid_max } return render(request, 'auctions/page_product.html', context) html: <p> final price = {{bid_max}} </p> models: class Bid_info(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) seller = models.ForeignKey(User, on_delete=models.CASCADE, related_name="seller") bid_price = models.DecimalField(max_digits=10, decimal_places=2) checkclose = models.BooleanField(default=False) winner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) -
Error integrating Django run server on windows 10
TypeError: translation() got an expected keyword argument 'codeset' First it started as python not found. I went ahead installing python from MS store. Most of the modules are raising translation errors like: _boostrap._gcd_import(name[level:], package, level) Self.remote_field.through = create_many_to_many_intermediary_model(self, cls) -
Getting code coverage 0% despite getting print statements in Django development server
I have a django project running on local development server. It has different remote DB server. I am trying run API integration tests. Tests are running and giving expected output. Also print statements are generated in console for APIs I am running tests for. But still code coverage is shown 0% for file which was executed after API hit. This is my sample test function class Test_Login_User_FR_and_Dispatcher: BASE_URL = http://passcodev.localhost:8000 FR_LOGIN_ENDPOINT = '/api/user/login/' # TESTCASE FOR SUCCESSFULL LOGIN OF USER def test_successfull_login_user(self, success_login): successfull_login = requests.post(f'{self.BASE_URL}{self.FR_LOGIN_ENDPOINT}',json=success_login) assert successfull_login.status_code == 200 I am using coverage.py for code coverage report generation. I tried coverage.py, pytest cov. But still I am unable to find any leads to troubleshoot this problem. -
AddEventListener is executed twice
I am working with Django and Js, and I am trying to get the code to switch the checked attribute of an element so that it changes the category during the creation of an entry in the form, but when clicking on the element, addEventListener is executed twice and, thus, first adds the checked attribute to the element but then immediately removes it Code: form <div class="new-post-header"> <div class="new-post-functions"> <button type="submit" class="save"><ion-icon name="checkmark-outline"></ion-icon></button> <div class="categories"> <div class="first-category">{{ form.category.0 }}</div> <div class="second-category">{{ form.category.1 }}</div> </div> </div> </div> <div class="new-post-content"> <div class="new-title">{{ form.title }}</div> <div class="new-description">{{ form.description }}</div> </div> js secondInput.hasAttribute('checked') ? localStorage.setItem('secondInput', true) : localStorage.setItem('secondInput', false) secondLabel.addEventListener('click', function() { let secondInputItem = localStorage.getItem('secondInput') if (secondInputItem === 'false') { firstLabel.innerHTML = `<input type="radio" name="category" value="1" required="" id="id_category_0"><ion-icon name="bookmark-outline"></ion-icon>` secondLabel.innerHTML = `<input type="radio" name="category" value="2" required="" id="id_category_1" checked="checked"><ion-icon name="archive-outline"></ion-icon>` localStorage.setItem('secondInput', true) console.log(true) } else { firstLabel.innerHTML = `<input type="radio" name="category" value="1" required="" id="id_category_0" checked="checked"><ion-icon name="bookmark-outline"></ion-icon>` secondLabel.innerHTML = `<input type="radio" name="category" value="2" required="" id="id_category_1"><ion-icon name="archive-outline"></ion-icon>` localStorage.setItem('secondInput', false) console.log(false) } }) -
I have a problem with django in python, i just installed in couple of days and it gave an error when every time i run it
/usr/bin/env : The term '/usr/bin/env' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 /usr/bin/env python "d:\Documents\Python\ecommerce\manage.py" + CategoryInfo : ObjectNotFound: (/usr/bin/env:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException how can i fix this? -
Create super user using Railway CLI
I'm trying to create super user for my django project using Railway CLI. I've install Railway CLI and tried 1-step railway login Successfully logged in 2-step railway link Linked my project 3-step railway run python manage.py createsuperuser But unexpectedly I've got this error : No such file or directory (os error 2) My django project is working awesome on railway, but can't do this task -
Django + Celery + SQS - Messages not received by celery worker?
I'm trying to implement background tasks on my Django web app using Celery and AWS SQS as the message broker. I have a view which calls a task, which is sent to SQS successfully. However, the actual task never gets executed (i.e. the print statements I have added in the task never get printed), even though I can see the number of in flight requests going up on SQS. I have configured Celery in my settings.py - CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_TASK_DEFAULT_QUEUE = 'tk-test-queue' CELERY_BROKER_URL = "sqs://%s:%s@" % (quote(os.environ.get('AWS_ACCESS_KEY_ID'), safe=''), quote(os.environ.get('AWS_SECRET_ACCESS_KEY'), safe='')) CELERY_BROKER_TRANSPORT_OPTIONS = { 'region': 'ap-south-1', 'visibility-timeout': 60 * 30, 'polling_interval': 1 } CELERY_RESULT_BACKEND = None My celery.py looks like this - import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_project.settings') app = Celery('my_project') app.config_from_object('django.conf:settings', namespace="CELERY") app.autodiscover_tasks() I have defined a task in my_app/tasks.py - from time import sleep, ctime from celery import shared_task @shared_task def celery_task(): print(f'Starting task at {ctime()}') sleep(25) print(f'Task finished at {ctime()}') Which I am using in my my_app/views.py - class TestCeleryView(View): def get(self, request): print('In view') celery_task.delay() return HttpResponse('Success') I am starting the celery worker by running - celery -A my_project worker -l INFO Every time I visit the URL for my view … -
Django Refresh Token Rotation and User Page Refresh
I'm using Django simple JWT to implement user authentication, I have done few adjustments so the access token and refresh token are sent as http-only cookies and everything works well On the frontend I have implemented Persistent Login that would keep the user logged in when they refresh the page or close the browser etc. But since I have enabled these settings: "ROTATE_REFRESH_TOKENS": True, "BLACKLIST_AFTER_ROTATION": True, If the user keeps refreshing the page multiple times in a very short time, it might occur that a token is blacklisted before the user receives the new refresh token is there a way to fix that? One possible fix yet I'm not sure of its reliability is disabling the automatic blacklisting and waiting for the frontend to send a request upon receiving the new refresh token, the request containing the old refresh token in its body like this @api_view(['POST']) def blacklist_token(request): refreshToken = request.data.get("refresh") print(refreshToken) if refreshToken: token = tokens.RefreshToken(refreshToken) token.blacklist() return Response(status=status.HTTP_200_OK) PS: Using React.js on the frontend -
How to update Django model fields after filtering by id?
I want to write a function that, when executing a "GET" request, will change fields such as: "inaction" and "lastAction" to 2 and the datetime.now(). But when I wrote my code for the first time, I encountered an error: TypeError: cannot unpack non-iterable int object. This code: def update(self, res_id: str): user, updated = User.objects.filter(id=res_id).update(inaction="2", lastAction=datetime.now()) code_status = HTTPStatus.ACCEPTED if updated else HTTPStatus.OK.value return user, code_status For this reason, I rewrote my code to the following and that started works: def update(self, res_id: str): updated_rows = User.objects.filter(id=res_id).update(inaction="2", lastAction=datetime.now()) user = User.objects.filter(id=res_id).first() code_status = HTTPStatus.ACCEPTED if updated_rows else HTTPStatus.OK.value return user, code_status But in this code, I'm worried about duplicates of the form: User.objects.filter(id=res_id). How can I avoid them? -
Display only certain values of foreignkey in django admin
I have three models in my django project. I want only those products to show up in django admin in product field of variation_price model for which variations already exist. How can I achieve that? In models.py: class VariationManager(models.Manager): def color(self): return super(VariationManager,self).filter(variation_category='color', is_active=True) def sizes(self): return super(VariationManager, self).filter(variation_category='size', is_active=True) variation_category_choice = ( ('color', 'color'), ('size', 'size'), ) class Variation(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) variation_category = models.CharField(max_length=100, choices=variation_category_choice) variation_value = models.CharField(max_length=100) objects = VariationManager() class variation_price(models.Model): price = models.IntegerField() product = models.ForeignKey(Product, on_delete=models.CASCADE) variations = models.ManyToManyField(Variation, blank=True) is_active = models.BooleanField(default=True) Thanks -
RawQueryset isn't working. ProgrammingError-"Error binding parameter 1: type 'builtin_function_or_method' is not supported"
views.py - if product.variant != "None": variants = Variants.objects.filter(product_id=product.id) colors = Variants.objects.filter(product_id=product.id, size_id=variants[0].size_id) sizes = Variants.objects.raw("SELECT * FROM core_variants WHERE product_id=%s GROUP BY size_id",[id]) variant = Variants.objects.get(id=variants[0].id) context = {'sizes': sizes, 'colors': colors, 'variant': variant, } return render(request, 'core/product-details.html', context) product-details.html - <select name="size" id="size" class="form-control"> {% for rs in sizes %} <option {% if variant.size_id == rs.size_id %}selected{% endif %} value="{{rs.size_id}}">{{rs.size_id.title}}</option> {% endfor %} </select> The error i'm getting is "Error binding parameter 1: type 'builtin_function_or_method' is not supported" The line i'm getting error is "{% for rs in sizes %}" I just want to show all the options from the queryset -
who will serve ASGI and WSGI when i add daphne?
when i add daphne in INSTALLED_APPS how will it work ? does it work itself to serve WSGI and ASGI ? or Does it work alone to serve ASGI only ? and Gunicorn still working to serve WSGI ? if daphne works alone to serve ASGI only, and Gunicorn works alone to serve WSGI only... that means i am running two servers in the same time . right ? i have read the document of Channels and ASGI ... but i did not find any thing talks about this thing .. and how will it act >> or if does it take everything and serve them all. if thet so, then i have to deploy my project on a server and run daphne only right? channels document. ASGI document. -
Deploying Django project in an Amazon EC2 Ubuntu instance
I have developed a Django website and hosted the application in an Amazon EC2 instance. AMI name: ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-20231207 Instance type: t2.micro I run the project following these steps: SSH into the EC2 instance from my terminal. I locate into the proper django project folder. I run this command: python3 manage.py runserver 0.0.0.0:8000 Now, following these steps, I'm able to run the project and it works fine. But when I close the cmd opened in my local PC that I used to SSH into the EC2 instance and to run the application, then the application doesn't work anymore. My aim would be to simply run the django project from my cmd once (of course after having SSH to the EC2) and then close my laptop and having the application still alive. Do you know how can I do this?