Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Passanger error while deploying via cPanel
I created an app using Django, and using this instruction wanted to deploy it, but the following error shown when loading the page. Stdout and stderr output Error: enterLve() failed: Failed to enter namespace for user *** UID 1001 errno 22 cause Invalid argument Using passenger_wsgi.py import os import sys from djangoinbi.wsgi import application sys.path.insert(0, os.path.dirname(__file__)) environ = os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoinbi.settings") wsgi.py """ WSGI config for djangoinbi project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoinbi.settings') application = get_wsgi_application() Which steps should i follow to debug that? I've tried several similar methods, but still app won't run. -
Getting Users with react and a django/websocket backend
I written code to connect to a web socket from react to a django/daphene websocket. The only problem is that when i try calling self.scope['user'] I get a lazy channel object that has no information. Here's my consumer code import json import datetime import bleach import re from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer from .models import Message clients = list() class Consumer(WebsocketConsumer): def connect(self): clients.append(self) self.room_name = self.scope['url_route']['kwargs']['room_name'] self.user = self.scope['user'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name, ) # Keeps track of online users async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'user_list', } ) self.accept() and here's my react websocket code const socket = (window.location.protocol === 'https:') ? 'wss://' : 'ws://'; const chatSocket = new WebSocket('ws://127.0.0.1:8000/ws/blap/'); let clients = [] // This gives us the websocket data from the server const useWebSockets = () => { React.useEffect(() => { chatSocket.onopen = () => { console.log('connected to chat socket'); } I think maybe i need the authenticate the websocket with a csrf token but im unclear on how to do that. logging in and out of the application to see if it does anything self.scope['user'].get_username() -
I got error when I run python manage.py makemigrations
When I run python manage.py makemigrations I got this error: (venv) ubuntu@ip-172-31-44-136:~/easy_django_repo$ python manage.py makemigrations /home/ubuntu/venv/lib/python3.10/site-packages/django/core/management/commands/makemigrations.py:143: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "Scribe3501" connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "Scribe3501" warnings.warn( No changes detected This is my database in setting.py: DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "Uninsured4645", "USER": "Scribe3501", "PASSWORD": "****", "HOST": "localhost", "PORT": '' } } I tried to reset my password with: CREATE USER ubuScribe3501t WITH PASSWORD '****'; -
Django OAuth2 authentication error: "invalid_client"
I'm trying to implement OAuth2 authentication in my Django web app using the django-oauth-toolkit package. I've registered my app on the OAuth2 provider and obtained the client ID and secret. However, when I try to get an access token using the authorization code, I'm getting the following error: {'error': 'invalid_client'} I've double-checked that the client ID and secret are correct, and that the redirect URI is set to the correct value in both the provider and the Django app. What could be causing this error, and how can I fix it? Any help would be greatly appreciated! Here is some of the relevant code : url.py for the project : from django.urls import include, path from django.conf.urls.static import static from django.conf import settings from rest_framework import routers from oauth2_provider.views import TokenView, RevokeTokenView, ApplicationRegistration router = routers.DefaultRouter() urlpatterns = [ path('', include(router.urls)), path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')), path('o/token/', TokenView.as_view(), name='token'), path('o/revoke_token/', RevokeTokenView.as_view(), name='revoke-token'), path('o/applications/register/', ApplicationRegistration.as_view(), name='register'), path('admin/', admin.site.urls), path('api/', include('vessels.urls')), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('', include('users.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py : from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-!b4#vvo$e(i*o*g61wz1@l0*6p16imxf$c2f1q4-ag==q1kril' DEBUG = True ALLOWED_HOSTS = [] CORS_ORIGIN_ALLOW_ALL = True INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # third-party … -
How can i post image to django server for use yolo algorithm
We are devoloping a project. We want to use yolo object detection algorithm in a django server and give api a computer which using python. We will post every frame of the camera to server. We want to that server give frame and run yolo or some other algorithm. How can we post frame (image). -
How to print HTML content from a Django template in a view?
Let's say I have a template called index.html with a bunch of block tags and variables and URLs. I can display it from my view using the render() function like so: def index(request): return render(request, "index.html", {...}) I would like to print the actual content that is being generated here in a normal python function. Something like this: def get_html(): html_content = some_function("index.html", {...}) # Takes in the template name and context print(html_content) Is this possible to do using Django? Thanks for any help! -
The progress bar cannot be dragged forward to skip ahead
I am using video.js as a video player, loading videos from Django static files. It can play the video, but when I try to skip ahead, it starts the video from 0 seconds.The values of videoP1 - videoP4 are retrieved from the database and have values of 1 and 0. var videos = [ { id: 1, name: "1", src: "{% static '/frontend/video/t1_1.mp4' %}", videoP1: {{ video_db.videoP1 }}, }, { id: 2, name: "2", src: "{% static 'frontend/video/t2_1.mp4' %}", videoP2: {{ video_db.videoP2 }}, }, { id: 3, name: "3", src: "{% static 'frontend/video/t3_1.mp4' %}", videoP3: {{ video_db.videoP3 }}, }, { id: 4, name: "4", src: "{% static 'frontend/video/3_2.mp4' %}", videoP4: {{ video_db.videoP4 }}, } ] var player = videojs("videoP"); function light(Cvideo) { for (let i = 0; i < videos.length; i++) { let video = videos[i]; if (videos[i].id === Cvideo) { document.getElementById("nameV").innerHTML = videos[i].name; player.src({ type: "video/mp4", src: videos[i].src }); player.load(); console.log(videos[i].id); if (!video["videoP" + (i + 1)]) { player.controlBar.progressControl.hide(); console.log(video["videoP" + (i + 1)]); player.on("timeupdate", function() { if(player.currentSrc() !== videos[i].src) { return; } var percentage = (player.currentTime() / player.duration()) * 100; document.getElementById("percentage").innerHTML = Math.round(percentage) + "%"; if (percentage === 100) { video["videoP" + (i + 1)] = 1; var … -
Running python script in subprocess
I have a celery task that's scheduled as a cronjob. But if failed I'm running a backup script which runs the tasks from command options as subprocess. This requires subprocess to 1) Activate python virtual environment in right directory 2) Use django manage.py to acess python shell 3) import and run the task I have created the code as follows process = subprocess.Popen(["source", "/application/bin/activate", "&&", "python3","/application/src/manage.py", "shell"],stdin=subprocess.PIPE,stdout=subprocess.PIPE) output1, error1 = process.communicate(b"from app.tasks import prediction") output2, error2 = process.communicate(b"prediction.run_task()") This causes django import not found error which caused by not activating python venv Each of these commands work fine running in terminal Is there any better way to do this or how can I resolve this? -
Github project structure file requierements.txt
I am learning from an article about deploying django in a container, here is the structure of the project: ├── .env.dev ├── .env.prod ├── .env.prod.db ├── .gitignore ├── app │ ├── Dockerfile │ ├── Dockerfile.prod │ ├── entrypoint.prod.sh │ ├── entrypoint.sh │ ├── hello_django │ │ ├── __init__.py │ │ ├── asgi.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── manage.py │ └── requirements.txt ├── docker-compose.prod.yml ├── docker-compose.yml └── nginx ├── Dockerfile └── nginx.conf I heard somewhere that the requierements.txt file should be in the root of the project, so that when the project is uploaded to github it is immediately visible, but here it is inside the django application, is this considered correct and why? -
Fortify issue - for sending unvalidated data to a web browser - django
sends unvalidated data to a web browser, which can result in the browser executing malicious code For this line of code i am getting security issue .can anyone help me to fix this in python (django) data = json.loads(requests.get(url, auth=self.auth).text) i tried by doing this way but still the issue is not resolved response = requests.get(url, auth=self.auth, verify=True) if response.status_code == 200: data = json.loads(response.text) -
Django form not working, data is not sent
I seem to have written everything correctly, but the queries do not go to the database get data from user, but it's not working -
How to convert Django model into DDL statement
I created a python code to create CLI tools that visualize the database schema. But I have an issue. I have tried to read the models.py in the django project and get sql statement but I don't know how to do it. I want to convert django model into sql query. -
Hashing USER_ID_FIELD payload on DJANGO REST FRAMEWORK - SIMPLE JWT
How to hashing only user id field on DJANGO REST FRAMEWORK - SIMPLE JWT? SIMPLE JWT = { 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', } -
Dev Server has been initialized using an options object that does not match the API schema. - options has an unknown property 'public'
There was an error linking django with vuejs. in my vue.config.js file: const BundleTracker = require('webpack-bundle-tracker'); module.exports = { publicPath: 'http://127.0.0.1:8080/', outputDir: './dist/', chainWebpack: config => { config.optimization.splitChunks(false) config.plugin('BundleTracker').use(BundleTracker, [{filename: './webpack-stats.json'}]) config.devServer.public('http://0.0.0.0:8080').host('0.0.0.0').port(8080).https(false).headers({"Access-Control-Allow-Origin":["\*"]}) }, pages: { index: 'src/main.js' } } This is an error on cmd. npm run serve django-vue@0.1.0 serve vue-cli-service serve INFO Starting development server... ERROR ValidationError: Invalid options object. Dev Server has been initialized using an options object that does not match the API schema. - options has an unknown property 'public'. These properties are valid: object { allowedHosts?, bonjour?, client?, compress?, devMiddleware?, headers?, historyApiFallback?, host?, hot?, http2?, https?, ipc?, liveReload?, magicHtml?, onAfterSetupMiddleware?, onBeforeSetupMiddleware?, onListening?, open?, port?, proxy?, server?, setupExitSignals?, setupMiddlewares?, static?, watchFiles?, webSocketServer? } ValidationError: Invalid options object. Dev Server has been initialized using an options object that does not match the API schema. options has an unknown property 'public'. These properties are valid: object { allowedHosts?, bonjour?, client?, compress?, devMiddleware?, headers?, historyApiFallback?, host?, hot?, http2?, https?, ipc?, liveReload?, magicHtml?, onAfterSetupMiddleware?, onBeforeSetupMiddleware?, onListening?, open?, port?, proxy?, server?, setupExitSignals?, setupMiddlewares?, static?, watchFiles?, webSocketServer? } at validate (/Users/byengju/Documents/01. Project/dataglass/django-vue/node_modules/schema-utils/dist/validate.js:115:11) at new Server (/Users/byengju/Documents/01. Project/dataglass/django-vue/node_modules/webpack-dev-server/lib/Server.js:231:5) at serve (/Users/byengju/Documents/01. Project/dataglass/django-vue/node_modules/@vue/cli-service/lib/commands/serve.js:194:20) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) How do I solve it? -
Django static file corrupted in CIFS share
I have a django site to serve images in static folder. The OS is ubuntu 18.04. I have two mounts //192.168.86.246/TestShare 7.3T 6.8T 14T 52% /media/testuser/TestShare /dev/sda1 7.3T 7.3T 13G 100% /media/testuser/TestDisk The /dev/sda1 one is a hard drive connected to the server directly through usb. The //192.168.86.246/TestShare one is on my NAS, mounted with CIFS. The mount cmd in fstab is: //192.168.86.246/TestShare /media/testuser/TestShare cifs username=xxx,password=xxx,dir_mode=0777,file_mode=0777,vers=2.0,uid=1000,gid=1000 I made two links in my Django project static folder. lrwxrwxrwx 1 testuser testuser 25 Feb 26 19:21 media2 -> /media/testuser/TestDisk/ lrwxrwxrwx 1 testuser testuser 28 Feb 26 20:03 media3 -> /media/testuser/TestShare The media2->/media/testuser/TestDisk/->/dev/sda1 one is working perfectly, all the images can be viewed through Django view in browser. But the CIFS one is weird. I can view all the images in ubuntu but when I use the Django site to load the images as static file, the browser cannot display the image. (Not permission or Not Found error). I download the static image from browser and I found that it has slight size difference compared to the original file and that caused the file corrupted. I think that it is related to the CIFS mount I did but I could not figure out … -
Django filters to generates filter for list of items
I want to filter the field vehicle_type based on comma query params {{url}}/vehicles-records-info/75d9ee1b-8a03-4697-82e7-2d96ef0a8c2d/?vehicle_type=Mixer,Lorry However when I print the query the generated query is ... AND "vehicle_type" IN (M, i, x, e, r, ,, L, o, y)) But the query should be ... AND "vehicle_type" IN ('Mixer', 'Lorry')) Here are my code Filter class VehicularAccessRecordInformationFilter(django_filters.FilterSet): vehicle_type = django_filters.CharFilter(field_name='vehicle_type', lookup_expr='in') start_timestamp = django_filters.DateTimeFilter(field_name='timestamp', lookup_expr='gte') end_timestamp = django_filters.DateTimeFilter(field_name='timestamp', lookup_expr='lte') class Meta: model = VehicleAccessRecordInformation fields = ['vehicle_type', 'timestamp'] ``` -
Django signal post_save, allow user to differentiate between different saving instance
@receiver(models.signals.post_save, sender=ModelName) def auto_trigger_update_customer(sender, instance, created, update_fields=['is_active', 'updated_at'], **kwargs) -> None: #How can I differentiate between different save so I can have different method for different save instance I tried to pass arguments in obj.save(a_argument=True) but it does not got passed to the signal -
ForeignKeyRawIdWidget, how to implement this functionality in the user model?
in django admin there is a functionality for adding, editing and deleting a record in the associated model using ForeignKeyRawIdWidget, how to implement this functionality in the user model? This is the code that is used in the django admin from django import forms from django.urls import reverse from django.utils.http import urlencode from django.core.exceptions import ValidationError from django.urls.exceptions import NoReverseMatch from django.utils.text import Truncator def url_params_from_lookup_dict(lookups): """ Convert the type of lookups specified in a ForeignKey limit_choices_to attribute to a dictionary of query parameters """ params = {} if lookups and hasattr(lookups, 'items'): for k, v in lookups.items(): if callable(v): v = v() if isinstance(v, (tuple, list)): v = ','.join(str(x) for x in v) elif isinstance(v, bool): v = ('0', '1')[v] else: v = str(v) params[k] = v return params class ForeignKeyRawIdWidget(forms.TextInput): """ A Widget for displaying ForeignKeys in the "raw_id" interface rather than in a <select> box. """ template_name = 'admin/widgets/foreign_key_raw_id.html' def __init__(self, rel, admin_site, attrs=None, using=None): self.rel = rel self.admin_site = admin_site self.db = using super().__init__(attrs) def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) rel_to = self.rel.model if rel_to in self.admin_site._registry: # The related object is registered with the same AdminSite related_url = reverse( 'admin:%s_%s_changelist' % … -
Python - Django - How do insert record into 2 tables from 1 screen with adding primary record to one table and secondary record with reference key
I am working on a screen which inserts record in to two screen one in to master table and one in to its reference table. It creates a record in to a master table and get auto generated id and use that to insert another record in to reference table. Here is my template enter image description here Here is Form enter image description here here is View enter image description here Here is the error I am seeing enter image description here -
Bootstrap5: Can I override the actual viewport so as to display content according to div size instead
I'm using Bootstrap 5 with Django - and have one component of my site that lives on its own page -with a responsive layout that stacks and moves some columns around. I want to reuse the exact same code for a smaller component that will live on the home page in a div that doesn't take 100% of the viewport. When loading the code, can I trick Bootstrap in thinking the viewport is small so that it displays the 'sm' layout? I have no idea how to do this - what I'm doing right now is basically duplicating my code like this: {% if compsize=='normal' %} <full responsive page> {% elif compsize=='compact' %} <copy/paste of only the compact version of the full page> {% endif %} It works, but it's not DRY. -
How to unite second level ManyToManyFields in Django?
I have models as follows: class Tag(models.Model): name = models.CharField(max_length=50) class Element(models.Model): tags = models.ManyToManyField('Tag') class Category(models.Model): elements = models.ManyToManyField('Element') @property def tags(self): ... # how can I do this? How can I get the union of all the tags that appear in elements of a given category? I could do something like this: def tags(self): all_tags = Tag.objects.none() for element in self.elements.all(): all_tags = all_tags | element.tags.all() return all_tags.distinct() But is there a way to do this directly at database level? -
PyQt result to webpage
Have spent a while working on a PyQt GUI with python, however, I would like to go beyond local hosting and have my UI hosted on a webpage. I understand that I can rewrite it all with flask or django but I wonder if there is any way to automatically capture a screenshot of the pyqt result and upload that to a hosted site? Or, I would appreciate any insight into other methods of web-hosting a PyQt program. TIA. Have not tried anything yet, been confused for a while. -
Django save User error not finding role based on choices
I've this models.py for user: from django.contrib.auth.models import AbstractUser from django.db.models import CharField from django.urls import reverse from django.utils.translation import gettext_lazy as _ from django.db import models from django.db.utils import IntegrityError """ Pour toute modification des roles possibles, il faut lancer dans le terminal python3 manage.py create_roles Pour voir le code correspondant, il faut aller dans le repertoire management/commands/ C est une commande cree expres pour cette fonctionnalité """ class Role(models.Model): # si changement de roles voir ci dessus le commentaire ADMIN = 'ADMIN' SELLER = 'SELLER' SALES_DIRECTOR = 'SALES_DIRECTOR' SALES_ASSISTANT = 'SALES_ASSISTANT' OPERATIONS = 'OPERATIONS' ROLE_CHOICES = [ (ADMIN, 'Administrator'), (SELLER, 'Seller'), (SALES_DIRECTOR, 'Sales Director'), (SALES_ASSISTANT, 'Sales Assistant'), (OPERATIONS, 'Operations'), ] role = models.CharField( max_length=20, choices=ROLE_CHOICES, default=SELLER, ) def __str__(self): # Here return self.role class User(AbstractUser): """ Default custom user model for Orphea. If adding fields that need to be filled at user signup, check forms.SignupForm and forms.SocialSignupForms accordingly. """ #: First and last name do not cover name patterns around the globe name = CharField(_("Name of User"), blank=True, max_length=255) first_name = None # type: ignore last_name = None # type: ignore role = models.ForeignKey(Role, on_delete=models.SET_NULL, null=True) def get_absolute_url(self): """Get url for user's detail view. Returns: str: URL for … -
Crispy form responsive input field issue
The issue I'm using Django, Bootstrap and Crispy Forms to produce input forms on a Django website. I'm having difficulty setting the responsiveness as required. At screen widths greater than 575px the input fields are the required width and perfectly centred within the container as desired. However, at widths smaller than 575px, the form looks like this, whereby the input fields take up the entire width of the container. This is undesirable and I want the input field to remain centred and modify it's width responsively as screen size decreases. What I have tried The form is composed of the classes form-select and form-control depending on the input method (dropdown and free text respectively). As such, I've tried using Bootstrap's media queries and have attempted using variations of the following code in the CSS file. @media (max-width: 575px) { .form-select { width: 90%; } } Unfortunately this doesn't seem to fix the issue. This is the entire HTML for the form: <div class="container"> <div class="row justify-content-center" style="margin-top: -100px;"> <!-- CALC LEFT --> <div class="col-md-4 mb-4 mb-md-0"> <div class="border rounded bg-light h-100"> <div class="row justify-content-center"> <!-- <h1 class="text-center"> Car Finance Calculator</h1> --> <h5 class="text-center"> Enter details for your estimate</h5> </div> <br> … -
BootstrapError, Parameter "form" should contain a valid Django Form
Views.py from django.shortcuts import redirect, render from .forms import SignupForm from django.contrib.auth import authenticate, login # Create your views here. def sign_up(request): if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data('username') password = form.cleaned_data('password1') user = authenticate(username=username, password=password) login(request, user) return redirect('/accounts/profile') else: form = SignupForm() context = {form: 'form'} return render(request, 'registration/signup.html', context) form.py from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignupForm(UserCreationForm): class Meta: model = User fields = ('username', 'email', 'password1', 'password2') signup.html {% extends "base_generic.html" %} {% load bootstrap4 %} {% block content %} <form method="post" > {% csrf_token %} {% bootstrap_form form %} <input type="submit" value="signup" class="boxed-btn3 w-100"> </form> {% endblock %} why get error: raise BootstrapError('Parameter "form" should contain a valid Django Form.' , although it works on the login.html page login.html {% extends "base_generic.html" %} {% load bootstrap4 %} {% block content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {% if next %} {% if user.is_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p> {% else %} <p>Please login to see this page.</p> {% endif %} {% …