Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
upload image to db using image url (DJANGO)
Im new to django and im trying to upload a specific image from html form to the django database using its url. I found multiple ways to do so, but they all use the "browse" button and makes the user manually choose which image to upload (see image below). Is there a way to automatically look for and upload a specific image thats already in my device using image url? -
Stop the main thread until all task done in a ThreadPoolExecutor - Python DJANGO
I've some rather heavy stored procedures in a view and I wanted to use threads to execute those queries in parallel but I don't know how to stop the main thread until those queries have finished. My code: from concurrent.futures import ThreadPoolExecutor def resultados(request): executor = ThreadPoolExecutor() context = {} executor.submit(resultados_proceso, regiones, territorios, canales, marcas, periodos) executor.submit(resultadosGrafica_proceso,regiones, territorios, canales, marcas, periodos) executor.submit(get_volumen_ejecucion_clientes_iniciativa, 106) executor.submit(get_volumenAP_xmarca, ['M']) return render(request, 'resultados.html', context) def resultados_proceso(context, regiones, territorios, canales, marcas, periodos): context['resultados'] = getResultados(regiones, territorios, canales, marcas, periodos) def resultadosGrafica_proceso(context, regiones, territorios, canales, marcas, periodos): context['grafica'] = getResultadosGrafica(regiones, territorios, canales, marcas, periodos) -
Readonly flelds in Wagtail admin
We're using Wagtail 4.1 and are seeking a way to make some fields in the admin non-editable (read-only). Normal Django techniques like setting widget.attrs['readonly'] = True on the form field don't work in Wagtail for most field types. I think this is because the Wagtail admin replaces all the vanilla <input> elements with dynamically generated javascript-powered fields that look great, but don't respect a form field's "readonly" attribute or any other changes you might make to the underlying <input>. As far as I can tell, Wagtail does not provide any built-in mechanism for making admin fields read-only. Maybe I need to write my own custom javascript to override behavior in the Wagtail form? Any help would be greatly appreciated. -
Django for Everybody CSS Autograder assignment stuck on trying to make replica page
I have been trying to complete this assignment for a total of 4 hours and I am no longer making progress and it is holding up my advancement in the course. I have completed the majority of it but I am stuck of the DJ4E sign. If you use the link below you will see what it is meant to look like. Specifics I am stuck on: How to remove the purple from from DJ4E text ( it is a link ) so now purple since the link has been visited. DJ4E should be just above the boxes ( see link for pic) Here is the link to the assignment: https://www.dj4e.com/assn/css/index.php HTML Code( Not meant to change): <!DOCTYPE html> <html> <head> <title>Blocks</title> <!-- Do not change this file - add your CSS styling rules to the blocks.css file included below --> <link type="text/css" rel="stylesheet" href="blocks.css"> </head> <body> <div id="one"> Turns out you have a really fun time if you go to work every day and focus on being silly and funny and happy! - Hannah Murray </div> <div id="two"> All you need in this life is ignorance and confidence, and then success is sure. - Mark Twain </div> <div id="three"> … -
django-rest-framework id field in user serializer
I have project with api on drf My User Model class User(AbstractUser): first_name = models.CharField( 'Имя', max_length=150, ) last_name = models.CharField( 'Фамилия', max_length=150 ) image = ResizedImageField(size=[255, 260], upload_to='image/', quality=51) role = models.CharField( 'Роль в проекте', max_length=200, null=True, blank=True) description = models.TextField( 'Описание', blank=True, null=True ) class Meta: verbose_name = 'Пользователь' verbose_name_plural = 'Пользователи' def __str__(self): return self.first_name serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'first_name', 'last_name', 'image', 'role', 'description') read_only_fields = ['id'] views.py class UserViewSet(GetListRetrieveMixin): queryset = User.objects.all() serializer_class = UserSerializer pagination_class = None filter_backends = (SearchFilter,) search_fields = ('id',) filterset_fields = ['id', ] filter_fields = ('id',) Now i have this json without id field [ { "first_name": "testname", "last_name": "testsurname", "image": "http://example.com/media/image/test.jpeg", "role": "test role", "description": "test desc" }, but i need this [ { "id": "1" "first_name": "testname", "last_name": "testsurname", "image": "http://example.com/media/image/test.jpeg", "role": "test role", "description": "test desc" }, What i tried to do: Add id in serializer Class like that: class FooSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField(read_only=True) class Meta: model = Foo fields = 'all' But i cant resolve my problem -
reactjs app gmail login issue when deploy on django server
import React, { useState, useEffect } from 'react' import {googleLogout, useGoogleLogin } from '@react-oauth/google'; mport {useNavigate} from 'react-router-dom'; import { Link as ReactLink } from "react-router-dom"; import axios from 'axios'; import './App.css'; function Homepage(){ const navigate = useNavigate(); const [ user, setUser ] = useState([]); const [ profile, setProfile ] = useState([]); const login = useGoogleLogin({ onSuccess: (codeResponse) => {setUser(codeResponse); navigate('/instructions');}, onError: (error) => {console.log('Login Failed:', error);} }); useEffect( () => { console.log('user:: ',user); if (user.length != 0) { axios .get(`https://www.googleapis.com/oauth2/v1/userinfo?access_token=${user.access_token}`, { headers: { Authorization: `Bearer ${user.access_token}`, Accept: 'application/json' } }) .then((res) => { console.log('result:: ',res.data) setProfile(res.data); }) .catch((err) => console.log('err',err)); } }, [ user ] ); return ( <div className="homepage"> <div id="customBtn" className="customGPlusSignIn" onClick={() => login()}> </div> ) } export default Homepage; ** when i am deploying this reactjs webapp on tomcat local server it is working fine and routing to instructions page but if i am deploying it on django server (generating build file and integrating that with django backend project)then getting issues like page is appearing but when i click on login button it opens popup for select account and then it goes to same login page, no error is coming on console as well as on … -
Multiple Django Projects on Apache Server with mod_wsgi is trying to load wrong project libraries?
I'm trying to run multiple Django projects on one server. The server is Windows and I am using mod_wsgi with Apache. Normally, each project lives on it's own server and everything works great - but for dev/staging purposes I am trying to just serve them all from the same server (I've done this successfully with other groups of projects on another server, but they were Flask applications) My structure looks similar to this: ProjectA (this project contains the authentication / login / logout) - appa1 (shared templates / static files) - appa2 ProjectB - appa1 (shared templates / static files) - appb1 - appb2 ProjectC - appa1 (shared templates / static files) - appc1 - appc2 My VirtualHost setup is pretty straightforward: <VirtualHost dev.projecta.mydomain.com:80> ServerName dev.projecta.mydomain.com Redirect / https://dev.projecta.mydomain.com </VirtualHost> <VirtualHost dev.projecta.mydomain.com:443> ServerName dev.projecta.mydomain.com WSGIScriptAlias / "C:/projecta/projecta.wsgi" CustomLog "logs/projecta_access.log" common ErrorLog "logs/projecta_error.log" SSLEngine on SSLCertificateFile "C:/path/to/projecta_cert/cert.cer" SSLCertificateKeyFile "C:/path/to/projecta_cert/project.key" <Directory C:\projecta> Require all granted </Directory> </VirtualHost> <VirtualHost dev.projectb.mydomain.com:80> ServerName dev.projectb.mydomain.com Redirect / https://dev.projectb.mydomain.com </VirtualHost> <VirtualHost dev.projectb.mydomain.com:443> ServerName dev.projectb.mydomain.com WSGIScriptAlias / "C:/projectb/projectb.wsgi" CustomLog "logs/projectb_access.log" common ErrorLog "logs/projectb_error.log" SSLEngine on SSLCertificateFile "C:/path/to/projectb_cert/cert.cer" SSLCertificateKeyFile "C:/path/to/projectb_cert/project.key" <Directory C:\projectb> Require all granted </Directory> </VirtualHost> <VirtualHost dev.projectc.mydomain.com:80> ServerName dev.projectc.mydomain.com Redirect / https://dev.projectc.mydomain.com </VirtualHost> <VirtualHost dev.projectc.mydomain.com:443> ServerName dev.projectc.mydomain.com … -
Define how to print param
i wont to save in a db a int data, and print a string when i call it. i have a model like this: class Flats(models.Model): title = models.CharField(max_length=50, unique=True, verbose_name="Titolo") description = models.TextField(blank=True, verbose_name="Descrizione") floor = models.SmallIntegerField(blank=True, default=0, verbose_name="N° piano") i wont that when i call floor return not a number but a string. how it is possible?? -
Running a celery task outside the django framework
I have a django/celery application that is working fine. In normal operations tasks get created and inserted into the worker queues as expected. I am trying to create a separate python script that will be run manually, that is attempting to insert a task into the worker queue... and it is not working. The test function is simple: @shared_task() def testtask(num=100, tag=0): for i in range(num): print_log("in testtask {0} {1}".format(i, tag)) time.sleep(1) return From the python3 prompt, I do the following: >>> os.environ.setdefault("DJANGO_SETTINGS_MODULE", "raxakprotect.settings.dev") >>> import django >>> django.setup() >>> from test import testtask # test has other django dependencies hence the django.setup() >>> testtask(10) # This works fine... but >>> testtask.delay(10) # hangs indefinitely Don't know why this is the case. Do I have to connect separately to the celery broker somehow? Watching celery events screen shows no events or entries being created. Thanks --prasanna -
How to provide a simple download section with sub folders in Django
I am trying to provide a simple download section via Django that lists files and sub folders and allows for downloading. I am using pythonanywhere for this. Here is my Link with the error: https://futureforest.eu.pythonanywhere.com/download/ Application name: servedownload views.py in servedownload: from django.shortcuts import render import os from django.http import FileResponse, Http404 def download_folder(request, path=''): # Set the file path to the directory you want to serve for download folder_path = os.path.join('/home/futureforest/webinterface/media/download', path) # Check if the folder exists, and raise a 404 error if it doesn't if not os.path.exists(folder_path): raise Http404('Folder not found') # Get a list of all the files and directories in the folder contents = os.listdir(folder_path) # Create empty lists for files and subdirectories files = [] subdirectories = [] # Iterate through the contents of the folder for item in contents: item_path = os.path.join(folder_path, item) # If the item is a file, add it to the list of files if os.path.isfile(item_path): files.append(item) # If the item is a directory, add it to the list of subdirectories elif os.path.isdir(item_path): subdirectories.append(item) # Recursively retrieve files from subdirectories subfiles = [] for subdirectory in subdirectories: subfiles.extend(download_folder(request, os.path.join(path, subdirectory))) # Combine the files in the current directory with the … -
API call to django server in my React app is returning invalid Json
I'm trying to connect my frontend react with backend django apps. In django, I defined my model database: from django.db import models class Departments(models.Model): DepartmentId = models.AutoField(primary_key=True) DepartmentName = models.CharField(max_length=100) my serializer: from rest_framework import serializers from EmployeeApp.models import Departments class DepartmentSerializer(serializers.ModelSerializer): class Meta: model = Departments fields = ('DepartmentId', 'DepartmentName') and my views: from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from django.http.response import JsonResponse from EmployeeApp.models import Departments from EmployeeApp.serializers import DepartmentSerializer @csrf_exempt def departmentApi(request, id=0): if request.method == 'GET': departments = Departments.objects.all() department_serializer = DepartmentSerializer(departments, many=True) return JsonResponse(department_serializer.data, safe=False) elif request.method == 'POST': department_data = JSONParser().parse(request) department_serializer = DepartmentSerializer(data=department_data) if department_serializer.is_valid(): department_serializer.save() return JsonResponse("Added Successfully!", safe=False) return JsonResponse("Failed to Add...", safe=False) elif request.method == 'PUT': department_data = JSONParser().parse(request) department = Departments.objects.get(DepartmentId = department_data['DepartmentId']) department_serializer=DepartmentSerializer(department, data=department_data) if department_serializer.is_valid(): department_serializer.save() return JsonResponse("Updated Sucessfully!", safe=False) return JsonResponse("Failed to update!", safe=False) elif request.method == 'DELETE': department = Departments.objects.get(DepartmentId=id) department.delete() return JsonResponse("Deleted Succefully!", safe=False) my urls: from django.urls import path from EmployeeApp import views urlpatterns = [ path('department', views.departmentApi), path('department/<int:id>', views.departmentApi) ] my django server runs on http://127.0.0.1:8000/, so I put it in my .env in the react app folder: REACT_APP_API_DEPARTMENT = http://127.0.0.1:8000/department and imported it to use on my Department.jsx component: … -
How to concat the django template variable in the jQuery html string for appending dynamically to the body
From the table, I can fetch the ID of the user, to get the first_name of the user, I have to get it from another table, to do this task I follow related_name method. for example, {{ data.custom_user.user_profile.first_name}} where user_profile is the related_name in the model. It works perfectly with html but how to do this if I am getting user ID from the ajax to jQuery ? Below is how I tried to concat the django variable in jQuery . jQuery(getElement).fadeOut(function () { jQuery(getElement).replaceWith("<p><span style='font-size: 15px; color: #008628;'><a href='#'>'"+{{res['new_comment'][0]['id'].master_user_profile.first_name}}+"'</a> – </span>"+res['new_comment'][0]['content']+"<span style='color: green;''><i class='la la-calendar-o'></i> Jan 16, 2016 07:48 am</span></p><p onclick='getInputElement(this);'id='{{question.id}}'>Add a comment</p>"); }).fadeIn(); } }); But it's not working. Please anyone let me know. -
Installing a version of Django REST framework that is compatible with Django 4+
I am in the process of upgrading from Django 3.2 to Django 4.0. When I do so, I get the following error: ImportError: cannot import name 'ugettext_lazy' from 'django.utils.translation' And the error seems to stem from this import: from django.utils.translation import ugettext_lazy as _ in rest_auth/registration/serializers.py I'm currently running Django 4.0.10 with djangorestframework 3.13.0, and I'm a bit confused because according to Django REST framework's release notes v3.13.0 should support Django 4.0 (I also tried v3.14.0, same results). What am I missing here? -
combined use of RedirectView and i18n_patterns in Django 4.0.3
I am having problems using RedirectView inside i18n_patterns in my urls.py file. My current situation is this: urlpatterns = i18n_patterns( path('', RedirectView.as_view(url='/home/', permanent=True)), path('adm/', admin.site.urls), path('rosetta/', include('rosetta.urls')), path('home/', include(('home.urls', 'home'), namespace='home')), ) What happens is that if I connect to my site (for this example mysite.com) I am not redirected to mysite.come/home, nor even to mysite.com/en/home. If I remove i18n_patterns urlpatterns = [ path('', RedirectView.as_view(url='/home/', permanent=True)), path('adm/', admin.site.urls), path('rosetta/', include('rosetta.urls')), path('home/', include(('home.urls', 'home'), namespace='home')), ] and I connect to mysite.com I am correctly redirected to mysite.com/home and the site works correctly. I have recently implemented i18n for the first time so I am not familiar with the topic. I tried splitting urlpatterns into two but got no results: urlpatterns = [ path('', RedirectView.as_view(url='/home/', permanent=True)), ] urlpatterns += i18n_patterns( path('adm/', admin.site.urls), path('rosetta/', include('rosetta.urls')), path('home/', include(('home.urls', 'home'), namespace='home')), ) -
Passing Value to create initial value in form
I am trying to create a center of a project (foreign key). However, when I call the url to create a center the project which this center should belong to is not automaticly set. So the user has to choose the project. The goal is to prefill the form element 'Project' with the name of the Project the id of which is specified in the url, the last element of the url is the id of the project as seen here: http://192.168.10.84:8080/procure/centercreate/5 Therefore I have to look up the name of the project with id 5, fill the form element and make it none editable. what I have so far. model of center: class Center(models.Model): CenterName = models.CharField(max_length=60, null=False) Project = models.ForeignKey(Project,on_delete=models.CASCADE) def __str__(self): return self.CenterName in the url.py path('centercreate/<int:pk>', views.CenterCreate.as_view(), name='center_create'), in the views.py: class CenterCreate(CreateView): model = Center form_class = CenterCreateForm template_name = 'Procure/center_create.html' def get_success_url(self): return reverse('centers_sys', kwargs={'pk':self.object.Project_id}) connected form I use: class CenterCreateForm(forms.ModelForm): class Meta: model = Center fields = "__all__" template used: {% extends "base_generic.html" %} {% block content %} <div id="container" > {% if user.is_authenticated %} <p>Welcome to ProcEdu - developed by <em>BZG</em>!</p> <h3>You are adding a Center to Project: <!-- PROJECT -->> </h3> … -
Django web app. werid theme toggle button
I'm developing a Django web app. If I try to access to the admin site there is a new button for selecting theme color. This button is not displayed properly. Here a screenshot: I didn't add any third party plugin about admin themes and I don't know which part of code you need to investigate the problem. Here you can find the installed packages of my python virtual env: asgiref==3.6.0 autopep8==2.0.2 beautifulsoup4==4.11.1 black==23.3.0 certifi==2022.12.7 charset-normalizer==3.1.0 click==8.1.3 colorama==0.4.6 defusedxml==0.7.1 diff-match-patch==20200713 Django==4.2 django-address==0.2.8 django-crispy-forms==1.14.0 django-filter==22.1 django-import-export==3.0.2 et-xmlfile==1.1.0 idna==3.4 MarkupPy==1.14 mypy-extensions==1.0.0 numpy==1.23.5 odfpy==1.4.1 openpyxl==3.0.10 packaging==23.1 pandas==1.5.1 pathspec==0.11.1 platformdirs==3.5.0 psycopg2==2.9.5 psycopg2-binary==2.9.5 pycodestyle==2.10.0 PySimpleGUI==4.60.4 python-dateutil==2.8.2 python-decouple==3.8 pytz==2022.6 PyYAML==6.0 requests==2.29.0 scipy==1.9.3 six==1.16.0 soupsieve==2.3.2.post1 sqlparse==0.4.3 tablib==3.3.0 tzdata==2022.6 urllib3==1.26.15 xlrd==2.0.1 XlsxWriter==3.1.0 xlwt==1.3.0 Here you can find my settings.py without sensitive data: """ Django settings for warehouseproject project. Generated by 'django-admin startproject' using Django 4.1.3. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path import os from django.urls import reverse_lazy from decouple import config, AutoConfig from django.contrib.messages import constants as messages # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent config = AutoConfig(search_path=".env") # Quick-start development settings - unsuitable … -
Will a Django Webapplication work on a Hostpoint standard Webserver?
I can't seem to find any confirmation anywhere that the standard webhosting service for HostPoint will be able to host my Django project. They seem to suggest I need a Managed Server to run my project, is that the case? I'm kind of new to all of this so I'm sorry if this is a stupid question. I've rummaged through hostpoint's site and can't find anything that helps me further, I've even written an email to hostpoint themselves but still haven't gotten an answer. -
Matplotlib and mpld3: how to show the corresponding y value of line plot in a tooltip based on hover x value?
I'm creating a graph in which I would like to show the Y value of the plot in a tooltip based on the hover x value. For this I am using Python with libraries: Matplotlib and mpld3. In my current version I have the tooltip showing up when I hover the line in the graph but I want it to show up when I just hover over the graph. For your visual presentation: This is what I have now (mouse hovering in red circle): My mouse is hovering in the red circle But I would like it to already show up when I hover above or below it like you can see in next picture. If I hover here I want the tooltip also to show with current hover x value and corresponding y value of the blue line I used the plugins.PointHTMLTooltip and it's working but only when I hover over the blue line, not when I just hover over the graph. -
Getting error [password authentication failed for user] while encrypt DB credential in Django
Hi Everyone i am working on django framework my credential store in config.ini file but when i encrypt my db password and run server getting 500 error in log showing password authentication failed for user this will happen when i encrypt db password and store in same config.ini file bt i store new config.ini file it will work but i need to store db password encryption in existing config.ini file please help me out. settings.py from cryptography.fernet import Fernet key = Fernet.generate_key() with open('key.key', 'wb') as key_file: key_file.write(key) # Define encrypt def encrypt(value): with open('key.key', 'rb') as key_file: key = key_file.read() f = Fernet(key) return f.encrypt(value.encode()).decode() #Define decrypt functions def decrypt(value): with open('key.key', 'rb') as key_file: key = key_file.read() f = Fernet(key) return f.decrypt(value.encode()).decode() # Read config file:------------------------------------------------------------ config = RawConfigParser() config.read(os.path.join(config_path, 'config.ini')) DB_PASSWORD = config['db_setting']['DB_PASSWORD'] encrypt_db_password=encrypt(DB_PASSWORD) # update config.ini file with encrypt_db_password config.set('db_setting','DB_PASSWORD', encrypt_db_password) with open('utility\config.ini', 'w') as config_file: config.write(config_file) #decrypt db_password decrypted_db_password = decrypt(encrypt_db_password) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db', 'USER': DB_USER, 'PASSWORD': decrypted_db_password, 'HOST': DB_HOST, 'PORT': DB_PORT, 'CONN_MAX_AGE': MAX_CONNECTION_AGE, 'OPTIONS': {'options': '-c search_path=' + SCHEMA + ',public'} } try to encrypt decrypt db password i will work when db credential store new config.ini file … -
ProgrammingError at /tasks/ (1146, "Table 'database.tasks_task_parent_task' doesn't exist")
I'm trying to join a table to itself using many-to-many. I keep getting an error that the table does not exist Model class Task(models.Model): title = models.CharField(max_length=255) description = models.TextField() percentage_of_realization = models.IntegerField() parent_task = models.ManyToManyField("Task", default=None) Migration: migrations.CreateModel( name='Task', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=255)), ('description', models.TextField()), ('percentage_of_realization', models.IntegerField()), ('parent_task', models.ManyToManyField(default=None, to='tasks.task')), ], ) I tried to write tasks in different ways like without "" or like tasks.task and modify with migrations, but nothing worked -
Displaying related data from two or more tables in a DetailView
I did not find information on how all named arguments **kwargs are passed in the overridden "get_context_data" method in the view call. There are 3 models: class User(models.Model): email = models.CharField(unique=True) company_id = models.IntegerField(blank=True, null=True) first_name = models.CharField(blank=True, null=True) last_name = models.CharField(blank=True, null=True) class Company(models.Model): logo = models.CharField(blank=True, null=True) name = models.CharField(blank=True, null=True) full_name = models.CharField(blank=True, null=True) address = models.CharField(blank=True, null=True) phone = models.CharField(blank=True, null=True) email = models.CharField(blank=True, null=True) kpp = models.CharField(blank=True, null=True) okved = models.CharField(blank=True, null=True) bik = models.CharField(blank=True, null=True) class Order(models.Model): user_id = models.IntegerField(blank=True, null=True) amount_total_cents = models.BigIntegerField() amount_mean_cents = models.BigIntegerField() created_at = models.DateTimeField() Communication between models: Company-User 1 to M, User-Order 1 to M There are no problems with direct output of data in the view without overriding the "get_context_data" method. However, there are no problems when overriding the method and linking two tables through the primary key: 1. company/urls.py urlpatterns = [ path('company/<int:pk>', CompanyShow.as_view(), name='company_show') ] company/views.py class CompanyShow(DetailView): model = Company template_name = 'company/company_show.html' context_object_name = 'company' def get_context_data(self, **kwargs): context = super(CompanyShow, self).get_context_data(**kwargs) context['users'] = User.objects.filter(company_id = self.kwargs['pk']) return context company_show.html <p>ID: {{ company.id }}</p> <p>Name: {{ company.name }}</p> <p>Members: {% for user in users %} <li> <a href="{% url 'user:user_show' user.id %}">{{ user … -
How to run a query with an inner query in it in Django?
I'm trying to run a query with an inner query in it as shown below: # Inner query Product.objects.filter(category__in=Category.objects.get(pk=1)) But, I got the error below: TypeError: 'Category' object is not iterable Also, I'm trying to run a query with an inner query in it as shown below: # Inner query Product.objects.filter(category=Category.objects.filter(pk=1)) But, I got the error below: ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing. So, how can I run these queries above with inner queries in them? -
How to make form fill and submit in bootstrap modal?
I can't figure out what the problem is, please help. I have a button, when clicked, a modal window opens, in which a form for adding an entry is displayed, but when the "save" button is clicked, the page reloads, but nothing is saved. I added my code below. If I make a form on a new page (localhost:8000/add_department/7), then the form is saved and everything works, but not in the modal window. base.html: <button class="btn btn-success btn-add btn-padding-left btn-add-department" data-bs-toggle="modal" data-bs-target="#button-department-add" data-url="{% url 'department_add' 7 %}"><i class="fa fa-plus"></i> Add department</button> <div class="modal fade" id="button-department-add" tabindex="-1" role="dialog" data-bs-backdrop="static"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content modal-department"> </div> </div> </div> add_department.html: <form action = "" method = "post"> <div class="modal-header"> <h5 class="modal-title">Add department</h5> <button class="btn-close" type="reset" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body" style="text-align: center;"> <b>Press "save".</b> <br> <br> {% csrf_token %} {{ form.as_p }} {{ answer }} </div> <div class="modal-footer"> <button type="submit" class="btn btn-success btn-save"><i class="fa fa-save"></i> Save</button> <button type="reset" class="btn btn-secondary btn-cancel" data-bs-dismiss="modal"><i class="fa fa-ban"></i> Cancel</button> </div> </form> views.py: from django.shortcuts import render from django.http import HttpResponse from .models import Region, Department from .forms import * from django.forms.models import model_to_dict from .forms import * from django.db import models from django.contrib.auth.decorators import login_required … -
can't load image from model via css background-image in my html page
can't load image from model via css background-image in my html page , i want to load image from model that i upload it to my html page via background-image in css my model : class Home_options(models.Model): background_img = models.ImageField(upload_to='images/',null=True, blank=True) your_small_img = models.ImageField(upload_to='images/',null=True, blank=True) # Background img def get_background_img(self): if self.background_img and hasattr(self.background_img, 'url'): return self.background_img.url else: return '/path/to/default/image' # your_small_img def get_your_small_img(self): if self.your_small_img and hasattr(self.your_small_img, 'url'): return self.your_small_img.url else: return '/path/to/default/image'` my css : .header { background-image: -webkit-linear-gradient(bottom, rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url('{{ home_options.get_background_img.url }}'); background-image: linear-gradient(to top, rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url('{{ home_options.get_background_img.url }}'); }` i tried to use home_options.get_background_img.url and home_options.your_small_img.url but they not work -
`FOREIGN KEY` on PlanetScale
I want to deploy a Django app on Vercel which uses PlanetScale as database. But since PlanetScale does not support foreign key and the Django works heavily with this constraint. So my question is there is any way that solves this problem ? I tried db_contraint setting to False like models.ForeignKey(Buses, on_delete=models.CASCADE, db_constraint=False) this for my models but this also not working.