Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Align dropdown items to the left
I have placed checkboxes within a dropdown using bootstrap, however they are all center aligned. I would like to left align the dropdown items. Here's the code <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown button </button> <form class="dropdown-menu" aria-labelledby="dropdownMenuButton2"> <label class="dropdown-item-left"><input type="checkbox" id="f1" name="result[]">AAAAA</label> <label class="dropdown-item"><input type="checkbox" id="f2" name="result[]">BBBBBBBBBB</label> <label class="dropdown-item"><input type="checkbox" id="f3" name="result[]">CCCCCCCCCCCCCCCCCCCC</label> <label class="dropdown-item"><input type="checkbox" id="f4" name="result[]">DDDDDDDDD</label> <label class="dropdown-item"><input type="checkbox" id="f5" name="result[]">EEEEEEEE</label> </form> </div> This is how it looks: I tried using text-align: left, align-self, etc using a separate css file, but it did not work. Please help me out. Thanks in Advance. -
Is there any way in django to secure the video from being download?
I am looking for suggestions to implement this video security feature/functionality in my web app. I want to upload videos but I do not want peoples to download it. Is there any way in django to do that. Positive answers are highly appreciated. -
Why cant' I upload and save images in Django running on Ubuntu server?
So I have a Django application running on Ubuntu and nginx. I have done everything that's required to upload image, and have a template with input fields for uploading images. There's actually no error in the process, but when I save it, I don't see any file attached in the Django admin. Let me show you my code and then explain further : mdoels.py class ArticleInput(models.Model): objects = models.Manager() ... img = models.ImageField(null=True, blank=True, upload_to="article_img") forms.py class ArticleInputForm(forms.ModelForm): ... img = forms.ImageField(required=False) class Meta: model=ArticleInput fields=['title', 'img', 'subtitle', 'contents'] views.py def articleinput(request): form = DansangInputForm(initial={'authuser':request.user}) if request.method == 'POST': form = ArticleInputForm(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.authuser = request.user instance.img= request.FILES.get('img') ... instance.save() return redirect('/article/articlemain') return render(request,'article/articleinput.html', {'form':form}) articleinput.html <form method="post" class="form-group"> {% csrf_token %} ... <div class="row"> <div class="col col-12"> <div class="input-img">{{form.img|as_crispy_field}}</div> </div> </div> ... <div class="row"> <div class="col"> <button type='submit' class="btn all-buttons"> Save </button> </div> </div> My settings.py has no problem, believe me, and I've also done the chmod -R 777 command for granting permission to all of my users. So as mentioned, everything works fine in the whole process. I get no error messages, but when I attach an image file and hit "save" and … -
Python Django Simple Form Generation Question
I'm new to python and just starting in django, so go easy on me. I have a form.py file with a class like such. What's the best way to map a list of string items to the choices? Since tuples are immutable I am unsure of how to add my own data, which exists as a separate list, with each item being a string. I can't just type it out either, since the data is subject to change and it would be very troublesome. If there is a way to do this without tuples, but rather a list of singular strings, or an easy way to create a tuple out of the list it would help me so much. The documentation is hard to understand being a beginner to python and django, but it seemed like I was stuck using tuples from when I was reading it. class RecipeForm(forms.Form): THE_CHOICES =( ("1", "1"), ("2", "2"), ("3", "3"), ("4", "4"), ) THE_CHOICES2 = THE_CHOICES recipe_form = forms.ChoiceField(choices = THE_CHOICES) -
Django subtract from stock
I'm new to Django and I'm working on a create order function. I have two models of stock and order. Every time a user creates an order I want the quantity in the stock modelto be subtract by 1. Now I can successfully create an order, but what can I add in the create function to achieve that functionality. models.py class Stock(models.Model): quantity = models.IntegerField(default='0', blank=True, null=True) date_updated = models.DateTimeField('date_created', default=timezone.now(), blank=False) modified_by = models.ForeignKey(User, null=True, related_name='modified_by_user', on_delete=models.CASCADE) class Order(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=30) address = models.CharField(max_length=100) memo = models.CharField(max_length=100, blank=True) date_created = models.DateTimeField('date_created', default=timezone.now(), blank=False) views.py def create_order(request): initial_date = { 'memo':"In Progress" } form = OrderForm(request.POST or None, request.FILES or None,initial=initial_date, user=request.user) if request.method == 'POST': if form.is_valid(): order = form.save(commit = False) order.user = request.user; order.save() form = OrderForm(user=request.user) return redirect('/orderlist') context = {'form':form} html_form = render_to_string('order_form.html', context, request=request, ) return JsonResponse({'html_form': html_form}) -
Fastest way to add an item into manytomany relationship of millions of objects in django
I want to store user personalized blog posts in personalized blogs queue for each and every user. So when a blogger post a blog then the blog should add into user's queues who follow the blogger. I have a blogger table class Blogger(models.Model): name = .. .... I have a user table class User(models.Model): name = .. .... I have blog table class Blog(models.Model): content = .. blogger = .... I have a follower table class Follower(models.Model): user = ... reporter = .... blogs = ManyToMany(Blog) def addBlog(self, blog): self.blogs.add(blog) What I want to achieve is, When a blog created by a blogger, using Django signal to add the blog into blogs queue in follower table. So what is the fastest way to do this? Note: Let's say there are 10000000 followers. So the single blog should added for 10000000 users queue. -
Django auto_now_add=True but "received a naive datetime"
I have a model field as follows with a timezone aware auto add: start_date = models.DateTimeField(auto_now_add=True, blank=True) However I still get a RuntimeWarning when running tests: RuntimeWarning: DateTimeField Survey.start_date received a naive datetime (2020-07-16 03:15:14.463640) while time zone support is active. I get the same when I have: start_date = models.DateTimeField(default=timezone.now, blank=True) Any thoughts? -
DRF, using drf-yasg for separate apis
I have a Django app that includes two different APIs. I'm using the drf-yasg to create swagger docs for my app. but I don't want the consumers of every API to be able to see each other's endpoints. Is there a way to still generate automatic docs but to have docs endpoint for each app? -
bootstrap navbar hamburger menu does not work in django app
I have developed a django app but for some reason the bootstrap navbar won't show menu items on mobile phone Whenever I run my app on a mobile device's web browser the hamburger menu does not extend to show my nav items...it is very odd. <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="#"><img src="{% static 'images/logo.png' %}"></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> {% if user.is_authenticated %} <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="{% url 'dashboard:transactions' %}">Transactions</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'dashboard:quote' %}">Quote Tool</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'dashboard:tracking' %}">My Projects</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'dashboard:home' %}">Home</a> </li> <a class="nav-link" href="{% url 'dashboard:support' %}">Support</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'logout' %}">Logout</a> </li> </li> </ul> {% else %} <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="{% url 'register' %}">Sign up</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'login' %}">Login</a> </li> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'dashboard:home' %}">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'dashboard:quote' %}">Quote Tool</a> </li> </ul> </div> {% endif %} </div> </nav> -
I cant make my website show its content although i got the same codes from my reference
So ive been learning django and i am practicing to make an ecommerce website from Programming with Mosh. I faced a problem at the part where I cannot display my products at the website. I cannot figure out what I did wrong so I changed reference and used dennis ivy's ecommerce website tutorial. And now, I am facing the same problem. I compared his code with mine and its just the same but I really dont know what im doing wrong. This is his code: https://i.stack.imgur.com/Ossxm.png And this is the result he get: https://i.stack.imgur.com/On1ri.png (he used for loop and it accessed everything from his products model This is my code: {% extends 'store/main.html' %} {% load static %} {% block content %} <div class="row"> {% for product in products %} <div class="col-lg-4"> <img class='thumbnail' src="{% static 'images/2+placeholder.png' %}" alt=""> <div class="box-element product"> <h6><strong>{{product.name}}</strong></h6> <hr> <button class="btn btn-outline-secondary add-btn">Add to cart</button> <a class='btn btn-outline-success' href="#">View</a> <h4 style="display: inline-block; float: right"><strong>{{product.price}}</strong> </h4> </div> </div> {% endfor %} </div> {% endblock content %} And this is the result i get: https://i.stack.imgur.com/WsPgT.png Can someone please enlighten my stupid little tiny brain? Im so drained about this, Im stuck. -
Better way to make dictionary of counts from a QuerySet based on a field in Django?
I have a queryset of objects that could have any text value in their field and I would like a dictionary of the counts of the values in that field. For example: I have a Test Drives Object which has a foreign key to vehicle, which has a make (Char field). I would like to know how many Test Drives each make had. I have actually solved it already, but I wonder if there is a better way using Django's inbuilt functionality. My existing, working solution: customer_test_drives_makes = customer_test_drives.values_list('vehicle__make', flat=True).order_by('vehicle__make').distinct() customer_test_drives_makes_dictionary = {} for make in customer_test_drives_makes : customer_test_drives_makes_dictionary[make] = customer_test_drives.filter(vehicle__make=make).count() print(customer_test_drives_makes_dictionary) This prints:{'BMW': 1, 'Honda': 1, 'Hyundai': 1, 'Mazda': 2} Which is correct -
Django sorl: not enough values to unpack (expected 2, got 1)
I am trying to have a form to generate thumbnails from images that will be uploaded I will be using sorl for the thumb generation and I am following the following documentation: Django multiple file upload: https://docs.djangoproject.com/en/3.0/topics/http/file-uploads/ Sorl Low level API: https://sorl-thumbnail.readthedocs.io/en/latest/examples.html When I try to generate the thumbnail I get the error of not enough values to unpack (expected 2, got 1) I dont understand what I am doing wrong, in summary I upload the image and this get saved in my root directory, then im trying to create the thumb Also is there a way to void saving this original image in the root? I am planning to send both Image and thumb to google cloud storage My forms.py: from django import forms class FileFieldForm(forms.Form): file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) My html file: upload.html <html> <head></head> <body> <h3>Read File Content</h3> <form enctype="multipart/form-data" action="" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Save"> </form> </body> </html> My views.py looks like: from sorl.thumbnail import ImageField, get_thumbnail from .forms import FileFieldForm class FileFieldView(FormView): form_class = FileFieldForm template_name = 'app_workflow/upload.html' # Replace with your template. success_url = '/photo' # Replace with your URL or reverse(). def post(self, request, *args, **kwargs): form_class = … -
I AM USING INFOSYS COMPANY LAPTOP, I AM UNABLE TO DOWNLOAD DJANGO. FOLLOWING ERROR OCCURS
C:\Users\mubeenahmed.kazi>pip install django Collecting django WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x0000029969073CA0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))': /simple/django/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x0000029969073EB0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))': /simple/django/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x0000029969073E80>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))': /simple/django/ WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x0000029969093A60>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))': /simple/django/ WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x0000029969093880>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))': /simple/django/ ERROR: Could not find a version that satisfies the requirement django (from versions: none) ERROR: No matching distribution found for django -
Converting json data to html table in django without using json2htmlconverter?
I have a json data hardcoded. Now I have to convert it into a html table and display it in the webbrowser. The problem is I have to use it without javascript and should not use json2html converter. Anyone pls help me out -
Adding apps sequence in Installed apps section in setting.py in django
i wanted to add my blog app templates so i just addes blog.apps.BlogConfig in my installed apps section but here's what i found INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] adding blog.app at the top section gave an error of "no module name .." but INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog.apps.BlogConfig', ] adding in the end worked fine ...i wanted to know why did it work and how does this sequence effects and in the tutorial the person added blog.apps.blogConfig at the starting but worked for him(version 2.0) and my version is also the same . -
display file uploaded filtered by user uploaderin views
I want to make the file uploaded by the user and the file will be displayed filtered by the user-uploader only but it always fails. I have tried a number of ways but it hasn't worked. Here is the code forms.py #forms.py class FileForm(ModelForm): class Meta: model = FileUsers fields = ['file_users',] models.py from django.db import models from django.conf import settings def user_file_path(instance, filename): # file will be uploaded to MEDIA_ROOT/myfile/user_<username> return 'myfile/{0}/{1}'.format(instance.user.username, filename) class FileUsers(models.Model): users = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) file_users = models.FileField(upload_to=user_file_path) views.py def welcome(request): #authenticate users if not request.user.is_authenticated: messages.add_message(request, messages.WARNING, 'Anda Harus Login') return redirect('../login') if request.method == 'POST': form = FileForm(request.POST, request.FILES) if form.is_valid(): obj = form.cleaned_data.get('file_users','users') #set session and save form obj = form.save(commit=False) obj.user = request.user obj.save() else: messages.add_message(request, messages.INFO, 'Gagal Upload') else: form = FileForm() #load file for list page file_list = FileUsers.objects.filter(users=request.user) return render(request, 'myfile/welcome.html', {'form': form, 'file_list': file_list}) welcome.html template <!DOCTYPE html> <html> <head> <title></title> </head> <body> <p>Welcome {{ user.username }}</p> <a href="{% url 'myfile:logout' %}"><button>Logout</button></a> <form action="" method="post" enctype="multipart/form-data"> {% if messages %} {% for message in messages %} <p>{{ message }}</p> {% endfor %} {% endif %} {% csrf_token %} {{ form }} <input type="submit" name="submit" value="Submit"> {% … -
Retrieving images uploaded by users in Django Templates
I understand there are multiple (if not 100s) of questions pertaining to my issue. After trying all, I am here finally to ask. I am able to upload the image and the image path in the model. Example of an image field from model: <ImageFieldFile: static/image1_FzGpiKx.jpeg> My static folder is right where the project and app folders are. In similar hierarchy. I have the following settings in my settings.py file: MEDIA_ROOT = '/static/' MEDIA_URL = '/' In my app level urls.py, here is what I have for rendering these images: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) After all this settings , my template shows the following as img src: /static/image1_FzGpiKx.jpeg Yet it just renders the typical broken image icon. Can someone help me here? Thank you! -
Return redirect in callback function of django view
I have two functions product_page_view and buy_now_view. Problem is, after successfully posting order_form. buy_now_view is returning back to product_page_view without redirecting, if I do it like this : def product_page_view(request, prod_slug, color=None, size=None): ... ... order_form = Buy_now_form() if request.method == "POST": order_form = Buy_now_form(request.POST) if order_form.is_valid(): buy_now_view(request, prod_slug, color, size) ... ... def buy_now_view(request, prod_slug, color, size): ... ... return redirect(reverse("product-shipping", args=(order_id,))) And if i do it like this: def buy_now_view(request, prod_slug, color, size): ... ... return order_id def product_page_view(request, prod_slug, color=None, size=None): ... ... order_form = Buy_now_form() if request.method == "POST": order_form = Buy_now_form(request.POST) if order_form.is_valid(): order_id = buy_now_view(request, prod_slug, color, size) return redirect(reverse("product-shipping", args=(order_id,))) ... ... It gives me unwanted results. Link to the Question What is happening here, exactly? -
How to display sub Cateogires in Serializer in django-restfmework
models.py from django.db import models Create your models here. from django.db import models class MiniItems(models.Model): name = models.CharField(max_length=200,null=True,blank=True) desc = models.CharField(max_length=100,null=True,blank=True) price= models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) class Catagory(models.Model): name = models.CharField(max_length=100,null=True,blank=True) desc = models.CharField(max_length=100,null=True,blank=True) status= models.BooleanField(default=True) class CatagoryItems(models.Model): name = models.CharField(max_length=200,null=True,blank=True) desc = models.CharField(max_length=100,null=True,blank=True) price= models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) catagory = models.ForeignKey(Catagory, related_name='catagoryItems', on_delete=models.CASCADE) MiniItems = models.ForeignKey(MiniItems, related_name='Mini', on_delete=models.CASCADE) serializers.py from .models import Catagory, CatagoryItems,MiniItems from rest_framework import serializers class MiniItemsSerializer(serializers.ModelSerializer): class Meta: Mini = serializers.StringRelatedField(read_only=False,many=True) model = MiniItems fields ="__all__" read_only_fields = ("Mini","id") depth=2 def create(self, validated_data): jobtag_data = validated_data.pop('name') job = MiniItems.objects.create(**validated_data) MiniItems.objects.create(job=job, **jobtag_data) return job class CatagoryItemsSerializer(serializers.ModelSerializer): class Meta: items = serializers.ListField(child=MiniItemsSerializer()) model = CatagoryItems fields ="__all__" read_only_fields = ("id","items") depth=2 class CatagorySerializer(serializers.ModelSerializer): class Meta: catagoryItems =serializers.SlugRelatedField( many=True, read_only=True, slug_field='name' ) id = serializers.Field() model = Catagory fields =("id","name","desc","status","catagoryItems",) read_only_fields = ("catagoryItems",) depth=2 -
stores user personalized news using django
I would like to ask a question on Django. Firstly I will explain what I want to achieve. My platform is a blogger can post news and users can follow only bloggers and can see news that posted by the blogger. I have blogger model, user model, follower model which keep track of relationships between blogger and users. I want to keep track of all news that related to a user can be stored in a queue in that way I can keep track of read and delete news that related to a user. Platform is similar to Whatsapp but all the data should be kept in backend database. Not in user phone storage What I suggest is Kee track of read news, delete news and all news that are related to a blogger and a user in follower table and when a blogger post a news, using Django signals to add that news to above mentioned field in follower table. Is it good solution? Or can you suggest a good one? -
How to solve Django server issue
(base) osx@localhost Api_test % python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). July 16, 2020 - 05:36:03 Django version 3.0.8, using settings 'Api_test.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Error: That port is already in use. (base) osx@localhost Api_test % -
How to update the ImageField in Django Model using djnago form?
I am trying to update an imagefield in djnago model using django form..But the pic is not getting Updated. here is my Djnago model: class Shop(models.Model): name = models.CharField(max_length=100) . . . cover_image=models.ImageField(blank=True,null=True,upload_to="covers/%Y/%M/%D") and here is my Djnago form to edit Shop: class PostForm(forms.ModelForm): class Meta: model = Shop fields = ('name,.....,'cover_image') and here is the HTML of the form: <form method="POST" class="post-form" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <div class="row "> <div class="col-5 col-md-6"> <button type="submit" class="btn form_btn">Save</button> </div> </div> </form> and here is my view to handle editing: def shop_edit(request, pk): shop = get_object_or_404(Shop, pk=pk) if request.method == "POST": form = PostForm(request.POST or None, request.FILES or None,instance=Shop()) if form.is_valid(): shop = form.save(commit=False) shop.cover_image=form.cleaned_data['cover_image'] shop.save() return redirect('shop_detail', pk=shop.pk) else: form = PostForm(instance=shop) return render(request, 'shops/shop_edit.html', {'form': form}) when I add an image while adding a new shop..then the image is uploaded. But when i try to update that image via edit shop it doesn't get updated..Please help! :( -
How to add translation fields to templates using django-modeltranslation?
I am trying to translate my webpage using django-modeltranslation. I have complete the setup with the help of documentation provided but I am facing problem to display the model translated fields to templates. Can you help? Here is what I have done. # settings.py def gettext(s): return s LANGUAGES = ( ('en', gettext('English')), ('de', gettext('German')), ) MODELTRANSLATION_TRANSLATION_FILES = ( 'main.translation', ) in app translation.py file # project/app/translation.py from modeltranslation.translator import translator, TranslationOptions from .models import Post class PostTranslationOptions(TranslationOptions): fields = ('title', 'description') translator.register(Post, PostTranslationOptions) project urls.py file. # urls.py from django.contrib import admin from django.urls import path, include import debug_toolbar from django.conf.urls.i18n import i18n_patterns urlpatterns = [ path('admin/', admin.site.urls) ] urlpatterns += [ path(r'^__debug__/', include(debug_toolbar.urls)), ] urlpatterns += i18n_patterns(path('', include('main.urls'))) Views.py # views.py def ceo_dashboard(request): post = Post.objects.all().select_related() return render(request, 'main/dashboard_page.html', {'user': request.user, 'Posts': post}) template file <h2 style="color:#0B2161;" >{{ post.title }}</h2> <hr> <p>{{ post.description }}</p> <h5>Uploaded by : {{post.user}}</h5> <hr> Now I have no idea how to display these fields to templates. -
How to get the data from django.db.models.query_utils.Q
I am facing one issue with fetching data I am getting data like this (AND: ('id', '123')) How do I access this value of this id from a q object -
querySelector, getElementById on div Inner HTML not working
Let say I have an ejs file with a nav bar containing a-tags of classes. Anytime each a-tags is click I do an http request to a server which response with a html code which I then set to be an innerHTMl of a div. The problem I am facing is that I can't do no queryselectors, get the elements or even do an event listeners on the html elements of the response HTML code. Is there a way to get this to work, because I really needed those to work. The External javascript file that I used is below: var arr = this.id.split('-') var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { // Typical action to be performed when the document is ready: document.querySelector('#nav-' + arr[1] + "-" + arr[2]).innerHTML = xhttp.responseText; } }; xhttp.open("GET", "/basic" + arr[1] + "-" + arr[2], true); xhttp.send(); })