Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is Django bulk_update slower than update?
I am trying to create and update around 30k data rows at once in the database from Django. This is taking me around 2-5 mins because all these rows have 90+ fields to be updated too, thus to reduce some time in this storage procedure I was planning to use bulk_update and bulk_create in the Django. But after the implementation I realised that this is taking a lot more time than my older process (upsert - update_or_create). Even if I remove the time taken for determining whether to create or insert (which I now realise can be directly done using an arguement in the bulk_create) it is still taking 4 times more time then my query. Based on the name of the function, I was thinking that this should be a better approach for bulk create and update of these many rows and save me sometime, but I don't know why this isn't working like that. Can anyone explain why is this happening and if there is a way to make it faster? The only reason I can come up with till now is that I have too many fields to be updated in a row, i.e., apart from 4-5 … -
Model does not exist, the problem is I get my objects from my urls.py file
I have an error in my Django 5.0 project which is Model does not exist, the cause is I get the objects from the urls.py file. Precisely I do a for loop to build my urls from my objects Model, so i get an error which is the Model does not exist, The question is : How to run migrations before the build of the urls I try to build my urls from my data's Model and i except an error which is the Model doesn't exist -
Weasyprint doesn't load the local image Django
view: from django.shortcuts import render from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status import base64 from django.template.loader import render_to_string from weasyprint import HTML from io import BytesIO from django.http import HttpResponse # Create your views here. import json from apps.pdf.models import Personas from django.conf import settings from apps.pdf.base_urls import PDF_BASE_FOLDER , PDF_CERT_SERV_FOLDER import os @api_view(["GET", "POST"]) def test(request): # Renderizar la plantilla HTML con los datos # datos = json.loads(request.body) datos = {"name": "pedro"} context={ "STATIC_URL" : settings.STATIC_URL } query = Personas.objects.filter(name=datos.get("name")).values()[0] html_template = render_to_string("pdfs_templates/Certificado.html", context) pdf_file = BytesIO() HTML(string=html_template).write_pdf(pdf_file) nombre_archivo = "example.pdf" ruta_carpeta_servidor = PDF_CERT_SERV_FOLDER ruta_completa_archivo = os.path.join(ruta_carpeta_servidor, nombre_archivo) with open(ruta_completa_archivo, "wb") as f: f.write(pdf_file.getvalue()) response = HttpResponse(content_type="application/pdf") # response["Content-Disposition"] = f'attachment; filename="{nombre_archivo}"' response.write(pdf_file.getvalue()) return response def vie(request): context={ "STATIC_URL" : settings.STATIC_URL } return render(request, 'pdfs_templates/Certificado.html', context) template : {% load static %} {% block content %} <!DOCTYPE html> <html> <head> <style type="text/css" media="all"> @page { /* size: A4 portrait; /* can use also 'landscape' for orientation */ margin: 100px 1cm 150px 1cm; @top-left { content: element(header); } @bottom-left { content: element(footer); } } header { position: running(header); /*height: 100px;*/ } table, th, td { border:1px solid black; } footer { position: running(footer); /*height: 150px;*/ … -
JWT token sent as cookie is being deleted when refreshing page (Next.js 14)
I'm using Django REST Framework as backend to handle login, if the user is verified, the service send a cookie with a JWT token. The code below works, I can see the cookie set in my browser. Login view: class Login(APIView): def post(self, request): email = request.data['email'] password = request.data['password'] user = Usuariso.objects.filter(email=email).first() ... key = os.getenv('JWT_KEY') token = jwt.encode(payload, key, algorithm='HS256') res = Response() res.set_cookie( key='jwt', value=token, httponly=True, secure=True, max_age=60*60*24, expires=60*60*24, path='/') res.data = { 'jwt': token } return res The problem occurs when I refresh the page, CSRF and JWT cookies are deleted. The code below fetch login API: app/components/loginForm.js const login = async () => { try { const response = await fetch('http://127.0.0.1:8000/api/user/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, key: 'Access-Control-Allow-Origin', credentials: 'include', body: JSON.stringify({ email: email, password: password }) }); if (response.ok) { console.log("it works"); } } catch (error) { console.log(error) } }; I have read about JWT, when setting httOnly to true, cookie can not be accessible from javascript, so I think I should not need an third party library to commit this What I have tried: Setting httpOnlny and secure = False Commenting out httpOnly and secure Setting domain as 'localhost' -
NoReverseMatch: Reverse for '...' not found. '...' is not a valid view function or pattern name - for path include name
I have this setup: # Django Project: core/urls.py def redirect_index(request): return redirect(reverse('account'), permanent=False) urlpatterns = [ path('', redirect_index, name='index'), path('account/', include('identity.urls'), name='account'), ] # Django App: identity/urls.py app_name = 'identity' def redirect_index(request): return redirect(reverse('identity:login'), permanent=False) def view_login(request): context = {"test_context": 'This is a test context'} return render(request, "common/base.html", context) urlpatterns = [ path('', redirect_index, name='index'), path('login', view_login, name='login'), ] When I visit http://localhost:8000/, I get this error: NoReverseMatch at / Reverse for 'account' not found. 'account' is not a valid view function or pattern name. What I want is this: If user goes to /, it should redirect to /account/, and from there redirect to /account/login. I know there are 2 redirects, but I'd like to have them separate so that I can set each one separately. But I get the above error. It looks like when there is an include, the name cannot be reversed. Of course, when I use reverse('identity:index') or reverse('identity:login') instead of reverse('account') in core/urls.py, it works. Is there no way I can do it the way I described earlier? -
Angular 14 / NGIX Server | White screen on Firefox and Chrome
Recently we are having issues with the deployment of our Angular App. Its angular 14, running in a ngix server. The issue arises when we do BGD (Blue green deployment, we have two prod environments, we switch between them to have 0 downtime, while one is serving the other is building the new version), our Angular app freezes on a white screen, just loading what is in the index.html (cookies popup, Analytics, etc). Sometimes works on Firefox but not on Chrome, or viceversa. Now it only fails on Firefox and I got some extra insights, looks like when tries to load runtime.js the HTTP call fails with error: NS_ERROR_CORRUPTED_CONTENT. I checked the file exists and it does, and the content is complete, seems correct. The MIME types are correct to for js files. The weirdest thing is that if switch the boolean sourceMap on the angular.json, it works again. Its not that it works being true, it just works again when we switch from true to false or viceversa. I'm running out of ideas or thing to check, and I can't find info related with this. If anyone had a similar issue or haves any insight or different thing to … -
Django, Allegro API, error with get data form endpoint
i have problems with getting data after authorization, i can get main categories, but when a want get orders from account its display it: {'errors': [{'code': 'EMPTY_USER_ID', 'message': 'User name from JWT cannot be empty', 'details': None, 'path': '/order/events', 'userMessage': 'User name from JWT cannot be empty', 'metadata': {}}]} CLIENT_ID = settings.ALLEGRO_CLIENT_ID CLIENT_SECRET = settings.ALLEGRO_CLIENT_SECRET TOKEN_URL = "https://allegro.pl.allegrosandbox.pl/auth/oauth/token" def get_access_token(request): try: data = {'grant_type': 'client_credentials'} access_token_response = requests.post(TOKEN_URL, data=data, verify=True, allow_redirects=False, auth=(CLIENT_ID, CLIENT_SECRET)) access_token_response.raise_for_status() tokens = json.loads(access_token_response.text) access_token = tokens['access_token'] `request.session['access_token'] = access_token` `return access_token` `except requests.exceptions.HTTPError as err`: `raise SystemExit(err)` def offers(request): url = 'https://api.allegro.pl.allegrosandbox.pl/order/events' headers = { 'Authorization': f'Bearer {get_access_token(request)}', 'Accept': 'application/vnd.allegro.public.v1+json', } response = requests.get(url,headers=headers).json() print(response) return render(request, 'index.html',{'events':response}) I trying asking chat, and i doing it with allegro api tutorials, but i dont know what is happened. I just want to get orders from my account and display. -
Unable to connect to cloud datastore from local legacy project based on python2.7 and django 1.4
I have a django==1.4 project (python==2.7) that I wanted to run and make some changes. I am unable to connect to cloud datastore from my local codebase. Right now, when I run the project using dev_appserver.py like: dev_appserver.py PROJECT_NAME --enable_console It runs three different servers: API server on localhost:RANDOM_PORT Module default at localhost:8080 Admin server at localhost:8000 Now I visit http://localhost:8000/console and browse interative console and then run some python script like importing User model and fetching if there is anything there or not. And there isn't, why? Because it connects to the local AppIdentityServiceStub. And obviously there isn't any data unless I create some. Now I want to connect this codebase to my cloud datastore and I have tried different implementations that are already on stackoverflow and other platforms. One of them is setting environment variable GOOGLE_APPLICATION_CREDENTIALS to a keyfile.json that service account provides. I have the keyfile.json and I have set it to env variable but still I get connected to local datastore which has no data. Let me know if I am running this project wrong? or is there any other way to connect to cloud datastore from my local? Also, one more thing, when I do … -
Django django.db.utils.IntegrityError .................error
django.db.utils.IntegrityError: The row in table 'students_student' with primary key '2' has an invalid foreign key: students_student.Classes_id contains a value '0' that does not have a corresponding value in students_classes.id. (venv) PS C:\Student Management System> making fields default but still facing error -
Django default User Login: Can't login even with correct password
I am using Django's default User and authentication to enable login functionality. My username and passwords are correct; I've reviewed them, and I can login to the admin. But it won't work in my app, through the login page. There must be something basic I'm overlooking but I"ve been over my code several times. Views.py: from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.views import View from django.contrib import messages from django.urls import reverse_lazy from .forms import EntryForm, CreateUserForm, LoginForm from .models import Entry from django.views.generic.edit import DeleteView, FormView # Authentication models and functions from django.contrib.auth.models import auth from django.contrib.auth import authenticate, login, logout #this is to ensure that even after you have your login setup, a user can't just manually type in the URL from django.contrib.auth.mixins import LoginRequiredMixin # Create your views here. class EntryView(LoginRequiredMixin, View): login_url = 'login' def get(self, request): logged_in_user = request.user.id entries = Entry.objects.filter(trader_id=logged_in_user).order_by("entered_date") form = EntryForm() return render(request, "entries.html", {"form":form, "entries":entries}) def post(self, request): form = EntryForm(request.POST, request.FILES) #must add request.FILES for uploads print(request.FILES) if form.is_valid(): form.save() messages.success(request, "Entry created!") return redirect("/") else: messages.error(request, "Please correct the errors below.") return render(request, "entries.html", {"form":form}) def SingleEntryView(request, pk): entry = Entry.objects.get(pk=pk) if … -
"Patients model in Django does not recognize the 'user' attribute when registering a new user."
I am practicing login, registration and logout in Django. I want to create a patient through registration and have the registration information saved in Patients, which is in my models.py. When I perform a registration I get the following error in terminal: raise self.RelatedObjectDoesNotExist( pacientes.models.Pacientes.user.RelatedObjectDoesNotExist: Pacientes has no user. Here is the code of my exercise. models.py from django.db import models from django.contrib.auth.models import User class Pacientes(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) nombre = models.CharField(max_length=50) apellido = models.CharField(max_length=50) fecha_nacimiento = models.DateField() genero = models.CharField(max_length=1) address = models.CharField(max_length=50) email = models.EmailField() phone = models.CharField(max_length=50) picture_profile = models.ImageField(upload_to='profile_images', blank=True) def __str__(self): return self.user.username + ' ' + self.user.last_name forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from .models import Pacientes class PacientesForm(forms.ModelForm): password1 = forms.CharField(label='Contraseña', widget=forms.PasswordInput) password2 = forms.CharField(label='Confirmar contraseña', widget=forms.PasswordInput) class Meta: model = Pacientes fields = ['nombre', 'apellido', 'fecha_nacimiento', 'genero', 'address', 'email', 'phone', 'picture_profile', 'password1', 'password2'] def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Las contraseñas no coinciden") return password2 def save(self, commit=True): paciente = super().save(commit=False) user = paciente.user user.set_password(self.cleaned_data["password1"]) # Guarda la contraseña en el objeto User if commit: user.save() paciente.save() return paciente class EmailAuthenticationForm(AuthenticationForm): … -
how to correctly derive a function book.user_max2() to make xlsx export fast
When exporting .xlsx, the book.user_max2() function increases the load and clogs up the RAM. If you just take book.price from the model, there is no such problem. But I need the price to change when unloaded, so I wrote a user_max2() function in the Products model. Everything is a problem in the user_max2() function. Without it, everything is unloaded quickly and there are no memory leaks. Please help, maybe someone has already encountered this. model Products class Product(models.Model): STATUS_CHOICES = ( (0, 'Не опубликовано'), (1, 'Опубликовано'), ) STATUS_NEW = ( (0, 'Нет'), (1, 'Да'), ) id_p = models.BigIntegerField(primary_key=True, db_index=True, unique=True, verbose_name='ID продукта') artikul = models.CharField(max_length=200, db_index=True, blank=True, verbose_name='Артикул') brend = models.CharField(max_length=200, db_index=True, blank=True, verbose_name='Бренд для поиска') analog = models.CharField(max_length=500, blank=True, verbose_name='Аналоги артикула') category = models.ManyToManyField(Category, blank=True, related_name='categ', verbose_name='Категория') brand = models.ForeignKey(Brand, on_delete=models.PROTECT, verbose_name='Бренд') product_sklad = models.ForeignKey(Sklad, on_delete=models.CASCADE, default=1, verbose_name='ID поставщика') product_time = models.IntegerField(default=0, verbose_name='Срок доставки ( дн.)') name = models.CharField(max_length=200, blank=True, verbose_name='Название продукции') image_a = models.ImageField(upload_to=get_path_upload_image_a, verbose_name='Фото A', blank=True, null=True, help_text="Фото продукта автоматитчески сохраняется под ID продукта") image_b = models.ImageField(upload_to=get_path_upload_image_b, verbose_name='Фото B', blank=True, null=True, help_text="Фото продукта автоматитчески сохраняется под ID продукта") image_c = models.ImageField(upload_to=get_path_upload_image_c, verbose_name='Фото С', blank=True, null=True, help_text="Фото продукта автоматитчески сохраняется под ID продукта") description = models.TextField(blank=True, verbose_name='Описание') price … -
How to force nginx to see my static files?
I'm trying to output a project to NGINX. I ask good people to help. I've been suffering for 2 days. First I ran: python manage.py collectstatic The static folder has been created! Here is the path to my manage.py: /home/ubuntu/ubuntu/project/Pet/Django/bewise/src Here are my static settings in settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [] Here are my NGINX settings: `server { listen 80; server_name 192.168.16.153; location /static/ { root /home/ubuntu/ubuntu/project/Pet/Django/bewise/src/static/; } location / { proxy_pass http://192.168.16.153:8000; } } And here is my gunicorn configuration:command = '/home/ubuntu/ubuntu/project/venvs/bewise/bin/gunicorn' pythonpath = '/home/ubuntu/ubuntu/project/Pet/Django/bewise/src' bind = '192.168.16.153:8000' workers = 3` I run gunicorn: gunicorn -c config.py config.wsgi Everything works fine, but I don't receive static files. When I try to go to 192.168.16.153/static/img/home.png I get err403. And I don't receive css files either. -
Error configuring django channels to connect to htmx
I have a problem when trying to design a realtime messaging function using channels daphne and htmx. I added channels, django_htmx to INSTALLED_APPS in settings.py, This is asgi.py file: `import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from channels.auth import AuthMiddlewareStack os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'server.settings') django_asgi_app = get_asgi_application() from Chat import routing application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(routing.websocket_urlpatterns)) ) }) ` This is routing.py file `import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from channels.auth import AuthMiddlewareStack os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'server.settings') django_asgi_app = get_asgi_application() from Chat import routing application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(routing.websocket_urlpatterns)) ) })` This is consumers.py file: `import json from channels.generic.websocket import WebsocketConsumer from .models import * from django.shortcuts import get_object_or_404 class ChatConsumer(WebsocketConsumer): def connect(self): self.user = self.scope['user'] self.partner_name = self.scope['url_route']['kwargs']['username'] self.partner = get_object_or_404(User, username=self.partner_name) self.accept() def disconnect(self, code): pass def receive(self, text_data): text_data_json = json.loads(text_data) content = text_data_json['content'] msg = Message.objects.create( sender=self.user, receiver=self.partner, content=content ) ` This is HTMX file: <form hx-ext="ws" ws-connect="ws/chat/{{partner.username}}" ws-send="send:click" hx-swap="outerHTML" _="on htmx:wsAfterSend reset() me"> {% csrf_token %} <div class="flex-grow-0 py-3 px-4 border-top" style="top: 0;"> <div class="input-group"> <input type="text" class="form-control" placeholder="Type your message" name="content" /> <button type="submit" class="btn … -
Websocket Connection Failed Django javascript
I am trying to connect to my websocket from the frontend in javascript const url = 'wss://chatapprender.onrender.com/${person_id}/'; I am using django channels for backend ASGI_urlpatterns = [ path("websocket/\<int:id\>/", consumers.ChatConsumer.as_asgi()) ] when the following line is executed it gives this error in the console WebSocket connection to 'wss://chatapprender.onrender.com/3/' failed: connectToWebsocket @ script.js:71 (anonymous) @ script.js:190 it works on my local 127.0.01:8000 server of django with this url ws://127.0.0.1:8000/websocket/${person_id} but when i deploy it it fails to connect INSTALLED_APPS = [ 'channels', 'daphne', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'chat', 'accounts', ] WSGI_APPLICATION = 'mychatproject.wsgi.application' ASGI_APPLICATION = 'mychatproject.asgi.application' **routing.py** from django.urls import path from . import consumers ASGI_urlpatterns = [ path("websocket/<int:id>/", consumers.ChatConsumer.as_asgi()) ] **asgi.py** import os from chat import routing from channels.auth import AuthMiddlewareStack from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mychatproject.settings') application = ProtocolTypeRouter({ 'http':get_asgi_application(), 'websocket':AuthMiddlewareStack(URLRouter(routing.ASGI_urlpatterns)) }) **consumers.py** class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() try: user_channel = UserChannel.objects.get(user=self.scope.get('user')) user_channel.channel_name=self.channel_name user_channel.save() except: user_channel=UserChannel.objects.create(user=self.scope.get('user'), channel_name=self.channel_name) user_channel.save() self.person_id=self.scope.get("url_route").get("kwargs").get("id") -
exporting data from sqlite database to postgress database in django
i wanted to transform my data from sqlite database onto posgres database in django. first of all i write the command: python -Xutf8 .\manage.py dumpdata --indent=4 --output=data.json to exporting data (in utf-8 encode) in a json file. everything was good and data exported properly, but when i want to import data in postgres (after configuration in settings.py) so i used python .\manage.py loaddata data.json and got this error: django.db.utils.IntegrityError: Problem installing fixture 'C:\Users\Bardia\Desktop\webapp\data.json': Could not load contenttypes.ContentType(pk=7): duplicate key value violates unique constraint "django_content_type_app_label_model_76bd3d3b_uniq" DETAIL: Key (app_label, model)=(blog, post) already exists. can anyone help my in this situation? thanks a lot loading data in new postgres database in django -
Is the __unicode__ method still required for a dynamic Django model? [duplicate]
I found code in our codebase that defines a __unicode__ dunder method for a dynamically created Django model. We are using Python 3.11 and Django 4.2. Is the __unicode__ method still required? Here is the code snippet: from typing import Type from django.db import models MODEL_NAME = "MyReport" MODEL_FIELDS = ["field1", "field2"] type( MODEL_NAME, (models.Model,), { "__module__": __name__, "__unicode__": lambda _: MODEL_NAME, **{ field_name: models.Field() for field_name in MODEL_FIELDS }, }, ) I've read __str__ versus __unicode__, but the question dates back to 2009 and the answers are mostly outdated. -
Captcha solving using Python
I am trying to extract values from below CAPTCHA image but my code is giving me output as none. I am getting empty string as output. I have tried using below code. While it was working fine with below image. def read_captcha(): ptes.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' try: img = cv2.imread('ss.png', 0) img = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1] imagetext = ptes.image_to_string(img) except TypeError: imagetext="a b" l = imagetext.split() s = "" for i in range(len(l)): s += l[i] if len(s)>0: return s else: return ""` -
Add button for django formset
I'm starting to use Django 5 and I'm building a web project to organize a Secret Santa gift exchange. My problem is that when using formsets, they are not dynamic, so I can't create a variable number of forms at the user's request. I have this form: class ParticipanteForm(forms.ModelForm): class Meta: model = Participante fields = ['nombre', 'email'] ParticipanteFormSet = formset_factory(ParticipanteForm) This model: class Participante(models.Model): sorteo = models.ForeignKey(Sorteo, related_name='participantes', on_delete=models.CASCADE) nombre = models.CharField(max_length=100) email = models.EmailField() And this view where I render the forms and save the data: def crear_sorteo(request): sorteo_form = SorteoForm(request.POST or None) ParticipanteFormSet = formset_factory(ParticipanteForm, extra=3) participante_formset = ParticipanteFormSet(request.POST or None) context = { 'sorteo_form': sorteo_form, 'participante_formset': participante_formset, } if request.method == 'POST': if sorteo_form.is_valid(): sorteo = sorteo_form.save() # Save the draw first if participante_formset.is_valid(): for participante_form in participante_formset: participante = participante_form.save(commit=False) participante.sorteo = sorteo # Assign the draw to the participant participante.save() return render(request, 'sorteo_realizado.html') return render(request, 'crear_sorteo.html', context) As you can see, ParticipanteFormSet = formset_factory(ParticipanteForm, extra=3) depending on the number of extra you specify, that will be the number of forms that will be created. But I would like in the template: <body> <form action="" method="post"> {% csrf_token %} {{ sorteo_form }} {{ participante_formset.management_data }} … -
delete instance of factory boy from another one
I have two FactoryBoy and I tried to delete the first one from the second, What I want to accomplish is when I delete a ShareLinksFactory instance, the associated WebShareFileFactoryBoy and its corresponding file should also be deleted. Below is the class ShareLinksFactory: class ShareLinksFactory(factory.django.DjangoModelFactory): class Meta: model = ShareLinks id = factory.LazyFunction(create_id) web_share_file_folder = factory.SubFactory(WebShareFileFactoryBoy) create_user = UuidCifsUsers.objects.get(cifs_user='user_test').id limit_datetime = factory.LazyFunction(lambda: timezone.now() + timedelta(days=30)) created_by_factory = True WebshareFileFactoryBoy class WebShareFileFactoryBoy(factory.django.DjangoModelFactory): class Meta: model = WebShareFileFolders django_get_or_create = ('inode',) name = factory.Faker('file_name', extension='txt') path = factory.Faker('name') inode = factory.Faker('random_number') is_dir = False @factory.post_generation def create_file_on_disk(self, create, extracted, **kwargs): self.name = self.name + str(uuid.uuid4())[:6] # these permit to make a unique name for the file automatic_folder_path = os.path.join(NAS_PATH, 'Share/automatic/') Path(automatic_folder_path).mkdir(parents=True, exist_ok=True) full_path = os.path.join(automatic_folder_path, str(self.name)) file_size_mo = kwargs.pop('file_size_mo', None) with open(full_path, 'w') as file: file.write( f'Name: {self.name} \n' f'Is a folder: {self.is_dir} \n' f'make with love: True \n' f'where: {full_path}' ) if file_size_mo: file_size = file_size_mo * 1024 * 1024 file.seek(file_size - 1) file.write('\0') self.inode = os.stat(full_path).st_ino self.path = 'Share/automatic/' + str(self.name) self.save() std, err, code = popen_wrapper([ 'sudo', '/set_webshare_extattr.sh', str(self.id), full_path ]) I try to overide the delete function from the class but I get an error django.core.exceptions.FieldError: Invalid field … -
In Django, why is my JSONFormField generating a style 'display: none'?
I am using django_jsonform (2.22.0) with django (4.2.11) to edit a configuration file written in JSON. I have verified the schema is correct and I can use it with the playground (https://bhch.github.io/react-json-form/playground/). When I egnerate the form, I print the form output and it has 'style "display: none"' emedded in it. from pathlib import Path from django import forms from django_jsonform.forms.fields import JSONFormField from testsite import settings class ConfigurationForm(forms.Form): configuration = JSONFormField(schema=Path(settings.CONFIG_ROOT) / 'config2.schema.json') def configuration(request: Request): if request.method == "POST": form = ConfigurationForm(request.POST) if form.is_valid(): return HttpResponseRedirect("/thanks/") else: with open(Path(settings.CONFIG_ROOT) / 'config.json') as configFile: data = json.load(configFile) form = ConfigurationForm(initial={'configuration': data}) print(f'form data = {form}') return render(request, "admin/preferences/preferences.html", context={"form": form}) The print(f'form data = {form}') statment produces this: form data = <tr> <th><label for="id_configuration">Configuration:</label></th> <td> <div data-django-jsonform-container="true" class="django-jsonform-container"></div> <textarea cols="40" id="id_configuration" name="configuration" rows="10" style="display: none;" data-django-jsonform="{&quot;data&quot;: &quot;{ <!-- sensitive data removed --> }&quot;, &quot;schema&quot;: {}, &quot;fileHandler&quot;: &quot;&quot;, &quot;fileHandlerArgs&quot;: {&quot;field_name&quot;: &quot;configuration&quot;, &quot;model_name&quot;: &quot;&quot;}, &quot;errorMap&quot;: {}, &quot;validateOnSubmit&quot;: false, &quot;readonly&quot;: false}"></textarea> </td> </tr> So what am I doing wrong? -
Django Templates - How can I have correct Root vs App Lookup
How can I have view load the templates from the corresponding app (root vs child)? Here's the full structure: Create django project - universe Created an app - let's call it earth. Created a (container) template for / -> universe/universe/templates/main.html Created a (container) template for /earth -> universe/earth/templates/main.html Created a (content) template for / and /earth at universe/universe/templates/index.html and universe/earth/templates/index.html respectively. In universe/universe/views.py, I have: from django.shortcuts import render def index(request): context = {} return render(request, 'index.html', context) In universe/earth/views.py, I have the same: from django.shortcuts import render def index(request): context = {} return render(request, 'index.html', context) When I run this, I get an error TemplateDoesNotExist at /. Why are templates not found? If I update universe/universe/settings.py TEMPLATES = [ ... 'DIRS': [ BASE_DIR / 'universe/templates' ] ] only the universe templates are picked up. How can I ensure that when I refer to the correct index.html based on the app? -
Logged out redirection
If I press Enter using http://127.0.0.1:8000/dashboard/ after logged out I am redirecting to http://127.0.0.1:8000/login/?next=/dashboard/. How can I redirect to http://127.0.0.1:8000/login/ after logged out by press Enter ? -
Limit the dropdown to logged in user for a table field
My tables are: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT, primary_key=True, ) address_line_1 = models.CharField(max_length=200,blank=True) class ProfileCar(models.Model): profile = models.ForeignKey(Profile,on_delete=models.CASCADE) car_model = models.ForeignKey(CarModel,on_delete=models.CASCADE) class AvailableRide(models.Model): profilecar = models.ForeignKey(ProfileCar,on_delete=models.CASCADE) ride_route = models.ForeignKey(Route,on_delete=models.CASCADE) ride_datetime = models.DateTimeField(default=timezone.now) In AvailableRide table, when running it, it shows the complete list of profilecar values, meaning all the users get listed. I want to limit this list to only logged in user. The list needs to be limited to logged in user only, who has onetoone profile record. -
Django: Generate multiple random time
I have Schedule class which has dates, routes and time. I have a problem generating random time. I saw this, (Create random time stamp list in python), but it only generate random time which only has minutes gap each. This is how I did mine, which is just very simple: no_of_route = int(request.POST.get('no_of_route')) time = random.sample(range(1, 24), no_of_route) But this one is just a whole number, I wanted to have results like 9:30, 1:45, and so on. There is no need of min and max time. Is this possible? I'm new to this, so I'm not sure how to do it exactly. Thank you for your help.