Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Group Entries by Month
I'm simply trying to group entries in my Data.active_objects that occur in the same month and year. I would like if entries sharing the same month and year would be annotated with the number of occurrences in Data.active_objects Data.active_objects has a few entries with the same month values in 'ts_create' What I've tried so far is test = Data.active_objects.annotate(ts_create__count=Count(TruncMonth('ts_create), distinct=True) However, this does not produce results that I would expect as every entry in Data.active_objects has an annotated value 'ts_create__count' of 1 even when the entries occur in the same month -
How Do I Add A Decorator To A Class?
So I'm able to add a decorator to several functions within my code but I'm unsure as to how to add it to a class. Here are my decorators: def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return redirect('index') else: return view_func(request, *args, **kwargs) return wrapper_func --------------------------------------------------------------------- def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse('You are not authorised to view this page') return wrapper_func return decorator --------------------------------------------------------------------- Here is the Class: class PasswordsChangeView(PasswordChangeView): form_class = PasswordChangedForm success_url = reverse_lazy('password-success') -
Getting Django view dictionary key in Javascript, but instead of considering it a String, considers a Variable Name
I am doing a project in Django. In my views I send data to the HTML pages with dictionaries. I can easily access that data on HTML, but when I try to access it on Javascript I can't because Javascripts thinks it's a variable name. For example, I have a log in page. If the credentials are wrong, I send them to the same page and tell them that the username or password are wrong. I want to keep the previously written username on the form, so the person only needs to rewrite the password. I send the username from the view to the Javascript, but I can't access it. My view code: def login_form(request): assert isinstance(request, HttpRequest) if 'username' and 'password' in request.POST: user = request.POST['username'] passw = request.POST['password'] if rightcredentials(user,passw): tparams = { 'message': 'login successful', } return render(request, 'about.html', tparams) else: tparams = { 'login' : 'failure1', 'username_info' : user } return render(request, 'login_form.html', tparams) Javascript code: {% if login == 'failure1' %} <form action="." method="post"> {% csrf_token %} <div class="program-info"> <h3 class="program-title">Sign Into Your Account</h3> <p>Wrong Username or password</p> <div class="form-group"> <input type="text" value="" class="form-control" name="username" id="username" placeholder="Username"> </div> <div class="form-group"> <input type="password" class="form-control" name="password" placeholder="Password"> … -
how to change the Model field value with logic to time
Say I have a model named Quote class Quote(models.Model): # date_validity will have persistent data like this 2023-11-30 15:00 date_validity = models.CharField(max_length=100, blank=True) quote_status = models.CharField( max_length=150, default='active') So I need to set quote_status expired if data_validity meets the current time, If validity is 2 days later from now then the quote should expire if validity time is over. How can I manage this automatically? As far as I know self.save() method does not trigger automatically. So any suggestions to solve this? -
Django error while serializing image model of child field
I am new to this tech, while working on django project i got some issues when i try to serialize Ticket's account.profile_pic models.py class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE profile_pic = models.ImageField(upload_to='images/profile_pics/', blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) class Ticket(models.Model): author = models.ForeignKey(Account, on_delete=models.CASCADE) descr = models.TextField(blank=False, null=False) likes = models.ManyToManyField(User) serializers.py class DetailedTicketSerializer(serializers.ModelSerializer): # Error occurs on below line: No file associated with ImageField author_profile_pic = serializers.ReadOnlyField(source='author.profile_pic') author_username = serializers.ReadOnlyField(source='author.user.username') class Meta: model = Ticket fields = ['id', 'author_profile_pic', 'author_username', 'likes', 'descr'] Anyone knows how do i serialize Account.profile_pic's url??? -
Unable to send context to django template
Didn't find a solution to similar issue. I have a list of tasks rendered on a page and after clicking on a title a modal window is popping up with a form to update the task. List and update are made in one class-based view. When a modal window is opened task id is received by views.py from AJAX to update my context in order to show saved data in form fields. I can see updated context with specific object when printing it in my views.py, but the object is not shown in HTML via template tag. Please, help me to figure out what am I doing wrong. Here is my views.py: class KanbanBoardView(PermissionRequiredMixin, View): permission_required = ('projects.view_taskassign',) def get(self, request, *args, **kwargs): context = { 'heading': "Kanban board", 'pageview': "Tasks", 'tasks': TaskAssign.objects.all(), 'statuses': Status.objects.all(), 'users': User.objects.all(), } if 'taskid' in request.GET: task_id = request.GET.get('taskid') task_object = TaskAssign.objects.get(id=task_id) context['task'] = task_object return render(request, 'tasks/kanbanboard.html', context) return render(request, 'tasks/kanbanboard.html', context) def post(self, request): if 'edittask' in request.POST: id = request.POST['id'] deadline = request.POST['deadline'] status = request.POST['status'] user = request.POST['user'] task = TaskAssign.objects.filter(id=id) task.update(deadline=deadline, status=status, user_id=int(user)) return redirect('tasks-kanbanboard') else: status_id = int(request.POST.get('status')) task_id = int(request.POST.get('task_id')) task = get_object_or_404(TaskAssign, pk=task_id) task.status_id = status_id … -
Django. General design philosophy question: best way to implement "toggleable" separate features in a website
Let's say I want to create a blueprint of an online store that I can sell to potential clients. However, the idea is to make it so that the client chooses features that they want their store to have (from a pre-designated list) and pay only for those features, that way avoiding paying for something they don't need. So for example, one client wants to have and online store with a Cart, Purchase History, Graphs, Reports. Another one only wants simple registration and cart (but maybe in future they will want me to "enable" other features as well). My question is: what, in your opinion, is the best way to tackle this problem from a Django developer perspective? My thoughts: Create every feature as a separate app and deploy the whole thing commenting out the features that client did not pay for. And when a client wants additional features, I simply go to settings.py and uncomment the app they requested. Can I even make changes on the settings.py file on a live website without restarting it? Create an admin panel for myself (the superuser) that will have an ability to turn features on or off. So when the client pays … -
How to handle create/update on multiple nested serializers?
I've been able to make creating/updating happen on nested serializers, but I can't seem to get it to work when there are multiple many to many nest serializers. Models: class Brand(models.Model): name = models.CharField(max_length=500) class Incentive(models.Model): name = models.CharField(max_length=500) brands = models.ManyToManyField(Brand, related_name='incentives_brand') start_dt = models.DateTimeField(auto_now_add=False, blank=True, null=True) end_dt = models.DateTimeField(auto_now_add=False, blank=True, null=True) class Version(models.Model): name = models.CharField(max_length=1000) incentives = models.ManyToManyField(Incentive, related_name='versions_incentive', blank=True) brands = models.ManyToManyField(Brand, related_name='versions_brand') Serializers: class BrandSerializer(serializers.ModelSerializer): class Meta: model = Brand depth = 1 fields = ['id', 'name'] class IncentiveSerializer(serializers.ModelSerializer): brands = BrandSerializer(many=True) class Meta: model = Incentive # depth = 1 fields = ['id', 'name', 'brands', 'start_dt', 'end_dt'] class VersionSerializer(serializers.ModelSerializer): incentives = IncentiveSerializer(many=True) brands = BrandSerializer(many=True) class Meta: model = Version fields = ['id', 'name', 'incentives', 'brands'] def create(self, validated_data): brands = validated_data.pop('brands', []) incentives = validated_data.pop('incentives', []) instance = Version.objects.create(**validated_data) for brand_data in brands: brand = Brand.objects.get(**brand_data) instance.brands.add(brand) for incentive_data in incentives: incentive = Incentive.objects.get(**incentive_data) instance.incentives.add(incentive) return instance def update(self, instance, validated_data): brands = validated_data.pop('brands', []) incentives = validated_data.pop('incentives', []) instance = super().update(instance, validated_data) brand_objs = [] incentive_objs = [] for brand_data in brands: brand = Brand.objects.get(**brand_data) brand_objs.append(brand) instance.brands.set(brand_objs) for incentive_data in incentives: incentive = Incentive.objects.get(**incentive_data) incentive_objs.append(incentive) instance.incentives.set(incentive_objs) return instance I tried using the … -
How to filter queryset based on boolean value, then count in template
I want to count how many jobs are open vs closed. I don't understand why this isn't working, I have added {{ap.id}} and {{open.line_num_id }} after the forloop just to see what was rendered. I would think that if they match, then it's added to the count. This is not the case, all jobs are counted regardless of the "if" statement. Totally lost as to what is happening and why. Any help would be very appreciated . I have two models: class Airplane(models.Model): line_num = models.CharField(max_length=10, unique=True) vh_num = models.CharField(max_length=4, unique=True) vz_num = models.CharField(max_length=4, unique=True) stall = models.CharField(max_length=30, choices=stall_picker) status = models.CharField(max_length=30, choices=status_picker) owner = models.ForeignKey(User, on_delete=models.CASCADE) is_completed = models.BooleanField(default=False) pm = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.line_num class Job(models.Model): line_num = models.ForeignKey( Airplane, on_delete=models.CASCADE, related_name="ap_jobs") job_num = models.CharField(max_length=10, unique=True) description = models.CharField(max_length=200) status = models.CharField(max_length=30, choices=status_picker) category = models.CharField(max_length=30, choices=categories_picker) is_completed = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class meta: ordering = ["category", "status"] def __str__(self): return (f"{self.job_num}: {self.description} : {self.is_completed}") My View: def Ap_linup(request): context = { 'ap_list': Airplane.objects.all().filter(is_completed=False), 'open_jobs': Job.objects.all().filter(is_completed=False), 'closed_jobs': Job.objects.all().filter(is_completed=True) } return render(request, 'airplane/airplane_list.html', context) Template: {% extends 'base.html' %} {% block title %} Airplane List {% endblock %} … -
Where does this (Django) CustomUser field come from?
My searches only turned up tips on how to add fields or add_fieldsets in admin.py when using Django's CustomUser. I need to find out where a field named admin comes from when the model form is rendered in the class-based CreateView. There is no error with the code, but the template automatically adds an admin choice field on top of the page-the drop-down choices are users (all 3 types) already created. But I want to create a new staff user. So how do I tell Django to leave the admin field out (at least until a user is saved)? # models.py class CustomUser(AbstractUser): user_type_data = ((1, "HOD"), (2, "Staff"), (3, "Student")) user_type = models.CharField(default=1, choices=user_type_data, max_length=10) class Staff(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) email = models.EmailField() objects = models.Manager() # forms.py class StaffForm(forms.ModelForm): model = Staff first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) class Meta: model = Staff fields = '__all__' # views.py class StaffCreateView(CreateView): model = Staff form_class = StaffForm context_object_name = 'staff' success_url = reverse_lazy('staff_list') # staff_form.html <form method="post"> {{ form.as_p }} <input type="submit" value="Save"> </form> -
chartjs-plugin-annotation box in Django app
I have chartjs v2.9.3 in my Django app and it works great. Now I need to add a box to one of my charts using chartjs-plugin-annotation, and I've followed all the steps, but I can't get it to work. I've used chartjs-plugin-annotation v0.5.7 which is for v2.9.3. I get no errors in the console log. First, scripts with chart.js and plugins: <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.7.0"></script> <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-annotation@0.5.7/chartjs-plugin-annotation.min.js"></script> My code for chart (chart works, I just can't get box to appear): <canvas id="myChart" height="250"></canvas> <script> function setChart12(){ $('#myChart').remove(); $('#container_glavni').append('<canvas id="myChart" height="200"></canvas>'); var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: date, datasets: [{ label: 'Number of reports', data: data_nc }, { type: 'line', label: 'Median', data: [50], fill: false, borderColor: 'rgb(54, 162, 235)', }], }, options: { layout: { padding: { top: 30 } }, responsive: true, legend: { display: false }, plugins: { datalabels: { anchor: 'end', align: 'end', offset: 5, }, autocolors: false, annotation: { annotations: { box1: { type: 'box', xMin: 0, xMax: 1, yMin: 0, yMax: 30, backgroundColor: 'rgba(255, 99, 132, 0.25)'} } } }, scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } });} </script> I've tried: … -
show aggragated data in admin changelist_view
I have an app where I am tracking user searches. The table currently looks like this: What I want to change is the view. I'd dlike to group/aggregate/annotate the view based on Search Term column and keep the latest date of each search term. The column User searches is being updated when user puts the same term in the search bar so there is no need for me to keep all records. I just need the latest one. I tried to update queryset using distinct() and annotate() in admin model but with no success. In other words I want to have 1 unique term in the table with the latest date (Searched on column). Below is my code: models.py class SearchQueryTracker(models.Model): id = models.AutoField(primary_key=True) author = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL, unique=False) total_results = models.IntegerField('Search results', default=0) total_searches = models.IntegerField('User searches', default=0) search_term = models.CharField(max_length=1000, blank=True, null=True) searched_on = models.DateTimeField('searched on', default=timezone.now) views.py @login_required def SearchViewFBV(request): query = request.GET.get('q') query_list = request.GET.get('q', None).split() query_list_count = len(query_list) user = User.objects.get(email=request.user.email) find_duplicate_results = SearchQueryTracker.objects.filter(search_term=query).update(total_searches=F('total_searches') + 1) .... search_tracker = SearchQueryTracker() search_tracker.total_searches = find_duplicate_results search_tracker.author = user search_tracker.search_term = query search_tracker.save() admin.py class SearchQueryTrackerAdmin(ImportExportModelAdmin): list_display = ('search_term', 'author', 'total_results', 'total_searches', 'searched_on') readonly_fields = list_display … -
apache2 permissions denied, django project
I have a linux server (ubuntu) and I uploaded a project, in my project, I try to generate a pdf with reportlab, using some fonts for the created pdf. I am having problems with permissions for reportlab. When I check out the error log in apache (/var/log/apache2/error.log), the error that appears is: reportlab.pdfbase.ttfonts.TTFError: Can't open file "recursos/fonts/Lato-Regular.ttf" I already gave full permissions (chmod 777) and also changed the owner to apache (chown :www-data) to the whole project, but the same error appears. In my local machine, works perfectly. -
Populating sql table with foreign keys using django
So im having some trouble inserting data into my sql database when using django. Setting up the tables aswell as populating them trough the admin page works perfectly fine but i have a scraper function that runts every 24h thats supposed to insert data. from datetime import datetime from .faceScraper import faceScraper as fc def Dbpopulator(): from ..models import Event [title_list, time_list, location_list, nation_list] = fc() print("scraped") for i in range(len(title_list)): e = Event() e.title = title_list[i] e.starttime = time_list[i][0] e.endtime = time_list[i][1] e.location = location_list[i] instance = e.save(commit=False) instance.nation = nation_list[i] instance.save() The problem arises when im trying to set the nation which is a foreign key from the models file below. from django.db import models # Create your models here. class Nation(models.Model): name = models.CharField(max_length=80, primary_key=True) description = models.TextField() Facebook = models.CharField(max_length=80, null=True, blank=True) def __str__(self): return self.name class Event(models.Model): title = models.CharField(max_length=80, unique=True) starttime = models.DateTimeField(null=True, blank=True) endtime = models.DateTimeField(null=True, blank=True) nation = models.ForeignKey( Nation, on_delete=models.CASCADE, default=None, null=True, blank=True) location = models.CharField(max_length=80, null=True, blank=True) def __str__(self): return self.title I have tried many different ways primarily just setting e.nation = nation_list[i] But it just wont work, i am also very certain that the database is already populated with … -
Django does not send cookies to my react app
Django backend app sends cookies in development but when I deploy it. It does not send cookies to my react application. My react application is served on Netlify and the Django app is served on Heroku. In the Django app, I have set CORS_ALLOWED_ORIGINS and CORS_ALLOW_CREDENTIALS = True. In the react app I have set withCredentials: true using Axios. The entire setup works well in development. -
django compressor error 'set' object has no attribute 'format'
Im trying to configure django compressor to work with the ifc.js library, it uses bundled js files, these arew my settings along the default from the django compressor toolkit COMPRESS_ES6_COMPILER_CMD = { 'export NODE_PATH="{paths}" && ' '{browserify_bin} "{infile}" -o "{outfile}" ' '-t [ "{node_modules}/babelify" --presets="{node_modules}/babel-preset- es2015" ]' } COMPRESS_ENABLED = True COMPRESS_OFFLINE = False when I load the page or if i try to compress, it gives me a "AttributeError: 'set' object has no attribute 'format'" with location in xxx/site-packages/compressor/filters/base.py in input, line 178, im not really sure if its a configuration error or a bug from the package, thanks -
Django Redirect by Name - No Reverse Match Error
My django project name is 'exercises' and the app name is 'practice'. This basic application allows a user can navigate to different pages with a button click. The reference to each page uses the following href: {% url 'practice:redirector' project.pk %} Where practice:redirector points to my app (practice) url path named redirector. It is parameterized with the primary key of the page which I am trying to redirect to. See below from django.urls import path from practice import views app_name = "practice" urlpatterns = [ path('', views.all_sites, name="all_sites"), path('<int:pk>', views.redirector, name='redirector'), path('clickToAddItems', views.clickToAddItems, name='clickToAddItems'), path('displayEvens', views.displayEvens, name='displayEvens'), path('displayMousePosition', views.displayMousePosition, name='displayMousePosition'), path('luckySevens', views.luckySevens, name='luckySevens'), ] This url points to the views within practice. There, I have a view set up for each page that corresponds to the name that the page will display. I also have a re director view that uses the pk passed in the url to pull the relevant page from my database and use the name as the argument in the redirect() shortcut: from django.shortcuts import render, redirect from practice.models import Project app_name = "practice" # Create your views here. # Main list of javascript sites def all_sites(request): # query my project model to return all site … -
How to properly update a many to many nested serializer?
I have been able to replicate the create method to add the correct nested serializers in a POST request. However, I'm still having issues updating in a PUT or PATCH. When using a PUT or PATCH request and I pass the entire object data or the "brands" data, it will only update in the position it is passed. So if I have an object with 3 values: "brands": [ { "id": 1, "name": "Brand 1 Test" }, { "id": 2, "name": "Brand 2 Test" }, { "id": 3, "name": "Brand 3 Test" } } If I pass: "brands": [ { "id": 1, "name": "Brand 1 Test" }, { "id": 2, "name": "Brand 2 Test" } It will give me the same list of 3 brands. But if I do that in reverse order it will update and add the 3rd brand. I'm not sure what's causing it. Here's the code I have: Models class Brand(models.Model): name = models.CharField(max_length=500) class Incentive(models.Model): name = models.CharField(max_length=500) brands = models.ManyToManyField(Brand, related_name='incentives_brand') start_dt = models.DateTimeField(auto_now_add=False, blank=True, null=True) end_dt = models.DateTimeField(auto_now_add=False, blank=True, null=True) Serializers class BrandSerializer(serializers.ModelSerializer): class Meta: model = Brand depth = 1 fields = ['id', 'name'] class IncentiveSerializer(serializers.ModelSerializer): brands = BrandSerializer(many=True) class Meta: model … -
How to Deploy Django app using OVH webhosting?
I am about to deploy my django app in OVHcloud, I bought the web hosting plan(shared web hosting platform) and it looks like I need to use a CMS. I am confused as I am not sure how to proceed, is Django CMS a solution? Moreover I am using django channels so my app is asgi would that be an issue or I should switch to VPS ? Any help/guidance is appreciated. -
Custom field - got multiple values for keyword argument 'related_name'
I'm working on a custom field that is just a shortcut to ForeignKey that points to addresses.Country model. When I run makemigrations it returns this error with I'm not sure: TypeError: Couldn't reconstruct field rsft_country on properties.Property: django.db.models.fields.related.ForeignKey.__init__() got multiple values for keyword argument 'to' I understand that there are two to arguments passed but I don't understand why. It looks like the field is initialized two times. Once with the kwargs I provided and then with all the kwargs. class RsftCountryField(models.ForeignKey): def __init__(self, verbose_name=None, **kwargs): print(kwargs) kwargs['verbose_name'] = verbose_name or 'Krajina' to = 'addresses.Country' on_delete = kwargs.pop('on_delete',None) or models.PROTECT related_name = kwargs.pop('related_name',None) or '+' super().__init__(to, on_delete, related_name=related_name, related_query_name=None, limit_choices_to=None, parent_link=False, to_field=None, db_constraint=True, **kwargs) Model: ... rsft_country = addresses_fields.RsftCountryField(null=True, blank=True) It prints kwargs two times: {'null': True, 'blank': True} {'blank': True, 'null': True, 'related_name': '+', 'on_delete': <function PROTECT at 0x7fa9fa277d00>, 'to': 'addresses.country'} Why does it do that and how to make it work? -
select_related().prefetch_related() returns invalid field
There is a class like: class SubCategories(models.Model): code = models.CharField(max_length=50) name = models.CharField(max_length=50) class Categories(models.Model): subcategory = models.ForeignKey( 'app.SubCategories', related_name='app_category_subcategory' ) I am going to do a query as follows: Cat = Categories() Cat.select_related('subcategory').prefetch_related('code').get_or_create(id=2, defaults={ 'subcategory__code':205610}) subcategory_id works but for subcategory__code (which I need) it raises an error that this is invalid field name for Categories. That would be nice if someone could tell me how can I access the code field from the ForeignKey -
Django migrate varchar [closed]
error Tengo un error al momento de hacer migrate... ¿Alguien podría darme una luz sobre como puedo avanzar en esta situación? Lo que más me preocupa es que en local me funciona perfecto, pero en el server ya me genera este error. -
How do I leverage react components from python email templates?
We have a django/react app that has a lot of work put into creating some react components that we want to reuse in some templated emails. Most of the components are in their own package outside of the actual react app. How should we incorporate these components into emails without having to rewrite them all? I'm assuming this will involve making a smaller react app hat only renders the content for the email then use that from some service to generate the python email template? I feel like this could be a large opened ended question but please add comments about how I could make it more specific and I will be happy to make changes. Also I feel like this has to be a common problem and wouldn't mind being pointed in the direction of some preexisting questions or articles as my googling must be lacking today. -
Django Foreign Keys connections
I have a model Field that has a OneToMany connections with TreeSensor and WeatherStation model. Im trying to pass over the queries of each treesensor/weatherstation model that match the id of each different field but get a Field 'id' expected a number but got <built-in function id>. .How do i fix that? Maybe change something on the filter ? class Field(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, default=None) friendly_name = models.CharField(max_length=24, blank=True) class TreeSensor(models.Model): field = models.ForeignKey(Field, on_delete=models.CASCADE) ... class WeatherStation(models.Model): field = models.ForeignKey(Field, on_delete=models.CASCADE) ... view def map(request): field_list = models.Field.objects.filter(user = request.user) tree_sensors = models.TreeSensor.objects.filter(field__pk = id) weather_stations = models.WeatherStation.objects.filter(field__pk = id) context = { "title": "Map", "field_list": field_list, "tree_sensors": tree_sensors, "weather_stations" : weather_stations, } template = 'agriculture/map.html' return render(request, template, context) -
How to Include JavaScript variable in Django URL in template?
I want to include mangaid variable in "{% url 'manga' mangaid %}". Neither ${mangaid} nor mangaid works. How can I do this? let input = document.querySelector("#search") input.addEventListener("keyup", () => { document.querySelector("#results").innerHTML = ""; let value = (input.value) fetch(`searchresponse/${value}`).then((response) => response.json()).then((results) => { results.forEach(function (result) { let mangaid = (result["id"]) document.querySelector("#results").insertAdjacentHTML('beforeend', `<a class="result" id="result${mangaid}">${result["title"]}</a>`); document.getElementById("result"+mangaid).addEventListener("click", (event) => { event.target.href = "{% url 'manga' mangaid %}" }) }) }) })