Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModelNotFoundError: No module named 'guardian.shortcuts'
I am trying to run a Django project, I tried to import assign_perm and remove_perm from guardian.shortcuts (code listed here: from guardian.shortcuts import assign_perm, remove_perm). and got an error: ModuleNotFoundError: No module named 'guardian.shortcuts' I am using python3.8.9 and django2.0.7. I have already tried install guardian(0.2.2) and Django-guardian(2.4.0). Please help me to figure it out. THX! -
How can i add a searchable drop down list/filter of cities?
I created a map using Folium in Python to visualize some geospatial data. However, I want to add a search bar with a drop-down list of cities that I want to manually write. This search bar should allow users to search for a specific city and, upon selection, the map should automatically pan to that city's location. How can I achieve this functionality using Folium? **index.html** <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous"> <title>HomePage</title> </head> <body> <!--- NAVBAR --> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Map App</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="{% url 'index' %}">Map <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> </ul> <form class="form-inline my-2 my-lg-0" method="post"> {% csrf_token %} {{form}} <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav> <!---END NAVBAR--> <div class="container"> <div class="row mt-5"> <div class="col-md-12 offset-md-0"> {{m | safe }} </div> </div> </div> <!-- Optional JavaScript; choose one of the two! --> <!-- Option 1: jQuery and Bootstrap Bundle (includes Popper) --> <script … -
Django View - How to Efficiently Filter Combined Querysets from Multiple Models?
I have a Django view that combines and sorts querysets from three different models (Event, Subject, and Article) to create a feed. I'm using the sorted function along with chain to merge the querysets and sort them based on the 'created_at' attribute. The feed is then returned as a list. However, I'm facing challenges when it comes to filtering the feed based on user-provided search and author parameters. Since the feed is in list form, I can't directly use the filter method from the Django QuerySet. class FeedView(View): form_class = YourFormClass template_name = 'your_template.html' def get_queryset(self): """ Get the combined and sorted queryset from events, subjects, and articles. """ events = Event.objects.all() subjects = Subject.objects.all() articles = Article.objects.all() feed = sorted( chain(articles, subjects, events), key=attrgetter('created_at'), reverse=True, ) return feed def filter_queryset(self, queryset): form = self.form_class(self.request.GET) if form.is_valid(): data = form.cleaned_data search = data.get('search') if search: queryset = [item for item in queryset if search in getattr(item, 'name', '')] author = data.get('author') if author: queryset = [item for item in queryset if author in getattr(item, 'created_by__username', '')] return queryset def get(self, request, *args, **kwargs): queryset = self.get_queryset() queryset = self.filter_queryset(queryset) context = { 'object_list': queryset, } return render(request, self.template_name, context) -
Submenu not displaying properly when i fectch data from database in Django
Good all I wanted to create a dynamic menu with submenu populating the menus from database. I created two tables mainmenu which related to submenu. The mainmenu gets populated and is didplayed properly but the submenu is populated but does not dropdown properly, the submenu stays ontop of each other. However if I manually code both mainmenu and submenu both work far. What am I doing wrong? Thanks for your time. What I Wanted What I am Getting My Code - Django Template <div class="collapse navbar-collapse sub-menu-bar" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> {% for mainmenu in mainmenu %} <li class="nav-item"> <a href="{{ mainmenu.menulink }}">{{ mainmenu.name }}</a> {% for submenu in mainmenu.submenu.all %} <ul class="sub-menu"> <div> <a href="{{ submenu.menulink }}">{{ submenu.name }}</a> </div> </ul> {% endfor%} </li> {% endfor %} </ul> </div> My Custom Context Processor from setup.models import Setup, Mainmenu, Submenu def setup(request): setup = Setup.objects.first() return {'organisation': setup} def mainmenu(request): mainmenu = Mainmenu.objects.order_by("order").filter(menutype="main") return {'mainmenu': mainmenu} def submenu(request): submenu = Submenu.objects.order_by("order").filter(menutype="submenu") return {'submenu': submenu}` **My Database Table** class Mainmenu(models.Model): name = models.CharField(_("Menu Name"), max_length=256, blank=True, null=True, unique=False) menulink = models.CharField(_("Menu Link"), max_length=512, blank=True, null=True, help_text="Enter menu link like this, <code>https://uidc.com.ng/page/display/about-us/</code>") order = models.CharField(_("Menu Order"), max_length=512, blank=True, null=True) is_active = models.CharField(_("Is … -
how do i fix the look of the pages
Error Hi Everyone, I published my django project with ubuntu 22.04 and apache2, but it looks like the picture, I tried many ways for the solution but it didn't work, what do you think might be the reason, thanks in advance it should look like it's not like this -
Django Rest Framework - partial=True is suppressing errors
I have a fairly simple code to patch an object called Entity. I am using HTTP PATCH to pass a few fields and then using the following code to update the Entity object. def patch(self, request, id): entity = getEntityOr404(id) serializer = EntitySerializer(entity, data=request.data, partial=True) print(serializer.__dict__) if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) As I pass the following request body in the PATCH call... { "email_id_verified": "true", "phone_id_verified": "true" } ....I see various errors messages in the serializer, the output is as below 'error_messages': {'required': 'This field is required.', 'null': 'This field may not be null.', 'invalid': 'Invalid data. Expected a dictionary, but got {datatype}.'}} But surprisingly there are no errors in the response returned and the code is 200 OK. When I remove the partial=True it obviously starts throwing all sorts of errors. Can someone help me in understanding what is happening here? -
Django Rest Framework error - This field may not be null for required=False
The Serializer class is as follows: class EntitySerializer(serializers.ModelSerializer): is_active = serializers.BooleanField(required=False) class Meta: model = Entity fields = ['is_active', 'owner_name', ...] extra_kwargs = {'is_active': {'required': False}} The model is: class Entity(models.Model): owner_name = models.CharField(max_length=100, null=False) is_active = models.BooleanField(default=False, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) When I try to create an Entity with POST request which does not have is_active in the request body it throws the following error { "is_active": [ "This field may not be null." ] } I am expecting that serializer should work as the field is_active is optional and not throw the null error. I don't understand what is wrong. The field is_active is a boolean field and is declared as below is_active = models.BooleanField(default=False, null=True) The django versions are as follows Django==4.2.2 django-environ==0.10.0 django-rest-framework==0.1.0 djangorestframework==3.14.0 -
Trouble importing file from subdirectory in Django project
I have this file structure in Django project: project ├── app └── __init__.py views.py ... tasks └── __init__.py server_tasks.py In views.py I tried to import project/app/tasks/server_tasks.py by typing following statements from tasks import server_tasks or from tasks.server_tasks import * And python3 manage.py runserver gives me following output File "/home/user-unix/python/django_projects/project/app/views.py", line 6, in <module> from tasks import server_tasks ModuleNotFoundError: No module named 'tasks' How can I import server_tasks.py into views.py? I tried answers from very similar question on stackoverflow but it doesn't work for me. -
How to update web page after successfull ajax request without reload the page
I am sending the AJAX request to server and after success I would like to update the page without refreshing it fully. It is my snippet of code, but here I can just reloading the page and not sure how to do that without it, my line does not work either, could you help, please? PS. I am using Django for back-end function saveTags(slug, form, e) { e.preventDefault(); let tags = form.getElementsByClassName("new-tags")[0].value; if (tags != '') { var formData = { csrfmiddlewaretoken: '{{ csrf_token }}', slug: slug, tags: tags, }; var POST_URL = "{% url 'save_tags' %}"; $.ajax({ url: POST_URL, type: "POST", data: formData, success: function (data) { var x = document.getElementById("snackbar"); x.classList.add("show"); setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000); $("document").html(data); //window.location.reload(true); } }); // end ajax } return false; }; -
In Django, print a text in a textarea after clicking on a button
I would like to select an element of the combobox and print it in a textarea, after clicking on the button. I have no errors, but the problem that when I click the button nothing happens I have a combobox with this function: views.py def trips(request): country = request.GET.get('country') trips = Trip.objects.filter(country=country) return render(request, 'trips.html', {"trips": trips}) I would like to print trips in a textarea. So I created the textarea and the button (I DON'T want them in a form) home.html .... .... .... {% include "trips.html" %} <!-- Textarea--> {% include "result.html" %} <!-- NOTE: textarea name="result" id="id_result"></textarea>--> <!-- Button--> <button type="button" class="mybtn" href="{% url 'test'%}">Button 1</button> <button type="submit" name='mybtn' value={{test}}>Button 2</button> In views.py I also added the function to print in the textarea (but surely I must have done something wrong) def test(request, trips): new = ("my trips is ", trips) return render(request,"result.html", {"new": new}) In urls.py urlpatterns = [ path('trips', views.trips, name='trips'), path('mytest', views.test, name='test'), ] -
Django Python : This variable is defined, yet the shell says it is undefined not allowing me to process the page
Hi I'm relatively new to Django and am struggling to understand how models work with views. This is from a form used to create a flashcard. I'm trying to assign the characters inputted in the fields to the classes parameters. Then I would like to display the parameters in a card which I do in the template. Whilst I would like this issue fixed I would also be open to see if there are any better and more efficient ways to approach this issue. This is the section of my views.py that raise the issue: def flashcard(response): if response.method == "POST": form = Flashcard_verif(response.POST) if form.is_valid(): print("is workinggg boii") head = form.cleaned_data["header"] ques = form.cleaned_data["question"] ans = form.cleaned_data["answer"] flashcard_data = Flashcard(header=head, question=ques, answer=ans) global rawHeader, rawQuestion, rawAnswer rawHeader, rawQuestion, rawAnswer = Flashcard(header=head, question=ques, answer=ans).flash_format() print(rawHeader, rawQuestion, rawAnswer) flashcard_data.save() else: form = Flashcard_verif() return render(response, "main/Flashcard.html", { "form":form, "header":rawHeader, "question":rawQuestion, "ans":rawAnswer, }) This is the flashcard model: class Flashcard(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="flashcard", null=True) header = models.CharField(max_length=40) question = models.CharField(max_length=200) answer = models.CharField(max_length=200) def __str__(self): return self.header def flash_format(self): print(self.header, self.question, self.answer) return self.header, self.question, self.answer This is the template: {% extends 'main/base.html' %} {% load static %} {% block … -
Watchlist matching query does not exist
Iam trying to find out if a movie exists on the watchlist on my movie project and this error occured while i goes to detail page of a movie that doesn't exists in watchlist, how can i solve this? this is the code. this is my Watchlist model class Watchlist(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) movie=models.ForeignKey(Movie,on_delete=models.CASCADE) quantity=models.IntegerField(default=1) date=models.DateField(auto_now_add=True) def __str__(self): return self.movie.name this is my movie detail request function on views.py def view_movie(request,mslug): user=request.usermovie=Movie.objects.get(slug=mslug) watchlist=Watchlist.objects.get(user=user,movie__slug=mslug) return render(request,'moviesingle.html',{'mov':movie,'watchlist':watchlist}) this is the movie detail template <div class="social-btn"> {% if watchlist.is_none %} <a href="{% url 'Watchlist:add_watchlist' mov.id %}" class="parent-btn"> <i class="ion-plus"></i> Add to Watchlist</a> {% else %} <a href="" class="parent-btn"> <i class="ion-heart"></i> Already in Watchlist</a> {% endif %} </div> while going to a movie that exists on the watchlsit, its showing 'Already on watchlist', the problem is with the movies not in watchlist.. -
Django: Hide required field in form and generate value from other fields
Having a class like this: class MyClass(): foo = CharField('Foo', max_length=42) bar = CharField('Bar', max_length=42) baz = CharField('Baz', max_length=42) Fields "foo" and "bar" should be show in the form, field "baz" should NOT be shown. When POST'ing, the field "baz" should be generated from "foo" and "bar", e.g.: baz = foo + bar The "baz" field can be prevented from shown in the form by using the "HiddenInput" widget. Ok. But using the CBV: Where to generate the "baz" content from "foo" and "bar"? In the "def post()", in the "def is_valid()", in the "def clean()"? Or somewhere else? -
an error is displayed The view images.views.image_create didn't return an HttpResponse object. It returned None instead
' from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from .forms import ImageCreateForm @login_required def image_create(request): if request.method == 'POST': # форма отправлена form = ImageCreateForm(data=request.POST) if form.is_valid(): # данные в форме валидны cd = form.cleaned_data new_image = form.save(commit=False) # назначить текущего пользователя элементу new_image.user = request.user new_image.save() messages.success(request,'Image added successfully') # перенаправить к представлению детальной # информации о только что созданном элементе return redirect(new_image.get_absolute_url()) else: # скомпоновать форму с данными, # предоставленными букмарклетом методом GET form = ImageCreateForm(data=request.GET) return render(request,'images/image/create.html',{'section': 'images','form': form}) ' if I write code from the phone and run it on Termux I tried to check the code but didn't find anything -
Implementing WooCommerce attributes into Django
I want to create a model where I can dynamically add the three attributes color, size and type like the images below taken from WooCommerce. Sometimes each feature comes in a single form and sometimes it comes in a double form -
python3.8 cannot import ed448 from cryptography.hazmat.primitives.asymmetric
I am using python3.8 to run a Django project, I tried to import Pisa from xhtml2pdf, got a error message listed below: File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/xhtml2pdf/pisa.py", line 26, in <module> from xhtml2pdf.document import pisaDocument File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/xhtml2pdf/document.py", line 24, in <module> from xhtml2pdf.builders.signs import PDFSignature File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/xhtml2pdf/builders/signs.py", line 5, in <module> from pyhanko.pdf_utils.incremental_writer import IncrementalPdfFileWriter File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko/pdf_utils/incremental_writer.py", line 8, in <module> from . import generic, misc File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko/pdf_utils/generic.py", line 21, in <module> from .misc import ( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko/pdf_utils/misc.py", line 18, in <module> from pyhanko_certvalidator.util import CancelableAsyncIterator, ConsList File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko_certvalidator/__init__.py", line 8, in <module> from .context import ValidationContext File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko_certvalidator/context.py", line 13, in <module> from .fetchers.requests_fetchers import RequestsFetcherBackend File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko_certvalidator/fetchers/requests_fetchers/__init__.py", line 8, in <module> from .cert_fetch_client import RequestsCertificateFetcher File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko_certvalidator/fetchers/requests_fetchers/cert_fetch_client.py", line 7, in <module> from ...errors import CertificateFetchError File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko_certvalidator/errors.py", line 8, in <module> from pyhanko_certvalidator._state import ValProcState File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko_certvalidator/_state.py", line 5, in <module> from pyhanko_certvalidator.path import ValidationPath File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko_certvalidator/path.py", line 15, in <module> from .util import get_ac_extension_value, get_issuer_dn File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko_certvalidator/util.py", line 10, in <module> from cryptography.hazmat.primitives.asymmetric import ( ImportError: cannot import name 'ed448' from 'cryptography.hazmat.primitives.asymmetric' (/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/cryptography/hazmat/primitives/asymmetric/__init__.py) P.S. my python version is 3.8.9, Django version is 2.0.7, cryptography version is 2.2.2. Can you please help me to figure it out? THX! -
Sending json and file(binary) together by requests() of python
I have this curl command which send file and data to my api. It works correctly. curl --location 'localhost:8088/api/' \ --header 'Content-Type: multipart/form-data' \ --header 'Accept: application/json' \ --form 'file=@"image.png"' \ --form 'metadata="{ \"meta\": { \"number\": 400 }}"' Now I want to do the equivalent thing to inside of the python. So I use requests however it says TypeError: request() got an unexpected keyword argument 'file' How can I do when sending the json and image data together? headers = { 'Content-Type': 'multipart/form-data', 'Accept': 'application/json' } metadata = {"number":400} response = requests.post('https://localhost:8088/api/', headers=headers, data={ metadata:metadata}, file = { open("image.png",'rb') } ) -
django show field from related model in form
I just don't get it. I have been reading but I am not even close to find the answer. It is most likely extremely easy. I have two models Person (Name and zipcode) and Zip (Zipcode and city). When registering a new person the field name and zipcode should be entered. When zipcode is entered the related correct city from the Zipmodel should be shown models.py class Zip(models.Model): zipcode = models.IntegerField() city = models.CharField(max_length=200) def __str__(self): return str(self.zipcode) class Person(models.Model): name = models.CharField(max_length=200) zipcode = models.ForeignKey('Zip',on_delete=models.CASCADE,) def __str__(self): return self.name forms.py from django import forms from .models import Zip, Person class PersonForm(forms.ModelForm): class Meta: model = Person fields = ('name', 'zipcode',) class ZipForm(forms.ModelForm): class Meta: model = Zip fields = ('zipcode', 'city',) views.py from django.shortcuts import render, redirect, get_object_or_404 from .forms import PersonForm, ZipForm from .models import Zip, Person def index(request): return render(request, 'theapp/index.html' ) def person_new(request): if request.method == "POST": form = PersonForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('person_detail', pk=post.pk) else: form = PersonForm() return render(request, 'theapp/person.html', {'form': form}) def zip_new(request): if request.method == "POST": form = ZipForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('zip_detail', pk=post.pk) else: form = ZipForm() return render(request, 'theapp/zip.html', {'form': form}) def … -
How to get the file object from request
I send file with javascript like this, fetch png from server and send to the python fetch(fileUrl,{headers: headers}) .then(response => response.blob()) .then(blob => new File([blob], "image.png")) .then(file => { var formData = new FormData(); formData.append("metadata",JSON.stringify(metadata)); formData.append("file",file); axios.post( ai_api,formData,{} ).then(function (response) { console.log("sent success"); } then in django @api_view(["POST"]) def jobs(request): metadata = request.POST.get("metadata") file = request.POST.get("file") print(metadata) # I can get the metadata here!! print(file) # None why this file is None? How can I get the file itself? -
i cannot create a column aws rds database using django
when i add code at models.py file to make a new column like below, partnerId = models.IntegerField(null=True, blank=True, default=None) # added and do "python manage.py makemigrations" and "python manage.py migrate", and migration is done successfully, but the 'partnerId' column' is created only in local mysql database, not in aws rds mysql database. how can i deal with this problem? -
ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported
I am working on a django project, it was working fine untill I added "namespace="polls" in the code below(urls.py) and connected it to "index.html" in 2nd code. 1st- urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('polls/', include('polls.urls', namespace="polls")), ] 2nd: index.html: {% extends 'polls/base.html' %} {% block main_content %} {% if latest_questions %} <ul> {% for question in latest_questions %} <li><a href={% url "polls:detail" question.id %}><b>{{question.question_text}}</b</a></li> {% endfor %} </ul> {% else %} <p> You don't have any questions. Please add some.</p> {% endif %} {% endblock %} Now when I renserver it shows following error: ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. Please help, where I am wrong, it could be some missing package/s too as it is recently installed pycharm. Thank you. -
django and stripe subscription payments issues
I'm trying to create a subscription based saas in django. There are three subscription tiers with both monthly and annual payment options. I have setup the stripe customer id to be created when a new user signs up. I have somehow managed to put together the forms so that they redirect to Stripe's checkout, but I can't save the subscription id and the subscription end date in the database. I get an error as well "An error occurred while creating the new subscription: Request req_8TXfavfNXo1P0A: This customer has no attached payment source or default payment method. Please consider adding a default payment method. For more information, visit https://stripe.com/docs/billing/subscriptions/payment-methods-setting#payment-method-priority." I want to be able to save the subscription id and subscription end date after a successful payment. My models.py from django.conf import settings from django.contrib.auth import get_user_model from django.db import models from django.db.models.signals import post_save import stripe stripe.api_key = settings.STRIPE_SECRET_KEY User = get_user_model() MEMBERSHIP_CHOICES = ( ('Free', 'free'), ('Basic', 'basic'), ('Premium', 'premium') ) class Membership(models.Model): membership_type = models.CharField( choices=MEMBERSHIP_CHOICES, default='Free', max_length=30) stripe_monthly_plan_id = models.CharField(max_length=40, blank=True, null=True) stripe_yearly_plan_id = models.CharField(max_length=40, blank=True, null=True) price_monthly = models.IntegerField(default=0) price_yearly = models.IntegerField(default=0) ordering = models.PositiveIntegerField(default=0) def __str__(self): return self.membership_type class UserMembership(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) stripe_customer_id … -
Nginx container don't see static from Django container
I launch containers through docker-compose, and when I go to url I see site without static. Where is the problem? git link to project - https://github.com/NNKapustin/docker-compose result I have tried different settings for Nginx and docker-compose.yml, but steel have same problem -
Docker-compose up starts Django server, but after changing index.html in templates folder, server doesn't reflect changes
My Dockerfile FROM python:3.6-slim ENV PYTHONUNBUFFERED 1 RUN mkdir /demo WORKDIR /demo ADD . /demo COPY requirements.txt . RUN pip3 install -r requirements.txt EXPOSE 8000 CMD python manage.py runserver 0:8000 my docker-compose file version: "3" services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/app ports: - "8000:8000" i tried all solution which provided by chatgpt but none of them is working for me -
Django html dependencies
I'm new to Django, I'm trying to load bootstrap5 and js to my project. To achieve this, I created a 'base.html' under templates and extend it in my other html file. For example: {% extends 'base.html' %} {% block content %} <div class="mt-4"> <h2>Log In</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Log In</button> </form> </div> {% endblock %} This method works but I think it might make the maintenance harder if I include those tags in all of my html files, so is it possible to remove those tags and the dependencies still works? {% extends 'base.html' %} {% block content %} ... {% endblock %} I've tried to use a document_processors to load the CDN, I can confirm that this method is executed but the style is still not loaded if I remove the tags. # document.processor.py def base_template_variables(request): return { 'title': 'Default Title', 'bootstrap_css_cdn': 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css', 'bootstrap_js_cdn': 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/js/bootstrap.bundle.min.js', }