Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery should return a non-zero exit code an exception occurs
I'm experiencing a weird situation with Celery 4.1, Python 2.7.13. When there is an issue with the connection between Python app and Database (MySQL in this case), Celery does not return a non-zero code and keep the worker running which doesn't make any sense. Although I can see the exception in the result of celery -A myapp worker -l INFO -E but the worker doesn't stop. I tried almost all options of celery worker but no luck. Is there any way to force the worker to stop working and exit if the database connection is failing? -
Trigger bootstrap modal after django form submission
How can I trigger the bootstrap modal to popup after my django form was submitted? In my index.html template I have a standard looking modal like this <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> below in the same index.html I have a django form {{ form.non_field_errors }} {% csrf_token %} <ul id="robul"> <div class="form-group"> <div class="col-xs-6"> <li id="name" name="{{ form.name.name }}" class="form-control">{{ form.name }}</li> </div> </div> <div class="form-group"> <div class="col-xs-6"> <li id="email" class="form-control">{{ form.email }}</li> </div> </div> <div class="form-group"> <div class="col-xs-6"> <li id="contactmessage" class="form-control">{{ form.contactmessage }}</li> </div> </div> </ul> in my view.py it looks like this: if request.method == 'POST': form = forms.FormName(request.POST) if form.is_valid(): contact_name = request.POST.get( 'name', '') contact_email = request.POST.get( 'email', '') form_content = request.POST.get('contactmessage', '') template = get_template('contact_template.txt') context = {'name': contact_name, 'email': contact_email, 'contactmessage': form_content,} content = template.render(context) mail = EmailMessage("New contact form submission", content, "Some Name" +'', ['somegmail@gmail.com'], headers = {'Reply-To': "noreply@gmail.com" }) mail.send() return render(request, 'index.html', {'form': form}) -
Django (v2.0.1) form Creation and pulling data's from DB
I am learner and started using django framework for a small project. I am struggling to create a form and pulling values from the DB. I have a table "travel" in my DB which has the following fields in it. ID, customer_name, travel_date, billing_status, created_at, updated_at 1, Robin Hood, 2018-01-10, Paid, 2018-01-10 15:29:25, 2018-01-10 15:29:25 Now I wanted to have a form with the above fields which should pull all the records from the database "travelmanager" and table "travel". If someone could, provide me an example with the above details. That could be very very helpful. Thank you in advance. -
Combine two querysets from different models into one queryset
I need to combine two querysets into one queryset (the result can't be a list or other type of object) as when I iterate on the querysets in a template I need to access their relations, which cannot be done from a list or dictionary. I've tried solutions like union however this is unacceptable as I need access to the relations in the template. The loop that I need the data structure for looks like the loop below. The two relations on this object are user and aircraft. {% for key in active %} <tr> <td>{{key.user.name}}</td> <td>{{key.aircraft.tail_number}}</td> <td>{{key.departure_date}}</td> <td>{{key.departure_city|title}}</td> <td>{{key.arrival_city|title}}</td> </tr> {% endfor %} One idea is to somehow do a join between the two tables in a way that a queryset is returned however at this point I've been unable to figure out how to do that. I haven't tried raw SQL yet so maybe that's the route? -
Add a field to a model in the view
I would like to add the field unread to a chat model in the view. The field unread needs to be computed first and depends on another model called chatmessages. Right now unread can only be requested separately from a chat via detail_route: class ChatViewset(ModelViewSet): ... @detail_route(methods=['get'], ) def unread(self, request, pk): chat = self.get_object() assert isinstance(chat, Chat) all_messages = ChatMessage.objects.filter( Q(in_chat__first_participant=request.user, in_chat__blocked_by_first_participant=False) | Q(in_chat__second_participant=request.user, in_chat__blocked_by_second_participant=False), in_chat=chat) all_unread_messages = all_messages.filter( Q(in_chat__first_participant=request.user, sent_by_first_participant=False, read_by_receiver=False) | Q(~Q(in_chat__first_participant=request.user), sent_by_first_participant=True, read_by_receiver=False)) return Response({'unread': all_unread_messages.count()}) def list(self, request, *args, **kwargs): self.serializer_class = ChatSerializer return super(ChatViewset, self).list(request, *args, **kwargs) def retrieve(self, request, *args, **kwargs): self.serializer_class = ChatSerializer return super(ChatViewset, self).retrieve(request, *args, **kwargs) ... How could I integrate unread into the view of chat? -
web application frontend & backend queries [on hold]
I'm on a project to create a web app for tribal people in my country.As Iam a beginner in web development,Iam not familiar with those web app frameworks which includes both front-end and backend.Moreover I should create these with open-source tools.I will list down the tools which I have in my mind for creating the app. Front-end: Languages:HTML,CSS,Javascript Frameworks:Angular JS,Bootstrap Texteditor:Sublime (or) Atom Backend: Languages:php/Javascript/python Framework:phpmyAdmin/node.js/django Database:MySQL/MongoDB API: - dialogflow-for chatbot - WYSIWYG text editor I have attached my abstract,click here. Iam very confused with the backend languages and frameworks.How to choose the right one for me? Now I require suggestion/advice regarding the following questions As a beginner,what framework do I choose for both front end & backend based on my above specified requirements? What database do I use based on above requirements(MySQL/MongoDB)? In my project,"article" module click hereis very difficult.It is just like "medium" or "quora" newsfeed.I could not get even a little spark of how to build? What resources can I use for creatng my project other than github? -
Django - - OSError: dlopen() failed to load a library: cairo / cairo-2 -- Continues to Appear Even After Downloading GTK+ Bundle 3.10.4
After installing WeasyPrint, I am getting this error: "Error in Django: OSError: dlopen() failed to load a library: cairo / cairo-2" Here are all the details: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0420DE40> Traceback (most recent call last): File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 254, in check for pattern in self.url_patterns: File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File … -
POST a conditional select using django-chosen
I'm a beginner developer and I'm trying to get my form to POST the results of my chosen option to the submitted URL as a list. I have a form that has a selection option the user will select an access level. <form action = "{% url 'submitted' %}" form method = "POST"> {% csrf_token %} <div class="container"> <div class="row"> <div class="col"> {% if showbutton is not None %} <label for="accesslevel"><h3>Access Level</h3></label> <select name ="accesslevelid" class="form-control my_select" id="accesslevelid"> <option value=""> Please select your access level </option> <option value="7"> Facility </option> <option value="5"> Division </option> <option value = "3"> Corporate </option> <option value = "6"> Market </option> <option value = "4"> Group </option> </select> </div> After the access level is selected a chosen.js multiple select box will display, this is handled by the following javascript. $('.chosen-select').chosen({}).change(function (obj, result) { console.debug('changed: %o', arguments); console.log('selected: ' + result.selected); }); $(document).ready(function () { $('#accesslevelid').change(function () { $this = $(this) $('.content_box').each(function () { $select = $('select', this); if ($select.data('id') == $this.val()) { $(this).show(); $select.show().chosen(); } else { $(this).hide(); $('select', this).hide(); } }); }); }); I use the following Django template which follows the select an access level template and is in the same form. {% … -
Why am I unable to do pip install django?
I get this error when I run pip install django: Collecting django Using cached Django-2.0.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "c:\users\shing_~1\appdata\local\temp\2\pip-build-eljct4\django\setup.py", line 32, in <module> version = __import__('django').get_version() File "django\__init__.py", line 1, in <module> from django.utils.version import get_version File "django\utils\version.py", line 61, in <module> @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' ----------------------------------------- Command "python setup.py egg_info" failed with error code 1 in c:\users\shing_~1\appdata\local\temp\2\pip-build-eljct4\django\ This is the first time I've gotten any error using pip install. What am I doing wrong? -
reseting the password using django authentication
when I try to use Django's built-in password reset system. it does not take my templates into account. Moreover, when I click the reset password button then it takes me to the Django admin reset page(photo). My the file map my urls.py:- from django.conf.urls import url from django.contrib.auth import views as auth_views from . import views app_name = 'accounts' urlpatterns = [ url(r"^login/$", auth_views.LoginView.as_view(template_name = "accounts/login.html"),name='login'), url(r"^logout/$", auth_views.LogoutView.as_view(template_name='thanks.html'), name="logout"), url(r"^signup/$", views.SignUpView, name="signup"), url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',views.activate, name='activate'), url(r'^password_reset/$', auth_views.PasswordResetView.as_view(template_name='registration/password_reset_form.html'), name='password_reset'), url(r'^password_reset/done/$', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), url(r'^reset/done/$', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] The Templates:- password_reset_form.html {% extends 'reg_base.html' %} {% load bootstrap3 %} {% block body_block %} <h3 class="display-1">Forgot password</h3> <form method="POST"> {% csrf_token %} {% bootstrap_form form %} <button class="btn btn-primary" type="submit">Submit</button> </form> {% endblock %} password_reset_confirm.html {% extends 'reg_base.html' %} {% load bootstrap3 %} {% block body_block %} {% if validlink %} <h3 class="display-2 text-center">Change password</h3> <form class="form-control" method="post"> {% csrf_token %} {% bootstrap_form form %} <button class="btn btn-default" type="submit">Change password</button> </form> {% else %} <p class="lead"> The password reset link was invalid, possibly because it has already been used. Please request a new password reset. </p> {% endif %} {% endblock %} -
Redirect the output of custom Django command to the browser
I have created a custom command which takes a positional and a named optional argument. It does many checks, downloads a file, unzips it and populates the database with the unzipped data. To make the things more convenient for the users I created a simple form and created a view: from django.views.generic.edit import FormView from django.core import management from .forms import DownloadForm class DownloadFormView(FormView): template_name = 'frontend/download.html' form_class = DownloadForm success_url = '.' def form_valid(self, form): country = form.cleaned_data['country'][:3] levels = int(form.cleaned_data['country'][-1:]) management.call_command('download_shapefile', country, levels=levels) return super(DownloadView, self).form_valid(form) That works fine and now I want to provide feedback to the user, as the command might run for a while. Is there any possibility to redirect the command output (or make it available) to the template and display it in the browser? In my command I use: self.stdout.write(self.style.SUCCESS('some success message')) self.stdout.write(self.style.WARNING('some warning message')) to output messages and don't print directly with the print method. -
Django : execute command collectstatic raise UnicodeDecodeError4
In this link enter link description here Is my error, but I not have solution .please help me. -
Querying, reading from a JSONField in PostgreSQL using Django
I am new to Django.. I have a requirement where I need to store a person's name and a they're blood pressure readings. I have made up a Django application and I can store this information information in PostgreSQL. My question is how can read the specific JSONField out to the console? I want to retrieve all JSON data. Here is my models.py file: from django.contrib.postgres.fields import JSONField from django.db import models class ABPM(models.Model): name = models.CharField(max_length=128, null=False, blank=True) bpData = JSONField(null=True) def __str__(self): return self.name JSON data stored in Postgre Database: bpData // field name jsonb // datatype {"sbpReading":["sbp",117],"dbpReading":["dbp",75],"mapReading":["map",98],"hrReading":["hr",73]} I want to print out all values to the console using Django Database API based on the persons name? The following CMDS do not work: ABPM.objects.all() // only returns names ABPM.objects.filter(name='some persons name..', bpData__contains={'sbpReadings', 'sbpReadings', 'mapReadings', 'hrReadings'}) Any help would be great.. -
convert php web application installed in usb to django web app
For my work i need to convert php to django. I know Django well, but php i don't have any experience. can you help me if you know some technologies to convert easier, and for your information our custumor give us the old web php application in the usb ^^ Thank you -
Template rendering is wrong, category shows 2 times
So I am trying to render my models in a template but just one tiny thing shows more times than I expect. I just want category name to show one time for many lectures. I just cant figure where to modify the template code. <ul> {% for a in categories %} {% for c in lectures %} {% if a == c.course_category %} <li><strong>{{ a.course_category }}</strong></li> {% endif %} {% if a == c.course_category %} <li>{{ c.lecture_title }}</li> <li>{{ c.content }}</li> {% if c.link %} <li>{{ c.link }}</li> {% endif %} {% if c.file %} <li><a href='{{ MEDIA_URL }}{{ c.file.url }}'>download</a></li> {% endif %} {% endif %} {% endfor %} <hr/> {% endfor %} </ul> -
Is it possible to have django apps in their own docker container and manage/interact with them?
Is it possible to have each app in a django project in its own docker container? this way 1- All the dependencies of the app is contained to itself and there wont be any dependency conflicts between two apps. 2- In our project we are discussing a use case where apps should deployed in containers(primary and backup) such that when the primary goes down the backup takes over .. basically implementing High availability(HA) of an app. I know that this may not exactly be a use case that Django was built to solve, but if it is doable in Django then i would like to do it using django as we have already created lot of apps using django and changing the architecture for the sake of HA would be a lot of work. Note: I understand that the whole project can be deployed in a container and HA can be implemented.. but i'm more interested distributing apps in containers. -
Gunicorn queue wait time
My setup is nginx => gunicorn => django. I am using gunicorn with sync workers. Can I find out how long requests take till they find an available gunicorn worker? I will use this measure to find out if I have too little workers and thus increase the count, does that make sense? I have the RAM available, as currently I am only using 50% of it, but if they aren't queued up I will use the RAM for something else. Can I somehow tell nginx or gunicorn master to annotate the wait time in queue? -
Django : how to display inline admin in the "child" admin of a OneToOne relation?
I have two models related via OneToOne field : class Appendix(Model): name = models.CharField(max_length=300) class Main(Model): name = models.CharField(max_length=300) appendix = models.OneToOneField(Appendix, on_delete=models.CASCADE, related_name='main') I'm trying to make Appendix editable from inside the Main django admin. However since Main is considered the "child" this doesn't seem possible with the current Django inline. This was brought up in a comment to this similar question but there is no answer beyond "change ownership of the key field". I've considered switching the ownership of the foreign key but this would complicate much of the rest of my code (in that all other operation I want to do seem easier with it this way). Is there a way around this? -
Django project creation error
PS C:\Users\shubham\Desktop> django-admin startproject ecom Traceback (most recent call last): File "C:\Python36\Scripts\django-admin-script.py", line 11, in load_entry_point('django==2.0.1', 'console_scripts', 'django-admin')() File "c:\python36\lib\site-packages\django-2.0.1-py3.6.egg\django\core\management__init__.py", line 371, in execute_from_command_line utility.execute() File "c:\python36\lib\site-packages\django-2.0.1-py3.6.egg\django\core\management__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\python36\lib\site-packages\django-2.0.1-py3.6.egg\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "c:\python36\lib\site-packages\django-2.0.1-py3.6.egg\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "c:\python36\lib\site-packages\django-2.0.1-py3.6.egg\django\core\management\commands\startproject.py", line 20, in handle super().handle('project', project_name, target, **options) File "c:\python36\lib\site-packages\django-2.0.1-py3.6.egg\django\core\management\templates.py", line 117, in handle django.setup() File "c:\python36\lib\site-packages\django-2.0.1-py3.6.egg\django__init__.py", line 16, in setup from django.urls import set_script_prefix File "c:\python36\lib\site-packages\django-2.0.1-py3.6.egg\django\urls__init__.py", line 1, in from .base import ( File "c:\python36\lib\site-packages\django-2.0.1-py3.6.egg\django\urls\base.py", line 8, in from .exceptions import NoReverseMatch, Resolver404 File "c:\python36\lib\site-packages\django-2.0.1-py3.6.egg\django\urls\exceptions.py", line 1, in from django.http import Http404 File "c:\python36\lib\site-packages\django-2.0.1-py3.6.egg\django\http__init__.py", line 5, in from django.http.response import ( File "c:\python36\lib\site-packages\django-2.0.1-py3.6.egg\django\http\response.py", line 13, in from django.core.serializers.json import DjangoJSONEncoder File "c:\python36\lib\site-packages\django-2.0.1-py3.6.egg\django\core\serializers__init__.py", line 23, in from django.core.serializers.base import SerializerDoesNotExist File "c:\python36\lib\site-packages\django-2.0.1-py3.6.egg\django\core\serializers\base.py", line 201 def save(self, save_m2m: object = True, using: object = None, kwargs: object) -> object: ^ SyntaxError: non-default argument follows default argument -
django get list of objects from query set
I have a model which has a CharField named as answer , it has only four options which it saves as a,b,c,d .Now in My views i want to write a query that can return the list of these options..I have tried the code below Here b is the list of ld for which we want the list. platform = get_object_or_404(Platform, user=request.user, test_key=article) b = json.loads(platform.list) ans = list(Upload.objects.filter(id__in=b).values_list('answer',flat=True)) Now this gives me the output as [(u'a',), (u'b',), (u'c',), (u'b',), (u'c',), (u'b',), (u'c',)] bu i can't use this list . I want the output as [a,b,c,b,c,b,c] kindly tell me how to get the list of objects -
Celery doesn't see tasks when django DEBUG is set to False
I've got a Django application with Celery. Tasks are described in tasks.py files with @shared_task in different apps, each has its own AppConfig and is being installed (added to INSTALLED_APP) correctly. Everything worked fine until I turned DEBUG off. Celery started to fail due to tasks of unregistered type. With the DEBUG variable Celery can see all of my tasks and work correctly. What can cause such a bug? -
How acess and modify SearchQuerySet(WayStack)?
I having some issues with waystacks. when i nitialize with my model that giving me a list with type SearchQuerySet: def sqs_query(self, sqs): q = self.request.QUERY_PARAMS.get('q', '') results = sqs.filter(content=q) pdb.set_trace() return results def get_queryset(self): sqs = self.sqs_query(self.sqs_models(SearchQuerySet())) return sqs (pdb) type(results) <class 'haystack.query.SearchQuerySet'> I can acess the position 0: (pdb) results[0] <SearchResult: article.article (pk=u'5')> But i can't assign: (pdb) results[0] = results[1] *** TypeError: 'SearchQuerySet' object does not support item assignment I need to modify the positions of the list. -
Bootstrap datetime picker in django modelform for one input
I need to use datetime picker in my django app. After I used it as it is described everywhere the result is incorrect - it doesn't work. Calendar shows on top of the page and doesn't populate the target field at all. forms.py: class addOrderForm(ModelForm): class Meta: model = Orders fields = [ 'shipvia', 'customer', 'employee', 'orderdate', 'freight', 'shipname', 'shipaddress', 'shipcity', 'shipregion', 'shippostalcode', 'shipcountry' ] DATEPICKER = { 'type': 'text', 'class': 'form-control', 'id': 'datetimepicker1' } widgets = { 'orderdate': forms.DateInput(attrs=DATEPICKER) } views.py: def addOrder(request): OrderDetailsFormSet = inlineformset_factory(Orders, OrderDetails, fields=('product', 'unitprice', 'quantity' , 'discount'), can_delete=False, extra=3) order=Orders() if request.method == 'POST': f = addOrderForm(request.POST, instance=order) if f.is_valid(): order = f.save(commit=False) if fs.is_valid(): fs = OrderDetailsFormSet(request.POST,instance=order) order.save() fs.save() return HttpResponse('success') else: f = addOrderForm(instance=order) fs = OrderDetailsFormSet(instance=order) return render(request, 'orders/addOrder.html', context = {'fs': fs,'f':f,'order':order}) orders/addOrder.html: <form action="/orders/addOrder/" method="post"> {% csrf_token %} <table> <div class="container"> <div class="row"> <div class='col-sm-6'> <div class="form-group"> <div class='input-group date' id='datetimepicker1'> {{ f.as_table }} <span class="input-group-addon"> <span class="glyphicon glyphicon-calendar"></span> </span> </div> </div> </div> <script type="text/javascript"> $(function () { $('#datetimepicker1').datetimepicker({ inline: true, sideBySide: true, format: 'YYYY-MM-DD', }); }); </script> </div> </div> </table> I have tested few modifications and when django form has been moved under spans then all text input … -
How can you add environment variables in a Jenkins Multibranch Pipeline
I am working on a Django project, I have integrated it withJenkins Multibranch Pipeline. I cannot inject environment variables by the Multibrach Pipeline option even after installing the Environment Injector plugin. I have evironment variables like DB_PASSWORD that must be included in the envvars. Any insight will be highly appreciated. -
Django geting error when loading static files?
I have the code below to load static files, but I keep getting a TemplateSyntaxError. Does anyone know how I can fix this issue? Template: {% load staticfiles %} <a href=""><img class="logo" alt="" src='{% static "images/logo.png"%}' width="110"></a> Settings: INSTALLED_APPS = [ ..., 'django.contrib.staticfiles', ] STATIC_URL = '/public/' STATIC_ROOT = os.path.join(BASE_DIR, "public") URLS: urlpatterns = [ ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Error I get: Invalid block tag on ...: 'static', expected 'endblock'. Did you forget to register or load this tag?