Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 %} {% … -
Django debug toolbar giving error about static file location
For the entire time I've been working on this project, I have had no problems with django debug toolbar, but suddenly, when I have it enabled, it gives me the error: The joined path (/images/user/blank-avatar.png) is located outside of the base path component (/opt/project/projectfiles/static). When DJDT is disabled, I get absolutely no errors. I'm not sure why this happens. When I go into the shell and check what django.conf.settings.STATIC_ROOT is set to, it comes back with /app/staticfiles, which is correct. I have no idea where this /opt/project/projectfiles/static is coming from. When I do a search through the entire project, there is no place where /opt, or opt/ shows up. This project is in a docker container, and the project is completely stored in the /app directory. I'm not married to DJDT, since I so rarely use it, but I am concerned that this shows something I might be doing wrong. Before anyone asks, this is not a media file. It legitimately is in the static folder at /app/projectfiles/static/images/user/blank-avatar.jpg. In production, it is stored on a digitalocean spaces container. Apparently it is the {{ staticfile.real_path }} section in the following template code that finally raises the error: </ol> {% else %} … -
How can I allow users to upload multiple images and files in django?
I want to create functionality like facebook/twitter for creating a post. I have a url smth like example.com/username/posts/create with the form related to the post model. As you probably know, there is no ability in vanilla ImageField & FileField to upload multiple items, as well as no decent editor for drag&drop like things. Drag&Drop isn't a crucial feature, but I really want to handle with a twitter/facebook like editor somehow. With all it's convenient buttons for photo/video/file. I saw there is a bunch of custom editors like DJANGO-CKEDITOR and etc., but I don't understand how it suppose to work anyway with one image/file field. Maybe, somebody was facing the problem? Attach my form and model in case it will help: Models.py class Post(models.Model): title = models.CharField(max_length=200, null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) images = models.ImageField(null=True, blank=True, upload_to="posts/images") body = models.TextField(max_length=255) post_date = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) likes = models.ManyToManyField(User, through='UserPostRel', related_name='likes') forms.py class PostCreationForm(ModelForm): class Meta: model = Post fields = [ 'title', 'body', 'images', ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['title'].label = "Title" self.fields['body'].label = "Body" self.fields['images '].label = "images" -
display form errors. Django
I have sign up form. I don't know how I can display errors. I'm trying it from models.py, I have unique errors, but they don't display, I also have custom validation in forms.py, where I'm checking if passwords match and some rules for passwords and it doesn't work either. So, question is, how can I display validation errors? models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, AbstractUser # Create your models here. class User(AbstractUser): username = models.CharField(max_length=100, unique=True, error_messages={ 'unique': "This username has already been registered."}) password = models.CharField(max_length=200, unique=False) email = models.EmailField(unique=True, error_messages={ 'unique': "This email has already been registered."}) phoneNumber = models.CharField(max_length=12, unique=True, error_messages={ 'unique': "This phone number has already been registered."}) first_name = None last_name = None forms.py from django.forms import ModelForm, ValidationError from django import forms from .models import User class LogInForm(forms.Form): username = forms.CharField(widget=forms.TextInput( attrs={'placeholder': 'Username', 'class': 'form-input'}), required=True) password = forms.CharField(widget=forms.PasswordInput( attrs={'placeholder': 'Password', 'class': 'form-input'}), required=True, min_length=8) class SignUpForm(ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput( attrs={"placeholder": "Password"}), min_length=8, required=True) password2 = forms.CharField( label='Confirm password', widget=forms.PasswordInput(attrs={"placeholder": "Confirm password"}), min_length=8, required=True) error_css_class = 'message-error' error_messages = { 'password_mismatch': 'Passwords must match.', } class Meta: model = User fields = ('username', 'email', 'phoneNumber', 'password') widgets = { "username": … -
fetch Django model in many to many relationship my other model
I am trying to figure out how many objects of a djanog model have a many to many relationship with a spicific objects of another model. my modles.py is from django.db import models from django.contrib.auth.models import User class Post(models.Model): post_title = models.CharField(max_length=200) post_body = models.CharField(max_length=1000) pub_date = models.DateTimeField('date published') by = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.post_title def get_id(self): return self.id def get_body(self): return self.post_body def get_date(self): return self.pub_date def get_name(self): return self.post_title def get_author(self): return self.by def get_likes(self): return type(self).likes.all() class Like(models.Model): associated_post = models.ManyToManyField(Post) associated_user = models.ManyToManyField(User) and my view is from django.views import generic from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.utils import timezone from .models import Post def index(request): posts = [] for post in Post.objects.order_by('-pub_date'): posts.append({'title': post.get_name(), 'author_id': str(post.get_author()), 'created': post.get_date(), 'body': post.get_body(), 'id': post.get_id()}) print(post.get_likes()) return render(request, 'home.html', {'posts': posts}) Basically the function post.get_likes needs to return the number of likes that have a realtionship with the post. I v'e read the django documentation on this topic, but I just can't quite figure out what is actually going on in the example code. -
Parallel execution of for loop in django functions
I have a function and this function goes to 10 different sites and retrieves data with a GET request. This is how I do it inside the for loop. WebSite.objects.all(); The database that I saved in a different area on django. web_site = WebSite.objects.all(): for web in web_site: get information from web I want to run this for loop in parallel. How can I achieve this, is there an easy way? I can also implement it directly in func code or try a feature of django/celery. -
Debug dockerized Django application running Uvicorn - ASGI on VSCode?
I'm trying to run debugpy in attach mode to debug on VScode a dockerized Django app. With the following configuration on launch.json { "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "attach", "pathMappings": [{ "localRoot": "${workspaceFolder}", "remoteRoot": "/app" }], "port": 9999, "host": "127.0.0.1" } ] } I've been able to attach correctly to it adding the following section on the manage.py file: #!/usr/bin/env python import os import sys from pathlib import Path if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") # debugpy configuration from django.conf import settings if settings.DEBUG: if os.environ.get("RUN_MAIN") or os.environ.get("WERKZEUG_RUN_MAIN"): import debugpy debugpy.listen(("0.0.0.0", 9999)) ... The Django Dockerfile is launching the script: #!/bin/bash set -o errexit set -o pipefail set -o nounset python manage.py migrate exec python manage.py runserver 0.0.0.0:8000 And I'm exposing the ports 8000 and 9999 running the docker image. So far so good. What I'm trying to do now is enable the same support for the ASGI application running under uvicorn. #!/bin/bash set -o errexit set -o pipefail set -o nounset python manage.py migrate exec uvicorn config.asgi:application --host 0.0.0.0 --reload --reload-include '*.html' asgi.py """ ASGI config for Suite-Backend project. It exposes the ASGI callable as a module-level variable named ``application``. For more information … -
How do I create a Django model for a chatroom in python?
Just letting you all know that I am very inexperienced with web development and so I decided to start a project in which I am making an application similar to Discord in which people can go to chat rooms and voice chat each other. From research, I decided to use Django (now with sockets). I started my project making the models first since that is the easiest for me to understand now. I was easily able to create a User Profile like so: from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver import django class UserProfile(models.Model): user_name = models.OneToOneField(User, related_name='user profile', on_delete=models.CASCADE) photo = models.ImageField(null=True, blank=True, default='random_14-512.webp') status = models.CharField(default='This is my status', max_length=255) is_online = models.BooleanField(default=False) objects = models.Manager() @receiver(post_save, sender=User) def create_user_profile(self, sender, instance, created, *args, **kwargs): if (created): UserProfile.objects.create(user_id=instance.pk) class ChatRoom(models.Model): pass but I have no idea how I can create a model for the chatroom. I can give it a name easily and such, but if I use models.CharField, the first parameter is the user. If anyone can point me in the right direction on how I can create the model for the chat room, that would be much …