Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Inheritance one model choice field from another
I have couple tables in DB. class VehicleBrand(models.Model): name = models.CharField(max_length=128, unique=True) class VehicleModel(models.Model): name = models.CharField(max_length=128, unique=True) class Vehicle(models.Model): link = models.CharField(max_length=256, unique=True, blank=False, null=False) model = models.ForeignKey(VehicleModel, on_delete=models.PROTECT) brand = models.ForeignKey(VehicleBrand, on_delete=models.PROTECT) I tried to crate form with two ModelChoiceField depending one from another. I have first Field (just all items from VehicleBrand) # first field brand = forms.ModelChoiceField(queryset=VehicleBrand.objects.all()) Next I want to get qs of models depending of first choice: # get brand brand = VehicleBrand.oblects.get(name=brand) # get qs for all items with chosen brand qs = Vehicle.objects.filter(brand=brand) # I want get second field with choices as list of distinct models values model = qs.values('model').distinct() For example I have next table 1 link1 Toyota Corolla 2 link2 Toyota Camry 3 link3 Nissan Altima 4 link4 Nissan Almera If I choose 'Toyota' I wanna have only models for it: 'Corolla' and 'Camry'. I wanna get it in one page dinamically depending of first(brand) field. Is it possible? Could someone give me advise please? Thanks. -
How to to create a Dynamic variable and Value in Django Admin
Please, I am completely new to this approach but I believed it is possible. I want to dynamically create something like this image in Django admin and render the result for other users to see. -
Manytomany into notifications does not work
I don't really understand why when I save my model. The notification does not save the ManyToMany relationship, exemple. Do you have any idea? def notifs_rerservationorder(sender, instance, *args, **kwargs): rerservationorder = instance table_nb = rerservationorder.exemple.all() notify = Notification(rerservationorder=rerservationorder, notification_type=9) notify.save() notify.exemple.add(*table_nb) notify.save() post_save.connect(notifs_rerservationorder, sender=RerservationOrder class Notification(models.Model): NOTIFICATION_TYPES = ... ... exemple = models.ManyToManyField('post.Exemple',blank=True, null=True, related_name='notifs_exemple') ... ) -
Python Flask-WTF Forms not showing up when running server, only base html not child html file, how can i fix it?
tried to create a signup form, here is my file tree right now: -mysite\ --app.py --forms.py --form.html --templates\ ----index.html so im pretty sure the structure is fine, however when i use terminal in PyCharm and run command, flask run, server starts without errors, however my forms.py is not running just index.html here is what my scripts look like from forms import RegistrationForm app = Flask(__name__, instance_relative_config=False) app.testing = True app.config['SECRET_KEY'] = 'any secret string' @app.route('/', methods=('GET', 'POST')) def registration(): form = RegistrationForm() if form.validate_on_submit(): return redirect(url_for('success')) return render_template( 'index.html', form=form ) so when i click on the link in the terminal from pycharm i get index.html boots up, however, the script from form.html does not work.. i have in form.html: {% extends 'index.html' %} ........... {% endblock %} obviously i have some script between the blocks .. not too sure what i am doin wrong. parent html = index.html child html = form.html -
Items after reload showing in different order Django
Hi I've made django webstore and there is small yet annoying bug. If I add click on add quantity in my cart items after reload are in different order note this only happens when user is not authenticated here are short gifs to help you understand my probelm not working correctly when user is auth and working correctly on guest user cart.js var updateBtn =document.getElementsByClassName("update-cart") for (i = 0; i < updateBtn.length; i++){ updateBtn[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action if (user === "AnonymousUser"){ addCookieItem(productId,action) }else{ updateUserOrder(productId, action) } }) } function addCookieItem(productId,action){ if(action == "add"){ if(cart[productId] === undefined){ cart[productId] = {'quantity':1} }else{ cart[productId]['quantity'] += 1 } } if (action == "remove" || action =="delete"){ cart[productId]['quantity'] -= 1 if(cart[productId]['quantity'] <= 0){ delete cart[productId] } } document.cookie = 'cart=' + JSON.stringify(cart) + ";domain=;path=/" history.go(0) } function updateUserOrder(productId, action){ var url = 'http://127.0.0.1:8000/updateItem' fetch(url, { method:'POST', headers:{ 'Content-Type': 'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId':productId, 'action':action}) }) .then((response) =>{ return response.json() }) .then((data) =>{ console.log(data) history.go(0) }) } html <div class="row no-gutters"> <div class="col-4"> <div class="controlQtyCart"> <i data-product="{{ x.product.id }}" data-action="remove" class="fas fa-minus update-cart updatePointer"></i> </div> </div> <div class="col-4"> <div class="controlQtyCart"> &nbsp;{{x.quantity}} </div> </div> <div class="col-4"> <div class="controlQtyCart"> <i data-product="{{ x.product.id }}" … -
Django: Parent object has no attribute children_set
I have these two models: class Periodo(models.Model): # id usato per identificare i documenti # periodo rilevato in fattura data_i_p = models.DateField('data inizio', blank=True) data_f_p = models.DateField('data fine ', blank=True) mc_p = models.DecimalField('mc', max_digits=7, decimal_places=0, blank=True, default=0) idfatt = models.ForeignKey(FattAqp, verbose_name="fattura AQP", on_delete=models.CASCADE, related_name='periodo_rel') descr = models.CharField('descrizione', max_length=50) objects = models.Manager() class Meta: verbose_name = 'Periodo' class DettFAqp(models.Model): imponibile = models.DecimalField('imponibile', max_digits=8, decimal_places=2, default=0) iva = models.DecimalField('%IVA', max_digits=4, decimal_places=2, default=10) mc = models.DecimalField('qtà (gg/mc)', max_digits=7, decimal_places=0, blank=True, default=0) voce = models.ForeignKey(VoceAqp, verbose_name="metodo di ripart.", on_delete=models.CASCADE) periodo = models.ForeignKey(Periodo, verbose_name="Periodo in fattura", on_delete=models.CASCADE, related_name='dettfaqp', help_text=u"periodo cui la voce appartiene") rigo = models.DecimalField('rigo', max_digits=2, decimal_places=0, default=0, help_text=u"rigo di fattura") when I try to access the set related to the parent I get the following error: >>> p=Periodo.objects.get(pk=2) >>> p <Periodo: consumo accertato in 344 gg> >>> p.dettfaqp_set.all() Traceback (most recent call last): File "<input>", line 1, in <module> p.dettfaqp_set.all() AttributeError: 'Periodo' object has no attribute 'dettfaqp_set' Any suggestion? Many tankds in advance. -
Nextcloud as User Master for other web apps (i.e. django based)
I have a Nextcloud instance where all potential users have an account. I would like to set up an Open Source Doodle (Bitpoll) that is django based, as I don't like the nextcloud poll app. For security reasons I would like to limit the Doodle app to users of my nextcloud. Also I don't want them to enter a password using the doodle app (so single sign on is required). I imagine a similar user user flow as the Login in with Github button that can be used to also create user accounts. The doodle app supports LDAP, so does nextcloud. There are django modules for OAuth as well as for the nextcloud. I have no LDAP experience at all and only very little OAuth experience. With which Nextcloud Settings / Apps and which Django Apps (and an idea of the settings) can I realize the explained scenario? To be more precise: Do I need to use LDAP at all? Or can I configure OAuth in a way that all users that come from nextcloud.mydomain.org generate a new account in the app? What are the correct OAuth terms for my nextcloud istance and for the doodle app in this scenario? … -
Images not showing after about 1 day of upload with editors (ckeditor)
I host my files on Digitalocean space. Almost everything works fine. The only issue is that I am unable to see images uploaded with editors for instance ckeditor after about a day of upload. This does show at first but fail to display by second day. When I tried to preview the image to ascertain what is wrong, I encountered this kind of error: <Error> <Code>AccessDenied</Code> <RequestId>txgjk006000a4ca-47ce82d-nyc3bkkhv**""**</RequestId> <HostId>47ce82d-***********zg02</HostId> </Error> Note: I replaced some things with ****. I've tried what I could do eg changing permission but all to no avail. Other images uploaded through IMG tags are displaying properly. The app is a django app. The site is medsjoin.com The concerned URLs are: https://www.medsjoin.com/post/101-are-covid19-vaccines-safe-for-hiv-patients/ https://www.medsjoin.com/forum/topic/14/covid19-update-in-nigeria/#c13 Kindly help. -
Nested Serializer in case of multiple children models
Given the following models class Parent(models.Model) type = models.CharField() # 1 = Child1, 2 = Child2 class Child1(models.Model) parent = models.ForeignKey(Parent, related_name='child1') class Child2(models.Model) parent = models.ForeignKey(Parent, related_name='child2') How do I go about setting up a Parent serializer which also serializes its children appropriately class ParentSerializer(serializers.ModelSerializer): child = ... # SomeSerializer depending on the `type` field on the parent class Meta: model = Parent fields = '__all__' -
How to serialize ChoiceFields in Django Rest Framework?
First time Python user here, coming from Javascript world. I'm able to retrieve my Model serialized to JSON from Django API and display it on the frontend written in React. But now I just added one more field priority to the Model that has multiple choices and I struggle to get these choices to the frontend (I want to display them in a dropdown and update REST API). Migration was successful and I can select choices from the back end but on the frontend I just get the default value set from migrations. Here is my code right now: models.py class Todo(models.Model): title = models.CharField(max_length=120) description = models.TextField() completed = models.BooleanField(default=False) priority_choices = [ ('High', 'High'), ('Medium', 'Medium'), ('Low', 'Low'), ] priority= models.CharField(max_length=6, choices=priority_choices, default='Low') #new field def __str__(self): return self.title serializers.py from rest_framework import serializers from .models import Todo class TodoSerializer(serializers.ModelSerializer): class Meta: model = Todo fields = ('id', 'title', 'description', 'completed', 'priority') views.py class TodoView(viewsets.ModelViewSet): serializer_class = TodoSerializer queryset = Todo.objects.all() I just want the simplest solution, preferably to just update TodoSerializer(serializers.ModelSerializer) class inside serializers.py so that it would all come from this one Model. Is that possible? Reading https://www.django-rest-framework.org/api-guide/fields/#choicefield is not clear for me whether I need … -
Django Form Not Saving the Data
I've imported this from django.contrib.auth.forms import UserCreationForm used csrf_token in the form but still when I hit submit the page reloads but doesn't save the data to database def signup(req): if req.method == 'POST': form = UserCreationForm(req.POST) if form.is_valid(): form.save() form = UserCreationForm() reg_con={ 'regform': form } return render(req, 'signup.html', reg_con) <form action="." method="POST">{%csrf_token%} {{regform.as_ul}} <input type="submit" value="Sign Up"> -
Django: What's the difference between Queryset.union() and the OR operator?
When combining QuerySets, what's the difference between the QuerySet.union() method and using the OR operator between QuerySets |? Consider the following 2 QuerySets: qs1 = Candidate.objects.filter(id=1) qs2 = Candidate.objects.filter(id=2) How is qs1 | qs2 different from qs1.union(qs2)? Is there some subtlety under the hood that I'm missing? -
Evaluating Django QuerySet is fast, but still consumes a lot of server time
Using Django Query Profiler, I get the following results when loading my page. My query only takes 48ms to run, but the total server time is nearly 2 seconds! I have been able to verify that the query is fast by printing out the raw query and then running it manually. The relevant code in my ListAPIView view looks like: def get_queryset(self): start = time.perf_counter() queryset = MyModel.objects.all() \ .prefetch_related( # Prefetch related fields ).defer( # Don't select these fields ) print(len(queryset)) end = time.perf_counter() print(f"Evaluation time: {(end - start):.2f}s") return [ # Return hardcoded JSON result with single value to eliminate other factors ] The print(len(queryset)) statement is where the evaluation occurs. For some reason, this takes almost 2 seconds to complete, but only 48 ms of it is spent on the database. For some perspective, there are only 11 rows in MyModel. I wanted to rule out the possibilities that the server time was due to transforming the data, serializing the data, etc., so I am just returning a single JSON object. Given that all the other views in my application work just fine, I see no reason the server time can't be at least 10x faster. Any … -
How to use the AJAX with DJANGO appropriately?
I am a newbie in web dev and I know how to use the AJAX with DJANGO but i want to know what method is going to be the best one i use the script tags within my html files because they allow me to use DTL for urls but the time when use them I feel I'm doing something bad about design. Any guidelines what is standard way of writing a clean code which will be more usable? -
Why does django-channels not connect to secure Websockets wss?
I am trying to deploy my django = app to heroku. All features work except for the chat which uses Websockets. Keep in mind all everything works on my local machine. The problem has to do with wss vs ws on my server I the ChatConsumer does not connect when the websocket url starts with wss Here's my code on the browser: var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws"; const chatSocket = new WebSocket( ws_scheme + '://' + window.location.host + '/ws/chat/' + friendship_id + '/' ); here's asgi.py import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DBSF.settings") import django django.setup() from django.core.management import call_command from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack import social.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DBSF.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( social.routing.websocket_urlpatterns ) ), }) here's routing.py from django.urls import re_path, path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/(?P<friendship_id>\w+)/$', consumers.ChatConsumer.as_asgi()), ] here's consumers.py import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer from .models import Message, Friendship, User import datetime class ChatConsumer(WebsocketConsumer): def connect(self): print('fuuuuuuuu') self.room_name = self.scope['url_route']['kwargs']['friendship_id'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name … -
Problem in deleting a package from a docker container (python)
I'm building a django api on a docker container. I change my mind about one of the dependencies. But when I try pip uninstall this happens: docker exec django-api-container_web_1 pip uninstall djangorestframework-api-key==2.0.0 Found existing installation: djangorestframework-api-key 2.0.0 Uninstalling djangorestframework-api-key-2.0.0: Would remove: /usr/local/lib/python3.9/site-packages/djangorestframework_api_key-2.0.0.dist-info/* /usr/local/lib/python3.9/site-packages/rest_framework_api_key/* Proceed (y/n)? ERROR: Exception: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/pip/_internal/cli/base_command.py", line 224, in _main status = self.run(options, args) File "/usr/local/lib/python3.9/site-packages/pip/_internal/commands/uninstall.py", line 89, in run uninstall_pathset = req.uninstall( File "/usr/local/lib/python3.9/site-packages/pip/_internal/req/req_install.py", line 686, in uninstall uninstalled_pathset.remove(auto_confirm, verbose) File "/usr/local/lib/python3.9/site-packages/pip/_internal/req/req_uninstall.py", line 397, in remove if auto_confirm or self._allowed_to_proceed(verbose): File "/usr/local/lib/python3.9/site-packages/pip/_internal/req/req_uninstall.py", line 440, in _allowed_to_proceed return ask('Proceed (y/n)? ', ('y', 'n')) == 'y' File "/usr/local/lib/python3.9/site-packages/pip/_internal/utils/misc.py", line 247, in ask response = input(message) EOFError: EOF when reading a line I don't have the opportunity to delete the dependencies. And also I don't want to just recreate the container because of this. Any ideas? -
Sending Django email through Postfix as a relay to Mailjet
I have a Django project on Ubuntu and I setup Postfix to send emails through Mailjet following this article. That works good to send message from the command line or scripts using mail. I am currently using django-anymail to send Django messages through Mailjet and it works but I was wondering if I could avoid the django-anymail dependency since I got Postfix to send messsages through Mailjet, but I could not make it work. The goal I guess is to safely allow SMTP to relay the Django messages from localhost, which is not enabled by default. The Django config I tried is: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'localhost' EMAIL_PORT = 587 EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS = True Not sure how to congig Postfix though. -
Updating a Boolean Field in Django database
can i please get an help in what i'm doing wrong? i have a boolean field in which i want when a user clicks on it, it updates in the database, but i can't achieve my aim. my code is below for better understanding models.py class OrderItem(models.Model): designer_size = models.ForeignKey("Frame_Sizes_Designer", on_delete=models.CASCADE, blank=True) ***** class Frame_Sizes_Designer(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) small = models.BooleanField(default=False, blank=True) def __str__(self): return self.user.username views.py def DesignerFrameSizeSmall(request): dss = get_object_or_404(OrderItem, id=request.POST['id']) dss.designer_size.small = not dss.designer_size.small dss.save() messages.info(request, "Your prefered size has been stored... Thanks") return redirect('business:summary') app_name = 'business' urlpatterns =[ path('designer_frame_small_size/', DesignerFrameSizeSmall, name='dfss'), ] html and js <form action="" method="POST"> {% csrf_token %} <input type="checkbox" id="designer_small" value="{{dss.designer_size.small}}"> <label>Small</label> </form> $(document).ready(function(){ $('#designer_small').change(function(){ $.post("{% url 'business:dfss' %}",{ id: "{{items.id}}", designsmall: this.checked, csrfmiddlewaretoken: '{{csrf_token}}' }); }); the error message i get is internal server error when i check my console and i also get an error in my command prompt dss.designer_size.small = not dss.designer_size.small AttributeError: 'NoneType' object has no attribute 'small' }); -
Format django_filters form
I've been trying for the last few days to format a django_filters filter form. For this I make a class where I define the filters and then I make another child class where I try to format using FormHelper() and Layout() . That child class is the one I use in my view. But the filter form does not come out with the correct formatting. What am I doing wrong? Why my form is not coming with the correct format? I am also using crispy forms. filters.py class DeviceFilter(django_filters.FilterSet): device_group = django_filters.ModelChoiceFilter(label='', lookup_expr='exact', field_name='device_group__pk', queryset=None, empty_label=('Select Group')) device_type = django_filters.ModelChoiceFilter(label='', lookup_expr='exact', field_name='device_type__pk', queryset=None, empty_label=('Select Type')) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.filters['device_type'].queryset = DeviceType.objects.filter(owner=self.request.user) self.filters['device_group'].queryset = DeviceGroup.objects.filter(owner=self.request.user) class Meta: model = Device fields = {} # HERE I TRY TO GIVE THE FORMAT. BUT IT IS NOT WORKING class CustomFilterForm(DeviceFilter): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Row( Column('device_type', css_class='form-group col-6 mb-0'), Column('device_group', css_class='form-group col-6 mb-0'), css_class='form-row' ), ) views.py class DeviceListView(OwnedMixin, SingleTableMixin, FilterView): model = Device template_name = 'devices/list.html' table_class = DeviceTable filterset_class = CustomFilterForm paginator_class = LazyPaginator def post(self, request, *args, **kwargs): queryset = request.POST for i in queryset['list'].split(","): if queryset['action'] == 'delete': … -
Test and Verify AWS Redis Integration with Django project
I am new to Django. I was trying to implement Redis cache system into my Django project. I am using AWS free tier to host my Django project on EC2 machine using gunicorn web server and trying to integrate AWS Redis Cache. I have added below entry in my settings.py file: CACHE = { 'default': { 'BACKEND' : "redis_cache.cache.RedisCache", 'LOCATION' : "redis://xxx.xxx.xxxxx.cache.amazonaws.com/1", 'OPTIONS' : { 'CLIENT_CLASS' : 'redis_cache.client.DefaultClient', }, } } And below is my view function: def usertable(request): obj = userdetails.objects.get(id=1) name = obj.name if cache.get(name): cache_name = cache.get(name) print ("From CACHE") else: cache_name = obj.name cache.set(name, cache_name) print ("*****************FROM DB********************") context = { 'name' : cache_name, } This code is working for me and I can see From CACHE printed in my terminal. But the key value pair which is set if I manually connect to redis using below cli tool: redis-cli -h xx.xx.xxxxx…cache.amazonaws.com -p 6379 -n 1 on giving keys * I do not see any key value pair is set. I am not sure if this is the correct way to test integration of Redis cache. Kindly advice if anyone had tried Redis Cache system. -
How to pass a variable inside a fetch() for static files in Django?
I'm developing an app that displays Highcharts charts in Django and the graph is typically created by reading the content of a JSON file stored in my static files like so: fetch("{% static 'myfile.json' %}") .then(......) Now I've got a dropdown list from which the user can select the json file name and I'd like to pass it to the fetch() function, but I can't figure out how to make it work. For instance: var resultStr = "{% static 'myfile_with_id_XX.json' %}"; fetch(resultStr) .then(.....) this returns a GET 404 error instead of fetching the appropriate json file. How should I format resultStr so that it can be passed in fetch()? And how should I write the fetch() function ? Many thanks for your help! -
Celery - Django Schedule task from inside a scheduled task
I have a Task (let's call it MainTask) that is scheduled using apply_async method, this task has some validations that can trigger another task (SecondaryTask) to be scheduled with an eta. Every time the MainTask tries to schedule the SecondaryTask using apply_async method, the SecondaryTask runs inmediatly, overriding the eta parameter. How can I schedule a different task from a "Main Task" and to be executed later, using eta? Here is an example of the code: views.py def function(): main_task.apply_async(eta=some_day) tasks.py @app.task(bind=True, name="main_task", autoretry_for=(Exception,), default_retry_delay=10, max_retries=3, queue='mail') def main_task(self): ... if something: ... another_task.apply_async(eta=tomorrow) @app.task(bind=True, name="another_task", autoretry_for=(Exception,), default_retry_delay=10, max_retries=3, queue='mail') def another_task(self): do_something() -
DRF: Simple Switch for a choice field in model via router
I want to build an APIView that can turn on power in a store so to say ... Can I do it using a router? model: class Store(models.Model): C = [(0,0), (1,1), (2,2), (3,3)] name = models.IntegerField("name", max_length=60) power_state = models.PositiveIntegerField("current state", default=0, choices=C) user = models.ForeignKey(User, on_delete=models.CASCADE) view: class OnOff(APIView): def patch(self, request): store = Store.objects.get(pk = request.user.id) return Response("switched") I am new to DRF and I do not know if I need a serializer here. The interface I see looks like this: while I was hoping for a simple dropdown between 0 and ... 3 in this case. Also how would the router have to be registered? Right now I put a path in the urls.py: path('test/', views.OnOff.as_view(), name = "on-off"), which means it will not be listed under 127.0.0.1:8000/api/ which would be nice. I tried using (but 404): router = routers.DefaultRouter() ... router.register(r'onoff', views.OnOff, basename = "onoff") urlpatterns = [ path("", views.StoreView.as_view(), name = 'index'), url('^api/', include(router.urls)), ... ] -
Django VSCode: How to make django-html format as expectedl?
I've seen a ton of unanswered questions about VSCode formatting (and if not here, where do you ask these questions?). There are 2 main issues I run into constantly when I'm trying to write django-html templates. 1. Basic HTML tag linebreak doesn't occur in django-html files. When you write an html tag, and press enter inside of it, it should split the tag with an empty line in the middle like. Expected behavior (pipe "|" represents the cursor): <!-- Write the tag --> <div>|</div> <!-- Press enter --> <tag> | </tag> Here's what's happening in the django-html file after enter: <!-- Press enter --> <tag> |</tag> How do you fix this WITH proper template tag formatting (below)? 2. Django template tags don't indent as expected. Tags within if, with, block, etc. tags should be indented. (treated like html) Expected result: <!DOCTYPE html> <html> <head> </head> <body> {% if x %} <p>I did x</p> {% else %} <p> I did else</p> {% endif %} <nav class="navbar"> </nav> {% block content %} <div class="content"> <p>I'm in contente</p> </div> {% endblock %} </body> </html> Instead, the html tags within the django template tags are flattened on the same indent level. Actual result: <!DOCTYPE … -
Django JavaScript template block
I'm learning Django and JS and jQuery all at the same time for a project I'm working on, and I'm having trouble with running JavaScript in a Django template block OTHER THAN {% block content %}. I've seen several tutorials use a {% block javascript %} template block for JavaScript, but I can only get my JavaScript to run if I include it in the {% block content %} block of the html file. If I include it in a like I've seen in the tutorials, it doesn't work (and neither do other functionalities, like html tags). Here's my base template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>{% block title %}{% endblock title %}</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> {% block style %} {% endblock style %} </head> <body> {% block content %} {% endblock content %} {% block javascript %} {% endblock javascript %} </body> </html> This works: {% extends 'base.html' %} {% block content %} {% load static %} <div class="container-fluid"> <form id="med_input_form"> <div class="form-group" > {% csrf_token %} <label for="{{form.input_meds.id_for_label}}">{{form.input_meds.label}}</label> {{form.input_meds}} </div> <button type="submit" class="btn btn-primary">Reconcile Meds</button> </form> </div> <div class="container-fluid"> <ul id="med_output"> </ul> …