Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to update product quantity after adding product to cart?
I am working on a shopping cart project which is developed using angular and django. I want to update the qty of product when adding a product. but now the qty is updated when page is refreshed. Below code i have been tried so far. Home.Component.ts: async ngOnInit() { await this.getUpdatedCart();} ngOnDestroy() { this.subscription.unsubscribe();} async getUpdatedCart() { this.subscription = (await this.cartService.getCart(this.products)) .subscribe(cart => { this.cart = cart; console.log('cart', this.cart); });}} shopping-cart.services.ts async getCart(product) { const cartId = JSON.parse(localStorage.getItem('cartId')); if (cartId) { return this.http.get(this.globalService.baseUrl + 'shopping-cart/' + cartId + '/'); }} product-card.component.ts export class ProductCardComponent { @Input('product') product; @Input('shopping-cart') shoppingCart; constructor(private cartService: ShoppingCartService, private homeComponent: HomeComponent) { } async addToCart(product) { await this.cartService.addProductToCart(product); //this.getQuantity(); } getQuantity() { if (!this.shoppingCart) { return 0; } const item = this.shoppingCart.carts; for (let i = 0; i < item.length; i++) { if (item[i].product === this.product.id) { return item[i].qty; } } return 0;}} product-card.component.html <div class="card-footer"> <button (click)="addToCart(product) " class="btn btn-primary btn- block">Add to cart</button> <div>{{getQuantity() }}</div> </div> </div> I want when user click "add to cart" button then the quantity will be updated. but quantity is updated after i click the button twice. -
Django Rest Show Several Reverse Relation
I have a model to which several other models have OneToOne relationship: class ModelA(models.Model): title = ... description = ... class ModelB(models.Model): peer = models.OneToOneField(related_name='ModelB') score = models.IntegerField() class ModelC(models.Model): peer = models.OneToOneField(related_name='ModelC') score = models.IntegerField() What I want to do is to provide an endpoint in which I list the score value of all the reverse relation that ModelA has. This is my desired url: modelA/<int:pk>/reverse-relations/ So I have tried achieving so by writing this simple serializer: class ModelAReverseRelationSerializer(serializers.ModelSerializer): class Meta: model = ModelA fields = ['ModelB', #This being the related_name 'ModelC',] And this view which I think I am getting something wrong here: class ModelAReverseRelationsView(ListAPIView): def get_queryset(self): print(self.kwargs["id"]) # Does not print anything in the console and I don't know why queryset = Threat.objects.filter( threat_id=self.kwargs["id"]) return queryset serializer_class = ModelAReverseRelationSerializer This approach returns the value of only one of the related models. I also tried setting many=true on the view but still I get on of the reverse relation's value. -
Django: send emails to users
I have a list of users with their email adress (only for Staff members), I am trying to send a form to the user. When I use i.email, I get this error: "to" argument must be a list or tuple When I use ['i.email'] I don't receive the message. urls.py path('users/<int:id>/contact', views.contactUser, name='contact_user'), views.py def contactUser(request, id): i = User.objects.get(id=id) if request.method == 'POST': form = ContactUserForm(request.POST) if form.is_valid(): message = form.cleaned_data['message'] send_mail('Website administration', message, ['website@gmail.com'], ['i.email']) return redirect('accounts:users') else: form = ContactUserForm() return render(request, 'accounts/contact_user.html', {'form': form, 'username': i}) I am using SendGrid. I have a 'contact us' form which is similar to contactUser and it works fine. -
Track Which user has updated which fields of any models?
How do I log which user has performed what changes(field value) in any of model? The way I tried: Write code in the pre_save signal. In that, I am getting the old and new value, but request object(for current login user) and list of updated fields are not getting. Write code in Django Forms save(), but same issue can fetch request object(current login user). -
How do I delete all the content in my database -Python-
How can I delete the entire contents of my database? Currently I have a script that reads a CSV file and stores the content in my database. But it's important to delete everything in the database before I add the new data. -> I run the script -> Database contents are deleted -> new data will be saved I have to do it that way, because the CSV file changes 1-2 times a day and the information it contains is completely different. -
How to fix "ImportError: cannot import name 'User' from 'cobudget.users.models' (/app/cobudget/users/models.py)" error?
I want to import my custom user model to another model file but I'm getting that error, when trying run django commands by manage.py. For example, I want to run "python manage.py migrate" and I'm getting this: Traceback (most recent call last): File "manage.py", line 30, in execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/site->packages/django/core/management/init.py", line 381, in >execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/init.py", line 357, in execute django.setup() File "/usr/local/lib/python3.7/site-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/usr/local/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/local/lib/python3.7/importlib/init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 967, in _find_and_load_unlocked File "", line 677, in _load_unlocked File "", line 728, in exec_module File "", line 219, in _call_with_frames_removed File "/app/cobudget/users/models.py", line 6, in from cobudget.companies.models import Company File "/app/cobudget/companies/models.py", line 2, in from cobudget.users.models import User ImportError: cannot import name 'User' from 'cobudget.users.models' (/app/cobudget/users/models.py) My models.py: cobudget/users/models.py from django.db import models from django.urls import reverse from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) from cobudget.companies.models import Company class CustomUserManager(BaseUserManager): def create_user(self, email, password=None): """ Creates and saves a User with the given email, date of birth and password. … -
django template tag pass as parameter of another template tag
I have 2 custom template tag as following: @register.simple_tag def foo(): return foo_value @register.simple_tag def bar(value): return bar_value + value and I want to to use them in my template like this: {% load my_custom_tags %} {% bar foo %} Is there a way to pass the result of a template tag to another template tag? -
How to order search results according to PageRank scores
I am working on a search engine that produces results with PageRank scores assigned to each link. I want the results to be ordered (sorted) according to the PageRank score (highest scored links come at the top). I am not an expert in python, but I used the following code with Django. I put part of the code I used here, please have a look: https://trinket.io/python/1d3490b96e How do I order the resulting links accoridng to their given PageRank Score? The scores are stored in a text file, and each link has its own score given during the crawling. Thanks -
Search population based on country, city and age group
I have the work to render population based on the dropdown menu selected of country, city and age group. How do i format the json data? How is it going to look like? I want to do it using React and django. What is the best way to do this? Thanks. -
Error while running ./runtests.py from django
I took fork from https://github.com/django/django Running in python3 virtual env When I run ./runtests.py inside the tests folder I am getting this error Traceback (most recent call last): File "./runtests.py", line 19, in from django.utils.deprecation import ( ImportError: cannot import name 'RemovedInDjango20Warning' Tried running on django 2.0 and django 1.9 Traceback (most recent call last): File "./runtests.py", line 19, in from django.utils.deprecation import ( ImportError: cannot import name 'RemovedInDjango20Warning' I should be able to run all the test cases -
django-storages get uploaded url
I'm using django-storages in Django 2.x to upload files manually without any model. Here is my implementation using Django REST Framework (DRF) class MediaListCreateView(generics.ListCreateAPIView): """ List and create media """ serializer_class = MediaSerializer parser_classes = [FileUploadParser] upload_path = 'uploads/media/' def post(self, request, *args, **kwargs): if 'file' not in request.data: raise ParseError('Empty content') file = request.data.get('file') file_ = default_storage.open('{}{}'.format(self.upload_path, file.name), 'w') file_.write(file.read()) file_.close() return Response('Success', status=status.HTTP_200_OK) The file is saved in the S3 bucket, but now I want to return the full URL of the uploaded file in the response in place of Success. How can I get the full URL of the uploaded file? -
Unable to search using elasticsearch in django with django-elasticsearch-dsl-drf (Set fielddata=true on [title.raw])
I have followed the quick start guide shown here, in order to experiment with elasticsearch searching and a sample Django app I am playing with. Using elasticsearch 6.3.1 and latest django-elasticsearch-dsl-drf The results is the following error. RequestError at /search/movies/ RequestError(400, 'search_phase_execution_exception', 'Fielddata is disabled on text fields by default. Set fielddata=true on [title.raw] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead.') I have added in the django project an extra app named search_indexes. Here is the documents.py from this app. from django_elasticsearch_dsl import Index, fields from django_elasticsearch_dsl.documents import DocType from elasticsearch_dsl import analyzer from library.models import * # Name of the Elasticsearch index INDEX = Index('search_movies') # See Elasticsearch Indices API reference for available settings INDEX.settings( number_of_shards=1, number_of_replicas=1 ) html_strip = analyzer( 'html_strip', tokenizer="standard", filter=["standard", "lowercase", "stop", "snowball"], char_filter=["html_strip"] ) @INDEX.doc_type class MovieDocument(DocType): """Movie Elasticsearch document.""" id = fields.IntegerField(attr='id') title = fields.StringField( analyzer=html_strip, fields={ 'raw': fields.StringField(analyzer='keyword'), } ) summary = fields.StringField( analyzer=html_strip, fields={ 'raw': fields.StringField(analyzer='keyword'), } ) people = fields.StringField( attr='people_indexing', analyzer=html_strip, fields={ 'raw': fields.StringField(analyzer='keyword', multi=True), 'suggest': fields.CompletionField(multi=True), }, multi=True ) genres = fields.StringField( attr='genres_indexing', analyzer=html_strip, fields={ 'raw': fields.StringField(analyzer='keyword', multi=True), 'suggest': … -
Bug only in deploy mode and not when launch runserver
I have a problem when I deploy my Django app with WSGI, but not in dev mode. I use apache2. My user model is in authentification I've tried to migrate authentification first, but it doesn't work. I've also already tried deleting the database, but nothing's changed. Here is the stacktrace: [Wed Aug 07 10:36:25.814102 2019] [wsgi:error] [pid 5342:tid 140647152961280] [remote ::1:57686] mod_wsgi (pid=5342): Failed to exec Python script file '/home/roo/myproject/Challenges/wsgi.py'. [Wed Aug 07 10:36:25.814171 2019] [wsgi:error] [pid 5342:tid 140647152961280] [remote ::1:57686] mod_wsgi (pid=5342): Exception occurred processing WSGI script '/home/roo/myproject/Challenges/wsgi.py'. [Wed Aug 07 10:36:25.815237 2019] [wsgi:error] [pid 5342:tid 140647152961280] [remote ::1:57686] Traceback (most recent call last): [Wed Aug 07 10:36:25.815301 2019] [wsgi:error] [pid 5342:tid 140647152961280] [remote ::1:57686] File "/home/roo/myproject/venv/lib/python3.7/site-packages/django/apps/config.py", line 178, in get_model [Wed Aug 07 10:36:25.815308 2019] [wsgi:error] [pid 5342:tid 140647152961280] [remote ::1:57686] return self.models[model_name.lower()] [Wed Aug 07 10:36:25.815322 2019] [wsgi:error] [pid 5342:tid 140647152961280] [remote ::1:57686] KeyError: 'user' [Wed Aug 07 10:36:25.815333 2019] [wsgi:error] [pid 5342:tid 140647152961280] [remote ::1:57686] [Wed Aug 07 10:36:25.815336 2019] [wsgi:error] [pid 5342:tid 140647152961280] [remote ::1:57686] During handling of the above exception, another exception occurred: [Wed Aug 07 10:36:25.815339 2019] [wsgi:error] [pid 5342:tid 140647152961280] [remote ::1:57686] [Wed Aug 07 10:36:25.815344 2019] [wsgi:error] [pid 5342:tid 140647152961280] [remote … -
Template id Not working after moving Oscar package to my Application?
I am getting 404 error on my home page, I just move Django Oscar package to my application, but it's not working now, Before moving top my application it was wing good, Please let me know what is the issue. Whenever i am opening my website it's showing me error 404, I think there are some mistake in my urls.py file Here are my settings.py file... """ Django settings for frobshop project. Generated by 'django-admin startproject' using Django 1.11.23. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os from oscar.defaults import * location = lambda x: os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', x) PROJECT_DIR=os.path.dirname(__file__) # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ SECRET_KEY = 'bg-a-t#7--wbz$rie*2n%1c-9j#0v8own&5+t7^kduqzc&j5nm' DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', 'compressor', 'widget_tweaks', 'haystack', 'treebeard', 'sorl.thumbnail', 'django_tables2', #'south', #oscar apps 'oscar', 'oscar.apps.analytics', 'oscar.apps.checkout', 'oscar.apps.address', 'oscar.apps.shipping', 'oscar.apps.catalogue', 'oscar.apps.catalogue.reviews', 'oscar.apps.partner', 'oscar.apps.basket', 'oscar.apps.payment', 'oscar.apps.offer', 'oscar.apps.order', 'oscar.apps.customer', 'oscar.apps.search', 'oscar.apps.voucher', 'oscar.apps.wishlists', 'oscar.apps.dashboard', 'oscar.apps.dashboard.reports', 'oscar.apps.dashboard.users', 'oscar.apps.dashboard.orders', 'oscar.apps.dashboard.catalogue', 'oscar.apps.dashboard.offers', 'oscar.apps.dashboard.partners', 'oscar.apps.dashboard.pages', 'oscar.apps.dashboard.ranges', 'oscar.apps.dashboard.reviews', 'oscar.apps.dashboard.vouchers', 'oscar.apps.dashboard.communications', 'oscar.apps.dashboard.shipping', ] SITE_ID = 1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', … -
djongo.sql2mongo.SQLDecodeError while updating / reading rows
I am using djongo as MongoDB conenctor for my Django project. I am getting below error, in create and update APIs djongo.sql2mongo.SQLDecodeError: FAILED SQL: UPDATE Read API giving matching query does not exist on Foreign key field Batch whereas when I check in DB the respective row is there. Setup: Django==2.1 pymongo==3.8.0 sqlparse==0.2.4 djongo==1.2.33 #model.py class Batch(models.Model): batch_number = models.IntegerField(unique=True) class Product(models.Model): batch = ForeignKey(Batch, on_delete=CASCADE) serial_number = models.CharField(max_length=255, unique=True) macid = models.CharField(max_length=100, unique=True) product_name= models.CharField(max_length=100) product_status = models.CharField(max_length=100, default='Unallocated') device_ip = models.GenericIPAddressField(default="10.0.0.1") white_label = models.CharField(max_length=100, default='') hardware_version = models.CharField(max_length=100, default='Unknown') last_online = models.DateTimeField(auto_now=True) modified_date = models.DateTimeField(auto_now=True) created_date = models.DateTimeField(auto_now_add=True) def set_ip(self, ip): self.device_ip = ip self.save() #code #getting IP is serializer from API payload. product = Product.model.get(macid='0C:F0:B4:24:69:3A') product.set_ip(IP) Below is the traceback of error #### Traceback <The complete stack trace of the error.> Internal Server Error: /productstatus Traceback (most recent call last): File "/usr/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 819, in parse return handler(self, statement) File "/usr/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 939, in _update self._query = UpdateQuery(self.db, self.connection_properties, sm, self._params) File "/usr/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 312, in __init__ super().__init__(*args) File "/usr/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 74, in __init__ self.parse() File "/usr/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 331, in parse c = self.where = WhereConverter(self, tok_id) File "/usr/lib/python3.6/site-packages/djongo/sql2mongo/converters.py", line 24, in __init__ self.parse() File "/usr/lib/python3.6/site-packages/djongo/sql2mongo/converters.py", line … -
How to change the value of model field when button is clicked in django?
I'm making a django app in which the homepage shows list of internships available of different companies.A user of usertype=Student can view those internships. Each internship list view has a button named 'Apply' when apply is clicked I want the booleanfield in my django model(StudentApplying) named applied to be set to true. So that the company who created this post can view the list of students who applied and then can accept/reject them. I don't want to use ajax,javascript etc unless there is no way I can't do it with django itself. models.py from django.db import models from InternsOnboardMain.models import internshipPost from django.contrib.auth.models import User class StudentApplying(models.Model): companyName = models.ForeignKey(internshipPost,on_delete=models.CASCADE) studentName = models.ForeignKey(User,on_delete=models.CASCADE) applied = models.BooleanField(default=False) view.py(I've tried this but it is not working) from django.shortcuts import render, redirect,get_object_or_404 from django.contrib import messages from django.contrib.auth.decorators import login_required from .models import StudentApplying from django.contrib.auth.models import User from django.db.models import F def applyStatus(request): if request.GET.get('applybtn'): profil = get_object_or_404(StudentApplying, created_by=request.user) profil.applied = True profil.save(update_fields=["applied"]) return redirect('InternsOnboard-Home') I have not used any forms.py html file -
Best place to retry a task in Django: requests or celery task
I am hitting an API using requests library in Django inside a celery task. To be very specific, it fetches some record from database, prepares a json and does a POST request. In the certain case scenario, the call fails with 500 error code. I want to retry the POST request again. What's the best way to go about it and why? Retry the Celery task itself (See implementation) Retry the request using urllib.util.retry (See full implementation) -
How to download the multiple bokeh images as a single report
My application is hosted on Django and one of the html pages shows multiple bar graphs which are drawn using Bokeh. I know we can download each graph separately by using SaveTool icon which comes with Bokeh. Now my requirement is I want to have a export button in the page, when I click on export button, all the images should be downloaded in a single pdf file or any other format what ever is the easier option to implement. Please guide me how can I achieve this? Thanks In Advance. -
Django prefetch_related seem to not work as expected
Descirption There is a Foo model that has a ForeignKey field bar: class Foo(models.Model): ... bar = models.ManyToManyField('bar.Bar', related_name='some_bar') ... Also Foo has get_config() method which returns its fields including bar like: def get_config(self): return { ... 'bar': map(lambda x: x.get_config(), self.bar.all()) ... Now there are 10,000 rows of Foo in the database. There are some Bar rows as well. Trying to retrieve the data about 10,000 Foo including the nested Bar data: query = Foo.objects.all().prefetch_related('bar') return [obj.get_config() for obj in query] Problem The query executes around 6 seconds. If there is no bar field - only 400 milliseconds. The prefetch seems to not work completely bar.get_config() seem to hit the database for each iteration step. It is supposed to simply load all Bar objects once and get config from that bar-query to populate each foo config. -
Django custom management commands still ouputs errors
I'm just trying to use Django mixer library to generate users. Sometimes, when then username already exists, there's an error, and even though I did a try-except and the loop continues, which implies I catch the right exception, the error is displayed (django.db.utils.IntegrityError: Mixer (): ERROR: the value of a duplicated key breaks the unique constraint « auth_user_username_key »). How to hide those errors? class Command(BaseCommand): help = "Populate database for testing purposes only" def handle(self, *args, **options): # Generate a random user for i in range(4000): try: user = mixer.blend(User) person = Person.objects.get(user=user) except IntegrityError: continue -
How to display the image from ImageField() in Django admin interface?
I want to display a small thumbnail-like image in my Django admin interface. How should I do this? Also, It doesnt seem to display any SVG files. Please do help models.py: from django.db import models import os from PIL import Image from datetime import date import datetime from .validators import validate_file_extension import base64 def get_directory_path(instance, filename): today = date.today() t = datetime.datetime.now() day, month, year = today.day, today.month, today.year hour, minutes, seconds = t.hour, t.minute, t.second filename = str(day) + str(month) + str(year) + str(hour) + str(minutes) + str(seconds) + '.png' dir = 'media' path = '{0}/{1}'.format(dir, filename) return path class Image(models.Model): image = models.FileField(upload_to = get_directory_path, null = True , validators=[validate_file_extension]) created_date = models.DateTimeField(auto_now = True) def __str__(self): return str(self.id) -
What signals.py should be for Django Rest Password Reset?
What signals.py should be for Django Rest Password Reset? Or is there another way to set up password reset functionality? -
.only().prefetch_related() gives 'ManyToOneRel' object has no attribute 'attname'
i am fetching required fields of a table after a select_related() and prefetch_related() on the same query using .only() I can't seem to get the result from prefetch_related probably because .only() is restricting access to its result ? I have tried adding prefetch_related field in .only() as well but to no avail. Feedback.objects.all().select_related( 'feedback_option' ).only( 'feedback_option', # tried with and without either one or both of the following 'feedback__remarks', 'feedback__remarks__text' ).prefetch_related( Prefetch( 'feedback__remarks', queryset=FeedbackRemark.objects.all().only('text'), ), ) I am getting the following exception because of this. AttributeError: 'ManyToOneRel' object has no attribute 'attname' I am using django 1.10.5 -
How to create a relative max-length constraint on Many-to-Many field in django?
I'm working on an educational django project as an intern and have got trouble with a database constraint on length of many-to-many field. I have a Trip model that contains a capacity field which is an IntegerField and a passeger field which is many-to-many. So I want to create a constraint that number of passengers of a trip never get more than trip's capacity. Can anybody help me with this problem? I have tied the CheckConstraints but faild to handle it with join attribute. class Trip(models.Model): WAITING_STATUS = 'wa' CLOSED_STATUS = 'cl' IN_ROUTE_STATUS = 'in' DONE_STATUS = 'dn' STATUS_CHOICES = [ (WAITING_STATUS, 'waiting'), (CLOSED_STATUS, 'closed'), (IN_ROUTE_STATUS, 'in route'), (DONE_STATUS, 'done') ] source = gis_models.PointField() destination = gis_models.PointField() is_private = models.BooleanField(default=False) passengers = models.ManyToManyField(Member, through="Companionship", related_name='partaking_trips') groups = models.ManyToManyField(Group, through="TripGroups") car_provider = models.ForeignKey(Member, on_delete=models.SET_NULL, related_name='driving_trips', null=True) status = models.CharField(max_length=2, choices=STATUS_CHOICES) capacity = models.PositiveSmallIntegerField(validators=[MaxValueValidator(20)]) start_estimation = models.DateTimeField() end_estimation = models.DateTimeField() trip_description = models.CharField(max_length=200, null=True) class Companionship(models.Model): member = models.ForeignKey(Member, on_delete=models.CASCADE) trip = models.ForeignKey(Trip, on_delete=models.CASCADE) source = gis_models.PointField() destination = gis_models.PointField() I got error "joined field references are not permitted in this query" when tried to migrate. -
Uncaught TypeError: Cannot read property 'showExportPDFDialog' of undefined at exportToPDF
I try to achieve a method that when I click the button, the webpage can show different views(based on which button I click). But after I run the server, I get this: VM2134:21 Uncaught TypeError: Cannot read property 'showExportPDFDialog' of undefined. I created button divs and used ajax. So if I click Page_1/Page_2/Page_3, the webpage can show up different content. I initial variables Page_1/2/3 and sent them back to Django. In the Django, I will compare data. If they are matched, it will jump to the desired html file web.html <button id="Page_1">customer</div> <button id="Page_2">mobile</div> <button id="Page_3">meeting</div> <script type="text/javascript"> $(document).ready(function(){ var id="Page_1" $("#Page_1").click(function(){ $.ajax({ url:"{% url "sheet" %}", data:{Page_1:id}, success:function(result){$("#vizContainersk").html(result);} }); }); }); ..... the rest of ajax are same as above one view.py @api_view(['GET']) def get_tableau_url(request): return render(request, 'web.html') def sheet(request): url ='http://xx.xx.xxx.xx:8000/trusted?username=some_name&target_site=demo' result = requests.post(url, timeout=15) context={} context['token'] = result.text q1 = request.GET.get('Page_1') s1 = "Page_1" q2 = request.GET.get('Page_2') s2 = "Page_2" q3 = request.GET.get('Page_3') s3 = "Page_3" if (q1 == s1): return render(request, 'sheet0.html', context) if (q2 == s2): return render(request, 'sheet1.html', context) if (q3 == s3): return render(request, 'sheet2.html', context) sheet0.html var viz; function initViz() { var containerDiv = document.getElementById("vizContainer"); var options = { width: '1300px', height: …