Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django serving static files even with Debug off and no web server set to serve
Based on all I've read in the docs and on various s/o questions, Django cannot serve static files in production (when DEBUG = False) and they have to be served by a web server. Yet, when I run my code my static files are showing up just fine even with debug turned off. This concerns because as we move to production, I can't imagine it will continue to serve those files without me setting it up so they're served by a web server and I don't want my dev environment to not give me an accurate picture of how it will work in production. How is it possible that my app is serving static files without a web server with DEBUG = False? I've included the relevant blurbs in my settings.py file and my command to collectstatic in my Dockerfile. It also serves the static files just fine when I have RUN python manage.py collectstatic and STATIC_ROOT commented out. settings.py STAT = os.path.join(BASE_DIR, 'static') DEBUG = False STATIC_URL = '/static/' STATICFILES_DIRS = [STAT] STATIC_ROOT = os.path.join(BASE_DIR, 'prod_static') Dockerfile RUN python manage.py collectstatic --noinput -
How to make dynamically URLs with Django
my new project needs to fetch URLs from database. Example: Backend add Categorys and URLs should work like: www.example.com/hardware if I make in Backend a new subcategory: www.example.com/hardware/notebooks If I add a article: ww.example.com/hardware/notebooks/lenovo-e410 or articlenumbers. But I didnt find out where I can add urls from SQL Queries. -
Extract month or year from mongo Datetime filed in Django
im using monogengine in my Django project and i want count() number of jobs in each year and each month. after each time users do some jobs, it will insert and save in my Database nicely. now i want to count them and use this number later in some charts in year-month format. this is my model from mongoengine import Document, EmbeddedDocument, fields class PortModel(EmbeddedDocument): idx=fields.StringField() protocolname=fields.StringField() protocolnumber=fields.StringField() description=fields.StringField(required=False, blank=True) class PortScanModel(Document): date=fields.DateTimeField() host=fields.StringField() ip=fields.StringField() Ports=fields.ListField(fields.EmbeddedDocumentField(PortModel)) i want something like group_by just on year and month for counting rows and extract how much users used it. my Date field is something like '2019-12-02T19:47:31.847170' and i want something like below: year-month | number of rows --------------------------- 2018-01 | 2 2018-02 | 7 2019-01 | 3 2019-05 | 14 i searched a lot for extracting year and month from date, but nothing i found. i don't know can i Extracting and Grouping in one Command or not in mongo, but it wasn't hard in SQL. thanks for your helps. -
How to list wagtail pages in Django template?
I have a site that is mostly made with Django but has a few content pages that need to be managed by Wagtail. How can I link to the pages created with Wagtail in Django templates? I don't want to have to hardcode any of the pages. The client should be able to make a page in Wagtail and a link should be created to that page in Django templates. The problem is that I don't know how to reference Wagtail pages through Django templates. -
How to Validate and Compare Data against the Database in DetailView - Django
I have a ChallengeDetailView which shows the details of a challenge like a blog post. I also have a form field on the same page and it supposed to get an answer of a challenge, and compare it to the database. So far here is what I did; class ChallengeDetailView(DetailView): model = Challenge def get_context_data(self, **kwargs): context = super(ChallengeDetailView, self).get_context_data(**kwargs) context['form'] = FlagForm return context class FlagFormView(): form_class = FlagForm success_url = reverse_lazy('challenge-detail') I try to implement a simple logic like the following; def get_flag(self, request): if self.request.method == 'POST': form = FlagForm(request.POST) if form.is_valid(): flag = form.cleaned_data.get('flag') if flag == Challenge.flag: return messages.success("You found the flag!") else: return FlagForm() I tried to include this in form_valid() method but couldn't make it work in the ChallengeDetailView. I'm open to any kind of suggestions. I'm coming from a Symfony background and pretty new to Django. -
Django model field for file system directory path
In the Django model field types reference I could not find a field for a file system directory path. With custom model fields it's possible to implement this. What should be considered w.r.t. validation? Can I extend Django's builtin model field types with a package? -
Django with cms model
hi i'm making a cms in django. I want users to be able to create pages from the admin panel. My model is like this, page properties -> designs on page -> data of designs. but I am doing too much database operation how do I optimize. I've reviewed Wordpress. I didn't quite get it. # Create your Page Models. class Page(models.Model): ID = models.BigAutoField(primary_key=True) page_title=models.TextField() page_contentmeta = models.ManyToManyField("ContentMeta") page_icon=models.ImageField() page_status=models.BooleanField(default=True) def __str__(self): return self.page_title class Content(models.Model): ID = models.BigAutoField(primary_key=True) name=models.CharField(max_length=500, blank=True, null=True) content=models.CharField(max_length=500, blank=True, null=True) image=models.ImageField(blank=True, null=True) def __str__(self): return self.name class ContentMeta(models.Model): ID = models.BigAutoField(primary_key=True) template=models.CharField(max_length=50) name=models.CharField(max_length=50) content = models.ManyToManyField("Content") def __str__(self): return self.template index.html template=Page model page->contentmeta->content {% extends 'base.html' %} {% block body %} {% for templates in template.page_contentmeta.all %} {{templates.template}} {% include templates.template %} {%endfor%} {%endblock%} Banner.html -->{{template|asd:"banner1,3"}} asd=template filter Banner1= content.name 3=contentmeta_name <section style="background: url(); background-size: cover; background-position: center center" class="hero"> <div class="container"> <div class="row"> <div class="col-lg-7"> <h1></h1><a href="#" class="hero-link">{{template|asd:"banner1,3"}}</a> </div> </div><a href=".intro" class="continue link-scroll"><i class="fa fa-long-arrow-down"></i> Scroll Down</a> </div> </section> template filter @register.filter("asd") def asd(value,args): first, second = args.split(',') return value.page_contentmeta.get(name=int(second)).content.get(name=first).content -
New to Django, mod_wsgi won't install
I am new to Django and have been making a portal to make access to a database easier. We are currently at the deployment stage and so tried configuring our apache server to host it using mod_wsgi. Immediately we ran into problems installing mod_wsgi using pip, with a little research we found it is important to make sure the root directory is set appropriately. Seeing as our apache server is distributed with xampp it looks like the correct folder is C:\xampp\htdocs, so we set that using 'set MOD_WSGI_APACHE_ROOTDIR=...' and got this error: C:\Users\administrator>set "MOD_WSGI_APACHE_ROOTDIR=C:/xampp/htdocs" C:\Users\administrator>pip install mod_wsgi Collecting mod_wsgi Using cached https://files.pythonhosted.org/packages/25/d8/1df4ba9c051cd88e02971814f0867274a8ac821baf98 3b6778dacd6e31f7/mod_wsgi-4.6.8.tar.gz Installing collected packages: mod-wsgi Running setup.py install for mod-wsgi ... error ERROR: Command errored out with exit status 1: command: 'c:\users\administrator\appdata\local\programs\python\python37\python.exe' -u -c 'import sy s, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\2\\pip-install-aum 8dfd1\\mod-wsgi\\setup.py'"'"'; __file__='"'"'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\2\\pip-install-a um8dfd1\\mod-wsgi\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replac e('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\ADMINI~1\AppData\Local\Temp\2\pip-record-u1d5t3mo\install-record.txt' --single-version-externa lly-managed --compile cwd: C:\Users\ADMINI~1\AppData\Local\Temp\2\pip-install-aum8dfd1\mod-wsgi\ Complete output (33 lines): c:\users\administrator\appdata\local\programs\python\python37\lib\distutils\dist.py:274: UserWarning: Unknown distribution option: 'bugtrack_url' warnings.warn(msg) running install running build running build_py creating build creating build\lib.win-amd64-3.7 creating build\lib.win-amd64-3.7\mod_wsgi copying src\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi creating build\lib.win-amd64-3.7\mod_wsgi\server copying src\server\apxs_config.py -> build\lib.win-amd64-3.7\mod_wsgi\server copying src\server\environ.py -> build\lib.win-amd64-3.7\mod_wsgi\server copying src\server\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\server creating build\lib.win-amd64-3.7\mod_wsgi\server\management copying src\server\management\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\server\management creating build\lib.win-amd64-3.7\mod_wsgi\server\management\commands … -
Whats the logic of importing models as `app_registry.get_model('app_name', 'ModelName')` in a custom migration
I am asking this question because I ran into this django.db.utils.IntegrityError: null value in column “lft” violates not-null constraint when I was using django-hordak which uses MPPT models. The solution provided is hacky as it violates the common practice but it works. THE BASICS In django when writing custom migrations for example when creating baseline data. def forward_func(apps_registry, schema_editor): Model = apps_registry.get_model('app_name', 'ModelName') Model.objects.create(**{'field_1': 'field_1', 'field_2': 'field_2') # Do whatever you want with my Model In my situation django-hordak with the account model. That .objects.create(**data) raises theIntegrityError on the DB as specified above. Proposed solution The proposed solution is to import the model directly. def forward_func(apps_registry, schema_editor): # Model = apps_registry.get_model('app_name', 'ModelName') # lets forget about importing the standard way because it will raise integrity error. from app_name.models import ModelName as Model # Now we can proceed to deal with our model without Integrity Error. Model.objects.create(**data) This leaves me scared of possible undesirable side effects of importing models directly in migrations files. As there must be very good reasons why the model is not imported that way in the migration files. I am not looking for the reason why MPTT models fail when imported the standard way as that question … -
Using Checkbox in ListView
I'm trying to make Todo app. I want to make checkbox next to task, so when you select it, the task is set to done. The problem is, I can't really know how to change value of my BooleanField in Task Model. There are plenty of posts like this, but they are usually using functions inside views.py or use forms, but I can't relate do my form in ListView. views.py class TodolistView(LoginRequiredMixin, ListView): model = Todolist template_name = 'todolist.html' def get_queryset(self): return Todolist.objects.all().filter(user=self.request.user) def get(self, request, *args, **kwargs): todolist_objects = Todolist.objects.all() return render(request, 'todolist.html', {'todolist_objects': todolist_objects}) todolist.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <p><a href="{% url 'todolist_create' %}">Add new task</a></p> {% for todo in todolist_objects %} <div> <form action="" method="post"> <li> {{ todo }} <a href="{% url 'todolist_detail' todo.pk %}">see details</a></l> </form> </div> {% endfor %} {% endblock %} -
How can i know which button was clicked and get its value in my view
Search.py {% block search %} <form action="#" method="post"> <div class="container"> <br> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" name="bankname" type="submit" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Name </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> {% for key , value in data_dict.items %} <a class="dropdown-item" value=key name="name" href="{% url 'details' %}">{{ key}} </a> {% endfor %} </div> </div> </form> {%endblock%} the number of items in data_dict is not always same , so some times it has 2 or 3 or even 10 different names which leads to 10 items in the drop down. I need to show details of the name clicked in the drop down in details .html Views.py def details(request ): request.GET('name') data_dict = request.session.get("data_dict") context = {"data_dict" : data_dict} return render(request , "details.html", context ) i want the value of the tab clicked in the drop-down in my view so i can display the details accordingly from my data_dict -
How to add new field or list to django queryset Object and output json as result without Django Rest Framework
I want to use Django as rest-API (that too without Django RestFramework) and also Django for rendering data to the template. Let me explain in-detail I have a single project when a user from website requests with header content-type as text/plain. I'll return Queryset Objects of the related model and when the request comes from mobile app header content-type will application/json than will send queryset data as JSON. I have accomplished this through Laravel Framework and wanted to the same in Django framework. While working I'm facing some of the below problems. I want to return JSON Data if header Content-Type is application/json. If not then return template with queryset. if request.META['CONTENT_TYPE'] == 'application/json': json = serializers.serialize('json', blogs) return HttpResponse(json) else: return render(request, template_path, context) I want to add field or dictionary or list to Queryset objects manually and send the response as JSON I have Tried below and it did not work for me. from blogs.models import BlogModel def json_1(request): blogs = BlogModel.objects.all()[0:5] for blog in blogs: blog.custom_field = 100 #`custom_field` is not show in json output blog.custom_dictionary = { "name" : "pavan" } #`custom_dictionary` is not show in json output json = serializers.serialize('json', blogs) return HttpResponse(json) Json Output … -
Remove messages before the response is rendered
I've got a page which contains 2 forms & allows updating of the model attached to each. I've also got the messages framework integrated which for the most part is perfect. But after posting to this page you get two messages of success and I'd like to display 1 simple message in their place. I've tried various approaches suggested in other questions; Django: Remove message before they are displayed Deleting/Clearing django.contrib.messages But I'm unable to clear the message queue. def post(self, request, **kwargs): profile_valid = False user_valid = False post_data = request.POST or None profile_form = self.profile_form_class( post_data, instance=request.user.profile, prefix='profile' ) user_form = self.user_form_class( post_data, instance=request.user, prefix='user' ) context = self.get_context_data( profile_form=profile_form, user_form=user_form ) if profile_form.is_valid(): profile_valid = True self.form_save(profile_form) if user_form.is_valid(): user_valid = True self.form_save(user_form) if profile_valid and user_valid: # First get the messages from the above save methods storage = messages.get_messages(request) for message in storage: # Need to iterate over the messages to achieve what we need pass # Set the messages as used storage.used = True # Add our simple message messages.success(self.request, self.success_message) return self.render_to_response(context) I'm using session based message storage, but that doesn't seem to have an impact on what's available in the view. I'm using; … -
I was given a task to run the deployed python django project on localhost. How can we achieve that?
I have the Django project which is deployed in the Digital ocean. I am trying to access that code internally through localhost:8000, but I am unable to access the project. Is there any setting that I need to look upon. Please help. -
ModuleNotFoundError: No module named 'chess.uci'
I am having this error when I try to do makemigrations using Django, but I already got python-chess installed and also tried to uninstall and reinstall it, and it still didn't work. Any clue about why I am having this error or how should I fix it? Really appreciate. -
ngrok 504 timeout error when server is overloaded
i'm using ngrok to host my django webapp. The page makes an api request to obtain some information from a server (basically running some sql codes there and returning a file), but when the server is busy and all queries are slow, ngrok returns a timeout error. Does anyone know how to mitigate this? I've tried adding timeout number in settings.py but doesnt seem to work. However, when i host it locally, using my ip, it seems to work even though its slow, it doesnt have timeout error. -
'Post' object is not iterable:TypeError
This is my view . I have used function based view to show to detail of post. def post_detail(request,slug,pk): detail = get_object_or_404(Post,slug=slug,pk=pk) context={ 'detail':detail } return render(request,'post/post_detail.html',context) This is my urls . of post_detail , and its name is also post_detail path('<int:pk>/<str:slug>/', views.post_detail, name='post_detail'), This is my models. It is a post model I have got get_absolute_url () to render to detail view class Post(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(User,on_delete=models.SET_NULL,null=True) story= models.TextField() image= models.ImageField() slug = models.SlugField() def get_absolute_url(self): return reverse('post_detail',kwargs={'pk':self.pk,'slug':self.slug}) def __str__(self): return self.title This is the post/post_detail.html for my post_detail view {% extends "post/base.html" %} {% block content %} {% for posts in detail %} {{posts.image.url}} {{posts.title}} Written by: {{posts.author}} {% endfor %} {% endblock content %} -
Django switch between inlines in the admin
I am currently working on a multi-role user login module for my Django project. I currently have two roles How can I change the inlines showing on the admin page according to the role choice? #models.py in users class User(AbstractUser): role_choice = ( ('Reader', u'Reader'), ('Author', u'Author'), ('Editor', u'Editor'), ('Admin', u'Admin') ) user_role = models.CharField(choices=role_choice, max_length=150, default='Admin', verbose_name='Role') #admin.py in users class ReaderInline(admin.TabularInline): model = Reader extra = 2 class AuthorInline(admin.TabularInline): model = Author extra = 2 class UserAdmin(admin.ModelAdmin): form = UserForm inlines = [ReaderInline, AuthorInline] -
SnapToGrid and group its value in Django
i have a problem regarding Django queryset grouping. i need to get queryset of points which are groped by point snaped grid ST_SnapToGrid, query should look like this: SELECT ST_AsGeoJSON( ST_SnapToGrid("events_place"."point", 1), 8 ) AS "point_geo", MAX("events_place"."adress") AS "adress" FROM "events_place" GROUP BY point_geo and code is fallowing: models.py class Place(models.Model): kode= models.BigIntegerField(blank=True, null=True) adress = models.CharField(max_length=250, blank=True, null=True) lat = models.FloatField(blank=True, null=True) lng = models.FloatField(blank=True, null=True) point = models.PointField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) + " "+str(self.adress ) + " ("+str(self.lat) + ", " + str(self.lat) + ")" class Meta: ordering = ('created_at',) def save(self, *args, **kwargs): super(Place, self).save(*args, **kwargs) # Call the "real" save() method. views.py class PlaceSTGViewSet(viewsets.ReadOnlyModelViewSet): queryset = Place.objects.all() serializer_class = PlaceSTGSerializer def get_queryset(self): queryset = Place.objects\ .annotate(point_geo=AsGeoJSON(SnapToGrid('point', 1)), adress=Max('adress'))\ .values('lng', 'point_geo') return queryset resulting query is fallowing: SELECT "events_place"."lng", ST_AsGeoJSON( ST_SnapToGrid("events_place"."point", 1), 8 ) AS "point_geo" FROM "events_place" GROUP BY "events_place"."id", ST_AsGeoJSON( ST_SnapToGrid("events_place"."point", 1), 8 ) ORDER BY "runis_events_place"."created_at" ASC Problem is that it includes "events_place"."id" in grop by statment. Could you please tell how to get rid of this id? -
Django - How to count child records
Given the following enter code heremodels: class Area(models.Model): area = models.CharField(unique=True, max_length=20, blank=False) is_deleted = models.BooleanField(default=False) ... class Group(models.Model): group = models.CharField(unique=True, max_length=20, blank=False) is_deleted = models.BooleanField(default=False) ... class Phone(models.Model): areacode = models.ForeignKey(Area, default=None, blank=True, null=True, on_delete=models.SET(0)) groupcode = models.ForeignKey(Group, default=None, blank=True, null=True, on_delete=models.SET(0)) name = models.CharField(max_length=20, null=True, blank=True) address1 = models.CharField(max_length=20, null=True, blank=True) address2 = models.CharField(max_length=20, null=True, blank=True) is_deleted = models.BooleanField(default=False) ... In Django, how do I count total records of parent table (Area and Group) that used in child table (Phone) eg area table Name Count Area1 5 Area2 8 and phone table Hotel 6 School 8 Office 9 -
DRF: only Author can create or update the book permission
So, I have two simple models: class User(AbstractUser, models.Model): username = models.CharField( 'Username', max_length=255, db_index=True, unique=True ) email = models.EmailField( 'Email', max_length=255, db_index=True, blank=True, null=True, unique=True ) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ('email', 'password',) class Book(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) and a serializer like this: class BookSerializer(serializers.ModelSerializer): class Meta: model = models.Book fields = ['title', 'author'] def validate_author(self, author): # < --- it doesn't work if author != serializers.CurrentUserDefault(): raise serializers.ValidationError( 'You cant update other authors book' ) author = serializers.PrimaryKeyRelatedField( default=serializers.CurrentUserDefault(), queryset=models.User.objects.all() ) and a view with some permissions: class IsAuthorOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.author == request.user class BookViewSet(viewsets.ModelViewSet): queryset = models.Book.objects.all() serializer_class = serializers.BookSerializer permission_classes = [IsAuthenticatedOrReadOnly & IsAuthorOrReadOnly] So, how can I ensure that a user can get all of the books but can't create or update the books which don't belong to him? -
MacOS - ERROR: No matching distribution found for django==2.2.7
I was trying to install django in virtual env on MacOS but I'm getting this error $sudo pip install django==2.2.7 ERROR: No matching distribution found for django==2.2.7 $ python -m django --version /Users/mbp/django/django/bin/python: No module named django How do I install django? -
Unable to use wagtail with multiple databases
As the title suggests, I'm finding it difficult to use multiple databases with Wagtail. My Objective is simple: Implementation of a scenario where all the Django as well as Wagtail tables will be created in the sqlite database for now rather than in the postgreSQL db. The Why: Cause I'd like the postgreSQL DB to remain uncluttered as well as utilise it for search/select purposes using the inspectdb command. The Error generated: relation "wagtailcore_page" does not exist Cause for concern: In the default wagtail home app, migrations folder, there's a file: 0002_create_homepage.py whose contents look like: from django.db import migrations def create_homepage(apps, schema_editor): # Get models ContentType = apps.get_model('contenttypes.ContentType') Page = apps.get_model('wagtailcore.Page') Site = apps.get_model('wagtailcore.Site') So makes me wonder: is this an error that happens because Wagtail already has its own initial migration in the home app or am I doing something wrong? Better yet, how would I implement this concept with wagtail. Here's my code: base.py- database section DATABASES = { 'sqlite': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'OPTIONS': { 'options': '-c search_path=test_schema,public' }, 'NAME': os.environ.get('DBWORKNAME'), 'USER': os.environ.get('DBWORKUSER'), 'PASSWORD': os.environ.get('DBWORKPASSWORD'), 'HOST': os.environ.get('DBWORKHOST'), } } DATABASE_ROUTERS = [ 'school.router.NonPersonalDBAttributeRouter' # Router's module path ] my_project_dir/router.py … -
Django forms, adding information automatically
I am creating a Django app and I am trying to add information to some fields using values given by the usuary and saved in the same table but in another fields. For example, If the user introduce its age using a function I want to fill another field in the same table with a category lile 'under 21' or the oposite. I've tryed to define the function in the models.py file, before creting the class definition, but when I call it inside the class it just return something like users.User.age so the function is not accessing to the value contained in the field, it is using the field itself. How can I get the value contained in this field? -
select onchange tag does not run my Javascript function
I have the following code: JS: function updateLink() { var selType = document.getElementByID("Types"); var selLen = document.getElementByID("Length"); var selLoc = document.getElementByID("Location"); var selMan = document.getElementByID("Manufacturer"); var test = document.getElementByID("test"); test.innerHTML="Test"; var selectedType = (selType.options[selType.selectedIndex].text); var selectedLength = (selLen.options[selLen.selectedIndex].text); var selectedLocation = (selLoc.options[selLoc.selectedIndex].text); var selectedManufacturer = (selMan.options[selMan.selectedIndex].text); document.getElementById("apply").href="myURL?typeName="+selectedType+"length="+selectedLength+"location="+selectedLocation+"manufacturer="+selectedManufacturer; } </script> and HTML <div id="filterdiv" class="dark"> <center><h3 id="test">Filters</h3></center> <br> <center>Type</center> <select id="Types" onchange="updateLink()"> <option>All</option> {% for types in TypesList %} <option>{{types}}</option> {%endfor%} </select> <br> <br> <center>Inspection Period</center> <select id="Inspection Period"> <option>All</option> {% for inspections in InspectionList %} <option>{{inspections}}</option> {%endfor%} </select> <br> <br> <center>Length</center> <select id="Length"> <option>All</option> {% for lengths in LengthList %} <option>{{lengths}}</option> {%endfor%} </select> <br> <br> <center>Location</center> <select id="Location"> <option>All</option> {% for locations in LocationList %} <option>{{locations}}</option> {%endfor%} </select> <br> <br> <center>Manufacturer</center> <select id="Manufacturer"> <option>All</option> {% for manufacturers in ManufacturerList %} <option>{{manufacturers}}</option> {%endfor%} </select> <br> <br> <a href="" id="apply"><button onclick="updatelist()">Apply Filter (TODO)</button></a> <a href="http://myURL"><button>Reset Filters</button></a> </div> It's a list of select boxes with options taken from my Django models to filter a list in another div. On pressing my button I am redirected to the same URL, no parameters attached. And my test string to change the title also doesn't change anything. So I suspect that my JS code is never …