Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can i show data using Veiw.py file
data enter in database but not showing on the Django website following error occur in view.py file File "C:\Users\usman\Downloads\OnlineCrime_ReportingSystem\firereport\views.py", line 5, in from .models import * Import Error: attempted relative import with no known parent package to solve this error I try a lot setting.py configuration urls.py the error are not solved overall project is working accurate but the data which is store on database not showing on website -
Accessing MySQL database with Django
Apologies in advance if this type of question already exists with a solution. I have been trying to get this solved for about 2 weeks now. So I had a Django project, which initially used the default Django database : SQLite3. I was able to access that database using /admin with the localhost, with 'admin' as password and username. I shifted the database to MySQL and everything was transferred properly, but I am not sure how to access the data using the /admin now. What should I enter in the username and password section? I have tried every possible combination with 'admin', database name, username, hostname and password which is provided in the settings.py when you change database. For reference, this is what the database section of my settings.py looks like DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'project', 'USER': 'root', 'PASSWORD': 'mysql-password', 'HOST': 'localhost', 'PORT': '3306', } } -
" Registration Sucessful" message is not showing in Django
Working on a Project"https://github.com/GargAnsh/donor_finder" wher i am having a "donor_add_form.html" which is having a donor registration form. While saving the form it's not displaying " regitration done succesfully " though entryn are succesfully hapening in data base and page redirecting to "Donor_finder.html " also I tried all the step, now need support to fix the problem. I also need help to expend the code further to add few feature. -
Can we create Attendance application inside Ms teams?
How to develop an attendence management application inside Microsoft teams app using python. My manager asked me to refer Microsoft SDK and its graph api. I have developed applications in django rest APIs but this is new for me. Dont know how to start and how to build this. How to use db for this and integrate here. Can anybody help me out -
Django rest auth - Custom validation error is not being caught
I am trying to overwrite the RegisterSerializer class provided by dj-rest-auth. I am running into an issue, which I believe is due to how I am trying to extend the ValidationError class I have overwritten the is_valid method as so: def is_valid(self, raise_exception=False): try: # we first replace password1 and password2 in initial_data (by default, dj-rest-auth # expects these fields -- our API just asks for 'password', and we rely on frontend # for password1=password2 verification) if "password" not in self.initial_data: raise CustomValidationError( GenericAPIErrorCodes.MALFORMED_REQUEST, "Password field is required" ) # Set "password1" and "password2" to the value of "password" self.initial_data["password1"] = self.initial_data["password"] self.initial_data["password2"] = self.initial_data["password"] output = super().is_valid(raise_exception=raise_exception) return output except CustomValidationError as exc: raise exc # furthering the error up the chain except DjangoCoreValidationError as exc: raise CustomValidationError( code=GenericAPIErrorCodes.MALFORMED_REQUEST.value, detail=exc.message ) except Exception as exc: print(exc) raise CustomValidationError( code=GenericAPIErrorCodes.MALFORMED_REQUEST.value, detail="" ) The error is getting thrown from line "output = super().is_valid(...)", which eventually ends up calling: def clean_password(self, password, user=None): # We catch errors coming out of clean password function and replace them with our own try: print("cleaning pass!") super().clean_password(password, user=user) print("cleaned!") except Exception as e: print("yes!") raise CustomValidationError( code=AuthErrorCodes.INVALID_PASSWORD.value, detail="Passwords must be at least 6 characters long, avoid … -
Problems with Django Websockets
I followed a Django Websockets tutorial in which I created a chatroom website. It didn't work so I doubble checked the code and I did everything the same as in the tutorial. I decided to clone the repository and check what is the problem with my code. I realized that the websockets didn't work with the downloaded project as well. Is there something wrong with the code or my computer? Link to the Tutorial: https://www.youtube.com/watch?v=jsxFEONN_yo Link to the repo: https://github.com/veryacademy/YT-Django-Project-Chatroom-Getting-Started.git I created a virtual env and installed django and channels. The only change I made is in the settings.py file where I replaced CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [os.environ['REDIS_URL']], }, }, } CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": os.environ['REDIS_URL'], "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" } } } With: CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } -
Celery Task received but not executing in Django project hosted on DigitalOcean
I have a Django project set up with Celery, hosted on a DigitalOcean droplet running Ubuntu 22.04. I'm running into a peculiar issue where a task is received by the Celery worker but doesn't seem to execute it. Here's the task that I am trying to run (provided by django-cookiecutter): from django.contrib.auth import get_user_model from config import celery_app User = get_user_model() @celery_app.task() def get_users_count(): return User.objects.count() I'm running the worker with the following command: celery -A config.celery_app worker --loglevel=DEBUG --without-gossip --without-mingle --without-heartbeat -Ofair --pool=solo I'm executing the task manually via django shell: get_users_count.delay() <AsyncResult: 821982b7-f256-462b-869c-e415da168c3f> The worker logs show that it received the task, but not that it's executed: [2023-10-06 23:57:25,568: INFO/MainProcess] Task myapp.users.tasks.get_users_count[821982b7-f256-462b-869c-e415da168c3f] received The task appears in Redis: 127.0.0.1:6379> keys * 1) "_kombu.binding.celery.pidbox" 2) "celery-task-meta-821982b7-f256-462b-869c-e415da168c3f" 3) "_kombu.binding.celery" When I query the task state and result manually, it shows that the task actually succeeded: >>> res = AsyncResult("821982b7-f256-462b-869c-e415da168c3f") >>> print("Task State: ", res.state) Task State: SUCCESS >>> print("Task Result: ", res.result) Task Result: 2 Despite the AsyncResult showing SUCCESS, there's no indication in the worker logs that the task was executed. What could be going wrong here? Any guidance would be greatly appreciated. The only thing that's really different … -
Django select the account from the account tree displays all the account details
I want when I select the account from the account tree using the checkbox it displays all the account details on the other side so I can add or edit an account later. What makes it difficult for me is that it relies on a tree system Please Help html {%load static%} <!DOCTYPE html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Daleel</title> <link rel="shortcut icon" href="{% static 'image/daleel.ico'%}" > <!-- Google Font: Source Sans Pro --> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback"> <!-- Font Awesome --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <link rel="stylesheet" href="{% static 'plugins/fontawesome-free/css/all.css'%}"> <!-- Bootstrap 5 --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <link href="https://unpkg.com/gijgo@1.9.14/css/gijgo.min.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" href="{% static 'css/acc.css'%}"> </head> <body> <h3 class="title">Accounts Tree</h3> <hr> <form method="POST"> {% csrf_token %} <div class='up'> <div class='acc'> <br> <div class="d-flex" role="search"> <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-secondary" type="submit">Search</button> </div> <br> {% for mainacc in mainaccs %} <ul class="tree" id="tree"> <li> <details > <summary class="mainacc" > <input class="form-check-input" type="radio" name="acc1" id="{{ aacc.acc_id1 }}" value="{{ mainacc.acc_id1 }}" style="margin-top:10px">&nbsp;&nbsp;{{ mainacc.acc_id1 }} ====>> {{ mainacc.E_name1 }}</summary> <ul> {% for aacc in mainacc.aacc_set.all %} <li> <details> <summary class="aacc"><input class="form-check-input" type="radio" name="acc2" id="{{ aacc.acc_id2 }}" value="{{ aacc.acc_id2 }}" style="margin-top:10px">&nbsp;&nbsp; {{ aacc.acc_id2 … -
grid-columns inside media queries not working for html article element?
Grid-columns doesn't seem to be working for my article element, but does for my nav. css /*sm-md*/ @media screen and (max-width:768px){ .signup-btn, .login-btn{font-size: 1.4em !important;} .listitem{font-size: 1.7em !important;} nav{grid-column: 4/15;} article{grid-column: 4/17;} } article{grid-column: 2/10;height: auto;width: 100%;margin: 30px 0 0 0;border-radius: 20px;display: flex;flex-direction: column;box-shadow: 0px 0px 20px 10px #0000001a;padding-inline: 30px;} nav{grid-column: 7/14;display: flex;width: 100%;justify-content: center;} Not sure what's the problem here? <main class="grid-container main"> <article class="grid-wrapper article"> content </article> <aside class="grid-wrapper aside"> content </aside> </main> Already searched documents and tried changing up things -
Django's query set filter with icontains stops working if there isn't at least one regisrty with unempty data at target column, what's the logic?
Okay, so I made a search form with some select fields I use to filter what plant species will appear in the search result page, like only species of a specific family. How it works: no value selected on any of the fileds, it returns all species. If you select something, it will filter species with that property or properties. So far it was working because I only filtered mandatory fields like family that all the species were required to have, the moment I added a query related to a field with no information on any of the species it made all searches return nothing, even without selecting any of the filters. So just to see if it would change anything, I inserted the information on the new fields using Django admin, and it started working as intended (meaning the filter was working and selecting nothing was showing all species again). Here is my query set logic that works as long as there is a single species: exemplares = Exemplar.objects.all() q = Q(tipoDeExemplar__opção__icontains=tipoDeExemplar) & \ Q(especie__familia__opção__icontains=familia) & \ Q(especie__genero__opcao__icontains=genero) & \ Q(especie__epiteto__opcao__icontains=epiteto) & \ Q(especie__variedade__opção__icontains=variedade) & \ Q(especie__grupoVegetal__opcao__icontains=grupoVegetal) & \ Q(especie__familiaLegada__opção__icontains=familiaLegada) & \ Q(especie__generoLegado__opcao__icontains=generoLegado) & \ Q(especie__epitetoLegado__opcao__icontains=epitetoLegado) exemplares = exemplares.filter(q) … -
How to remove these details showing under password in Django form?
I am using Django forms and want to remove these details that are showing in image i attach under. from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from django.contrib.auth.forms import AuthenticationForm from django.forms.widgets import PasswordInput , TextInput # - Register a user / Create a user class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username','password1','password2'] # - LOgin a user class LoginForm(UserCreationForm): username = forms.CharField(widget=TextInput()) password = forms.CharField(widget=PasswordInput()) -
How to run javascript unit tests on django templates
I am trying to create a django application that has javascript functions. Some of these functions also uses JQuery. I want to write unit tests for these functions using Jest. index.html <script src="{% static 'jquery-3.5.1.min.js' %}"></script> <script src="{% static 'setup.js' %}"></script> <script> $(document).ready(async function(){ const data = await myFunction() }) </script> setup.js async function myFunction(){ // call some jquery function here const res = await $.ajax() return res } setup.test.js import {myFunction} from '../setup' test('test my function', async () => { await myFunction() }) I have two problems here. When I call my function in my django template it works, but when I run the test it does not since it won't recognize jquery. I cannot import my function in the test unless I do export async function myFunction(){ // call some jquery function here const res = await $.ajax() return res } however, this won't work in my index.html because "expected token 'export' at ..." I have tried adding this to my base.html, however I get "Cannot use import statement outside a module at ..." <script> $(document).ready(async function(){ import myFunction from '{% static "setup.js" %}' const data = await myFunction() }) </script> I have also tried setup.test.js jest.mock('jquery') import … -
Django model - how to model history and current
I want to model Employee, and his contracts. So for example there is Employee1, and can have 3 contracts: from 01-2021 to 05-2021, from 05-2021 to 08-2023, from 08-2023 to 10-2024, Obviously the last one is current. We can model it with 2 models, and simple FK relationship. But - in most cases I will not need historical data, but just a current contract. To get it - some manipulation is needed ie. joining employee with contracts, and filtering based on current date. I prefer to avoid it, and have (in Employee model?) some field called "current contract" ?? But then some logic will be needed to update it... when any update/create on Contracts is done. Is there any inteligent way to handle such cases? -
Page not found (404) - The current path, poussaim/nouria/'
I've been stuck for a while; I can't figure out what's wrong. I want to display all the details about a customer (DetailView) and I get error 404. Here's the url returned: http://127.0.0.1:8000/poussaim/nouria/' When I remove the apostrophe at the end of the url, the page is displayed correctly: http://127.0.0.1:8000/poussaim/nouria/ Thanks in advance for your help. Here's my code urls.py from django.urls import path from poussaim_app.views import * app_name = "nrn" urlpatterns = [ path("contact/", signup, name="contact"), # Customer path("", HomeViewCustomer.as_view(), name="home"), path("<str:slug>/", DetailViewCustomer.as_view(), name="view-customer"), path("<str:slug>/deletecustomer/", DeleteViewCustomer.as_view(), name="delete-customer"), views.py from django.urls import reverse_lazy, reverse from django.views.generic import CreateView, UpdateView, DeleteView, ListView, DetailView from django.contrib.auth.mixins import LoginRequiredMixin from poussaim_app.models import Customer class HomeViewCustomer(ListView): """ Page d'accueil, page principale avec la liste des clients enrégistrés """ model = Customer template_name = "index.html" context_object_name = "customes class DetailViewCustomer(DetailView): """ Vue info/détail d'un client """ model = Customer template_name = "client/detail_client.html" context_object_name = "custome" class DeleteViewCustomer(DeleteView): """ Suppression d'un client """ model = Customer template_name = "client/delete.html" success_url = reverse_lazy("nrn:home") models.py class Customer(models.Model): """ Table client: la liste des entreprises partenaires name: nom de l'entreprise """ customer_name = models.CharField(max_length=255, unique=True, verbose_name="Nom du Client") gerant = models.CharField(max_length=255, blank=True,null=True, verbose_name="Nom du dirigeant ou son représentant") save_by … -
Django import model in subdirectory
I have an application "wallet" which has has a Transaction class. I want to use this Transaction inside a file located at: wallet/folder/file.py. The file.py should just import the Transaction class. So far I tried: sys.path.append('../../') from wallet.models import Transaction sys.path.append('../') from models import Transaction from wallet.models import Transaction or from ...wallet.models import Transaction. When I am confident that it should work I get this error: File "C:\Users\Sergiu\django_projects\BitcoinWhaleDashboard2.0\BitcoinWhaleDashboard\webapp\wallet\trading_bot\binance_api.py", line 5, in <module> from wallet.models import Transaction File "C:\Users\Sergiu\django_projects\BitcoinWhaleDashboard2.0\BitcoinWhaleDashboard\webapp\wallet\trading_bot\../..\wallet\models.py", line 6, in <module> class Transaction(models.Model): File "C:\Users\Sergiu\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 129, in __new__ app_config = apps.get_containing_app_config(module) File "C:\Users\Sergiu\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "C:\Users\Sergiu\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\registry.py", line 138, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I must mention that all the folders have init.py files in them. I have also tried to make use of the setup.py: # setup.py from setuptools import setup, find_packages setup(name='webapp', version='1.0.0', packages=find_packages('wallet')) but even after I run this I still encounter the exact same error. Please help. -
Decode Base64 string to PDF File Django Python?
I have this problem, I have this string in base 64: eC1hbXotaWQtMjogRW1VZWtRZHhLTWViUWZQa0txT... My idea is to decode the string and download the file (pdf), but when I try to download the file I have this screen enter image description here I do not what happen, this is the code that I use to decode and download the file: @login_required def get_pdf_document_invoice(request, id): import base64 print('invoice_pdf') customer = request.user.company.customer invoice_pdf = customer.get_pdf_invoice(id) contentb64 = invoice_pdf['data'] decode_file = base64.b64decode(contentb64) print(invoice_pdf, "pdf") response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=invoice.pdf' response.write(decode_file) return response -
Django Template Language - URL Based On Template {{ value }}
Let's say I have, in context, a JSON called "rows", and each row has 2 fields: a and b. I wish to make b a url parameter and pass to a url call, like this: {% for row in rows %} <tr> <td>{{ row.a }}</td> <td><a href = "{% url 'some url' param={{ row.b }} %}">{{ row.b }}</a></td> <tr> The above code is invalid. How to do this? -
django-DefectDojo postgres user disconnects & reconnects constantly
I am running DefectDojo on AWS using a serverless Aurora (Postgres 13.8) DB I see a large number of connect/disconnect events in the logs. They look like this: 2023-10-04 19:44:04 UTC:10.237.120.220(56990):[unknown]@[unknown]:[19442]:LOG: connection received: host=10.237.120.220 port=56990 2023-10-04 19:44:04 UTC:10.237.120.220(56990):postgres@defectdojo:[19442]:LOG: connection authorized: user=postgres database=defectdojo SSL enabled (protocol=TLSv1.2, cipher=AES128-GCM-SHA256, bits=128, compression=off) 2023-10-04 19:44:04 UTC:10.237.120.220(56990):postgres@defectdojo:[19442]:LOG: disconnection: session time: 0:00:00.011 user=postgres database=defectdojo host=10.237.120.220 port=56990 The logs are filled with these actions: connection received -> connection authorized -> disconnection. These sessions all last for less than a second. Is this behavior expected or is this a symptom of an underlying problem with my postgres user connection? -
Custom Middleware not worked on live server python django
When enable custom middleware in setting.py file in live server then the django application shows an error in browser: We're sorry, but something went wrong. The issue has been logged for investigation. Please try again later. error id: 1312e065. N.B in localhost server there was no issue. Setting.py: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'userAuth.custom_middleware.RequestLoggerMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'userAuth.middleware.InactivityTimeoutMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] middleware.py: class InactivityTimeoutMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) if request.user.is_authenticated: session_key = request.session.session_key if session_key: session = Session.objects.get(session_key=session_key) last_activity = session.get_decoded().get('_session_last_activity') if last_activity: idle_time = timezone.now() - last_activity if idle_time > timedelta(minutes=5): # User has been inactive for more than 5 minutes, log them out request.session.flush() return response thanks in advance. -
How can I solve problem with Django Template Language {{ form }}?
<div class="form-title"> {% if form.errors %} <p>{{ form.errors.error }}</p> {% endif %} <form action="{% url 'login' %}" method="post" class="fs-title"> {{ form }} {% csrf_token %} <button type="submit" class="btn btn-success">Join</button> </form> <a href="{% url 'password_reset' %}">Forgot password?</a> </div> I tried specifying the css name in the class attribute, but the output from {{form}} did not change its style. Is there a way to move the content of {{form}} to the center and set a style for it? -
Django runserver error: ModuleNotFoundError: No module named 'Deleted folder'
I hope you are doing well. I just started studying Django with the Meta back-end Cert. I created my first project inside a venv and ran the server just as instructed. Then I deleted the first folders, and tried to practice starting from zero. When I create the new project folder I do the following steps: create the venv -> py -m venv env activate the venv -> env\scripts\activate install django -> pip3 install django create the project -> django-admin startproject new_sample change directory -> cd new_sample try to runserver -> py manage.py runserver Error Below the console response, it tries to reach a deleted folder. ModuleNotFoundError: No module named 'C:\django_projects\project1' THE DELETED FOLDERS (env) PS C:\new_django_folder\project4\new_sample> py manage.py runserver Traceback (most recent call last): File "C:\new_django_folder\project4\env\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\new_django_folder\project4\env\Lib\site-packages\django\core\management\commands\runserver.py", line 74, in execute super().execute(*args, **options) File "C:\new_django_folder\project4\env\Lib\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\new_django_folder\project4\env\Lib\site-packages\django\core\management\commands\runserver.py", line 81, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: ^^^^^^^^^^^^^^ File "C:\new_django_folder\project4\env\Lib\site-packages\django\conf\__init__.py", line 102, in __getattr__ self._setup(name) File "C:\new_django_folder\project4\env\Lib\site-packages\django\conf\__init__.py", line 89, in _setup self._wrapped = Settings(settings_module) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\new_django_folder\project4\env\Lib\site-packages\django\conf\__init__.py", line 217, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python312\Lib\importlib\__init__.py", line 90, in import_module return … -
I get the error while applying "python manage.py migrate"
when I run python manage.py migrate I get the following error TypeError: function missing required argument 'year' (pos 1) following is my showmigrations (https://i.stack.imgur.com/gqT42.png) how can i solve this migration error in my django project ..? -
Error: Failed to deploy web package to App Service. Error: Deployment Failed, Package deployment using ZIP Deploy failed. Refer logs for more details
Deployment Failed. deployer = GITHUB_ZIP_DEPLOY deploymentPath = ZipDeploy. Extract zip. Remote build. Error: Failed to deploy web package to App Service. Error: Deployment Failed, Package deployment using ZIP Deploy failed. Refer logs for more details. I am using GitHub cli to deploy mu Django app to Azure app service It was working fine until GitHub started to use zip deployment or package deployment than It gives me this error. I tried to add WEBSITE_RUN_FROM_PACKAGE=1in my app configurations and the deployments pass in GitHub without errors but the app doesn't work at all. -
I can't transfer data to an html template from the view
I'm trying to transfer data from the model to an html template, but it turns out a little crooked, help me figure it out and do it normally? models class SidesCaseInCase(models.Model): '''8. Промежуточная таблица для сторон по делу''' name = models.CharField( max_length=150, verbose_name='ФИО' ) sides_case = models.ForeignKey( SidesCase, on_delete=models.SET_NULL, blank=True, null=True, verbose_name='Стороны по делу', ) date_sending_agenda = models.DateField( blank=True, null=True, verbose_name='Дата направления повестки' ) recived_case = models.ForeignKey( ReceivedCase, on_delete=models.SET_NULL, blank=True, null=True, verbose_name='Поступившее дело', ) business_card = models.ForeignKey( BusinessCard, on_delete=models.SET_NULL, blank=True, null=True, verbose_name='Карточка на дело', ) class Meta: constraints = [ UniqueConstraint( fields=('sides_case', 'recived_case'), name='sides_cese_unique' ) ] verbose_name = 'Стороны по делу, в деле' verbose_name_plural = 'Стороны по делу, в деле' views def index(request): template = 'index.html' title = 'Первый проект. Главная страница' business_card = BusinessCard.objects.select_related( 'case_category', 'author' ) ` # card = get_object_or_404(BusinessCard, pk=card_id) sides_case_in_case_data = SidesCaseInCase.objects.all()` cards = BusinessCard.objects.select_related('case_category', 'author') page_obj = paginator_list(request, cards) context = { 'title': title, 'text': 'Главная страница', 'business_card': business_card, 'page_obj': page_obj, } return render(request, template, context) def business_card_detail(request, card_id): '''страница подробней о карточке''' card = get_object_or_404(BusinessCard, pk=card_id) ` side = get_object_or_404(SidesCase, pk=card_id) sides_case_in_case_data = SidesCaseInCase.objects.filter( business_card=card )` author = card.author author_card = author.cards.count() context = { 'card': card, 'author': author, 'author_card': author_card, 'side': side, … -
How to store and render HTML template files?
I am creating a web map with Django, Leaflet and PostgreSQL. I have a layer with points on the map. When I click on them, a popup shows up with some attribute data about that feature. This popup also has a button, which when clicked, opens o modal window with more details about the clicked feature. The text that shows up in the modal is a HTML template's text data stored in a field in the points table. The text has HTML tags, and are correctly shown, formatted and styled. I also have some images that should be rendered in the modal window, but they are not. As I am new to web development, I am wondering what would be the optimal way of storing this long HTML templates with images. Is it better to leave them as HTML files and render them when the appropriate button is pressed? I tried to render the images with django's static method. On my index page I can render the images, using the same img tag as in the modal window: .