Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I'm using vanilla js to make a ajax post request to django
I'm trying to make a ajax post request to django this is js snippet const xhr = new XMLHttpRequest(); console.log(xhr.readyState); xhr.open('POST', ''); var data = '{% csrf_token %}'; console.log(data); console.log(typeof(data)); xhr.setRequestHeader('X-CSRF-Token', data); xhr.onload = function(){ console.log(xhr.readyState); console.log(xhr.status); if(xhr.status == 200){ console.log(JSON.parse(xhr.responseText)); }else{ console.log("Something went wrong!!"); } } xhr.send({'userId' : userId}) } This is my error log I've been getting a 403 forbidden error can anybody help me out? -
How to remove "No File Chosen" from django image form
I have a Django profile edit form. When i render the html page, it gives me the choose file button. But it also has No File Chosen along with it. I want to remove this, and only keep the choose file button part. below if my views.py views.py @login_required def edit_profile_view(request): if request.method == "POST": u_form = UserEditForm(request.POST or None, instance=request.user) p_form = ProfileEditForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, 'Your account has been updated!') return redirect("edit_profile_view") else: u_form = UserEditForm(instance=request.user) p_form = ProfileEditForm(instance=request.user.profile) context = { "u_form": u_form, "p_form": p_form } return render(request, 'users/edit_profile.html', context) here is my forms.py forms.py class ProfileEditForm(forms.ModelForm): image = forms.ImageField(label=('Image'),required=False, error_messages = {'invalid':("Image files only")}, widget=forms.FileInput) class Meta: model = Profile fields = ['image', 'organization', 'name', 'bio'] widgets = { "organization": forms.TextInput(attrs={'class':'form-control'}), "name": forms.TextInput(attrs={'class':'form-control'}), "bio": forms.Textarea(attrs={'class':'form-control', 'rows': 3}) } and here's the html html file <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="col-sm-9" style="float:right;"> <span style="font-size: 12px; color: #6f6f6f;">{{ u_form.username.label }}</span> {{ u_form.username }} </div> <img id="img" src="{{ user.profile.image.url }}"><br> {{ p_form.image }} <!-- the image button part --> </form> this is the important part of the HTML code. The other is just some other stuff. This is where the button … -
The development server provided with django, ./manage.py runserver, no longer updating when changing the views.py code
I am using a virtual machine and the development server provided with django, ./manage.py runserver. Which, was working wonderfully. But now when I run the command ./manage.py runserver, it no longer executes with the most updated code (views.py). I have restarted the virtual machine, the server, etc. But I cannot get it to work. Most answers on stack overflow regarding this topic state that if you're using ./manage.py runserver, you shouldn't run into this problem. So I'm not sure how else I should continue to solve the issue. Any help is appreciated! -
Django Rest Framework Client Authentification
I want to setup an e-commerce store with a Django Rest Framework on the backend and React JS on the frontend and I also want to build a mobile application for the store. I want the api to be only accessible by my React Front End client and my Mobile app, but I want my customers to see the product list without signing up or logging in first. Is there a way to authenticate the client (the application itself) just for one view and all for all other views the user has to authenticate? Do I need to setup an API key? Can you guys help me with some examples please? -
Django: email validation for custom user
In DRF I have a custom user. I have to add an extra validation on the email field. How do I validate it? Every time I try to create a user which has a non-unique email, it gives me the corresponding error. I've tried custom validation in View and Serializer, and they are simply being ignored. I've also tried making a custom UserManager with create_user method, which works with unique emails but it doesn't run if I try to create a user with non-unique email. Same error. P.S. I've also tried changing email field to unique=False and it is still being validated. -
I am trying to add search by deadline. How can I do it in django?
I am trying to add search filters for deadline. Like In one week or 1 one month, but i was able to do it for 1 week, but not sure how to do it for 1 one month as well. I tried but it not showing correct results. Here I am attaching my views function that I defined. def is_valid_queryparam(param): return param != '' and param is not None def filterView(request): qs = Scholarship.objects.all() title_contains_query = request.GET.get('title_contains') financialcoverage_query=request.GET.get('financialcoverage') deadline_query=request.GET.get('deadline') date_min = request.GET.get('date_min') date_max = request.GET.get('date_max') if is_valid_queryparam(title_contains_query): qs=qs.filter(title__icontains=title_contains_query) elif is_valid_queryparam(financialcoverage_query) and financialcoverage_query != 'Choose...': qs=qs.filter(Q(financial_coverage__icontains=financialcoverage_query)).distinct() if is_valid_queryparam(deadline_query) and deadline_query != 'Choose...': qs=Scholarship.objects.filter(end_date=datetime.now().date() + timedelta(days=7)) if is_valid_queryparam(date_min): qs = qs.filter(timestamp__gte=date_min) if is_valid_queryparam(date_max): qs = qs.filter(timestamp__lt=date_max) context = { 'queryset':qs, } return render(request, 'filters.html', context) Here is my left sidebar html: <div class="form-group sm-10 col-sm-10"> <label for="deadline">Deadline</label> <div class="input-group"> <select id="deadline" class="form-control " name='deadline'> <option select>Choose...</option> <option value="{{queryset}}">1 week left</option> {% comment %} <option value="{{queryset}}">2 weeks left</option> {% endcomment %} {% comment %} <option value="{{queryset}}">1 month left</option> {% endcomment %} </select> </div> </div> Here is my search results that I render to this page. <h2>This is the results of your search</h2> {% for post in queryset %} <a href="{{ post.get_absolute_url }}">{{ post.title … -
Getting the iregex of data with the count of and unique regex hits
I have a model Book() with a (title, contents, isbn) etc... I would like to look in the book contents for a iregex and get the values(isbn, title) and add the number of regex hits to that value as well as the number of unique hits on that regex. Is there a Django ORM way to add the columns of info to the query? looking at this I found the correct order of get and value query https://docs.djangoproject.com/en/3.1/ref/models/querysets/ This is as close as I've gotten (correctly) def book_results(self, regex): book_results = Book.objects.values('isbn', 'title').get(contents__iregex=regex) return HttpResponse(f'<h2>{book_results}</h2>') It seems that I want to use some combination of get(), values(), and annotate(). -
How to use variable in HTML img src path
I have the following in an HTML template: <img src="{% static 'display/plots/AAPL.png' %}" alt=""> I also pass a variable called ticker. How can I use it instead of AAPL? -
Can you pass an argument to ListView in Django?
I am creating a Fixture webapp with Django. I have written the class below, which displays a list of first team fixtures. Can I rewrite it as TeamView, then pass the team_id? class FirstView(generic.ListView): template_name = 'fixtureapp/team.html' context_object_name = 'fixtures' def get_queryset(self): """return all first team matches""" return Match.objects.filter(team_id=1).order_by('date') def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) data['page_title'] = '1st Team Fixtures' return data I have the following urls, how would I rewrite these to match? urlpatterns = [ path('', views.HomeView.as_view(), name='home'), path('first', views.FirstView.as_view(), name='first'), path('second', views.SecondView.as_view(), name='second'), as you can see I have currently created a second class called SecondView this is almost a carbon copy of FirstView, not very DRY -
What are the pros and cons of validating email address by code and by activation link. Django
In Django, during site register, input to the EmailField is validated by class EmailValidator: Link to the code. However, this validation looks a little bit lengthy and source consuming to me. After so much checking it is still probable for a validated email address to not be in use. Don't you think it would be much better if email-validation-by-code was totally skipped and authentication was dependent only on the activation link in terms of server resources and time. This would also provide more genuine signups/registers on the website. Almost all webpages today send the user an activation link. It is almost inevitable for servers not to use computational power on sending emails anyway. Is there anything that I miss about validating-by-code? Or are there any situations that activation link method would not work? What is the reason Django chose it that way? Thank you. -
add fields in signup form with custom user model with cookie-cutter config
I add this to my models.py: class User(AbstractUser): """Default user .""" name = CharField(_("Name of User"), blank=True, max_length=255) first_name = None # type: ignore last_name = None # type: ignore is_organisor = models.BooleanField(default=True) is_agent = models.BooleanField(default=False) company = models.ForeignKey("organisation", on_delete=models.CASCADE, related_name='company', default=None) I want to add company fields in my signup.html. As I did not change any thing in cookie-cutter config, how can I add this mandatory field to signup form ? -
Uncaught DOMException: Failed to construct 'WebSocket': The URL 'ws://127.0.0.1:8000:8001/public_chat/' is invalid
Uncaught DOMException: Failed to construct 'WebSocket': The URL 'ws://127.0.0.1:8000:8001/public_chat/' is invalid. at setupPublicChatWebSocket (http://127.0.0.1:8000/:215:28) at http://127.0.0.1:8000/:206:2 setupPublicChatWebSocket @ (index):215 (anonymous) @ (index):206 So, I am working with Python Django Channels and JavaScript. I wanted to build a Websocket with Django and connect to it with Javascript, but now I get this error. So I know, 127.0.0.1:8000:8001/public_chat/ can't be a valid URL :) Here is my Javascript code: <script type="text/javascript"> setupPublicChatWebSocket() function setupPublicChatWebSocket(){ // Correctly decide between ws:// and wss:// var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws"; console.log(ws_scheme) {% if debug_mode %} var ws_path = ws_scheme + '://' + window.location.host + "/public_chat/{{room_id}}"; // development {% else %} var ws_path = ws_scheme + '://' + window.location.host + ":8001/public_chat/{{room_id}}"; // production {% endif %} var public_chat_socket = new WebSocket(ws_path); // Handle incoming messages public_chat_socket.onmessage = function(message) { console.log("Got chat websocket message " + message.data); }; public_chat_socket.addEventListener("open", function(e){ console.log("Public ChatSocket OPEN") }) public_chat_socket.onclose = function(e) { console.error('Public ChatSocket closed.'); }; public_chat_socket.onOpen = function(e){ console.log("Public ChatSocket onOpen", e) } public_chat_socket.onerror = function(e){ console.log('Public ChatSocket error', e) } if (public_chat_socket.readyState == WebSocket.OPEN) { console.log("Public ChatSocket OPEN") } else if (public_chat_socket.readyState == WebSocket.CONNECTING){ console.log("Public ChatSocket connecting..") } } </script>``` -
DRF + not DRF joint authentication
I'm new-ish to Django and Token based authentication and have both a multi page site from django (non-DRF) with standard allauth session-based authentication, and a react app using graphQL on DRF and JWT authentication. They are on different subdomains but use the same django/db instance. I would like my users to be able to log in on either site and navigate to the other and still stay 'authenticated'. i.e. not have to log in again. I was thinking about trying to get my non-DRF site to use JWT, but there doesnt seem to be much online content on this that isnt DRF. Also is it even possible to provide a token cross subdomain? Is this all a pipe dream? Can someone please point me in the best direction to solve this problem? Thanks in advance for your time. -
Change Django domain keeping user authenticated
I am routing a new user from AWS Cognito back to my app, which is served under multiple subdomains. Problem is that Cognito callback url is defined once, so user is ending up on the main domain, instead of his own. This illustrates the situation: #1 - User visits: personal.mydomain.com #2 - User clicks to authenticate on cognito #3 - Cognito sends user to: main.mydomain.com #4 - Django validates cognito session and authenticates the user #5 - User is on its homepage, but under main.mydomain.com I if I use HttpResponsePermanentRedirect to the personal.mydomain.com, user lands as AnonymousUser (cookie with authentication is based on domain) So how do I send the user to its own subdomain already authenticated? -
Translation of a PHP Script to Python3 (Django)
I am attempting to convert from scratch the following PHP script into Python for my Django Project: Note that it is my understanding that this script should handle values sent from a form, sign the data with the Secret_Key, encrypt the data in SHA256 and encode it in Base64 <?php define ('HMAC_SHA256', 'sha256'); define ('SECRET_KEY', '<REPLACE WITH SECRET KEY>'); function sign ($params) { return signData(buildDataToSign($params), SECRET_KEY); } function signData($data, $secretKey) { return base64_encode(hash_hmac('sha256', $data, $secretKey, true)); } function buildDataToSign($params) { $signedFieldNames = explode(",",$params["signed_field_names"]); foreach ($signedFieldNames as $field) { $dataToSign[] = $field . "=" . $params[$field]; } return commaSeparate($dataToSign); } function commaSeparate ($dataToSign) { return implode(",",$dataToSign); } ?> Here is what I have done so far : def sawb_confirmation(request): if request.method == "POST": form = SecureAcceptance(request.POST) if form.is_valid(): access_key = 'afc10315b6aaxxxxxcfc912xx812b94c' profile_id = 'E25C4XXX-4622-47E9-9941-1003B7910B3B' transaction_uuid = str(uuid.uuid4()) signed_field_names = 'access_key,profile_id,transaction_uuid,signed_field_names,unsigned_field_names,signed_date_time,locale,transaction_type,reference_number,amount,currency' signed_date_time = datetime.datetime.now() signed_date_time = str(signed_date_time.strftime("20%y-%m-%dT%H:%M:%SZ")) locale = 'en' transaction_type = str(form.cleaned_data["transaction_type"]) reference_number = str(form.cleaned_data["reference_number"]) amount = str(form.cleaned_data["amount"]) currency = str(form.cleaned_data["currency"]) # Transform the String into a List signed_field_names = [x.strip() for x in signed_field_names.split(',')] # Get Values for each of the fields in the form values = [access_key, profile_id, transaction_uuid,signed_field_names,'',signed_date_time,locale,transaction_type,reference_number,amount,currency] # Insert the signedfieldnames in their place in the list … -
Django Observer pattern errors
I am trying to learn the Observer design pattern in Django, for that purpose I am trying to send a confirmation email for any order that has been placed. I was able to implement the email functionality using inbuilt Django email.send() function. I am trying to work this solution in the Observer design pattern. I have run into this error. I am fairly new to Django and any help would be greatly appreciated. Here is my models.py where I am trying to implement the observer calls: class FullOrder(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,null=True) recepient_fullname = models.CharField(max_length=100, null=True, blank=False) phone_no = models.IntegerField(null=True, blank=False) address_line1 = models.CharField(max_length=200, null=True, blank=False) address_line2 = models.CharField(max_length=100, null=True, blank=True) city = models.CharField(max_length=200, null=True,blank=False) state = models.CharField(max_length=200, null=True,blank=False) country = models.CharField(max_length=100, null=True, blank=False) zipcode = models.CharField(max_length=200, null=True,blank=False) amount = models.IntegerField(null=True,blank=True) transaction_id = models.CharField(max_length=100,null=True,blank=False) date_ordered = models.DateTimeField(auto_now_add=True,null=True,blank=True) success = models.BooleanField(null=False,default=True) def successOrder(self,user_id): print(user_id) adr = ShippingAddress.objects.get(user_id) template = render_to_string('store/email_template.html', {'name':adr.recepient_fullname}) email = EmailMessage( 'Thank you for your order2', template, settings.EMAIL_HOST_USER, [adr.email], ) email.fail_silently=False email.send() def __str__(self): return '{}-{}'.format(self.recepient_fullname,self.id) class sendEmail: def __init__(self, user_id=[]): self.user_id = user_id self.Model = FullOrder() def sendmail(self, user_id): self.Model.successOrder(user_id) Here is my ObserverPattern.py with 2 classes. class UserOrderCore: def init(self, user_id): self._observers = [] self.user_id = user_id … -
how to substitute Chinese characters instead of English characters?
I want to use Chinese characters instead of English characters so I searched about it and I found the solution but the thing I can't do is I need to refer to the same slug which calls "t_slug" and duplicated for two or three times depending on using it but Regex prevents that to occur so, my solution I thought it will be good is to use a "or"'s logic in case of the first slug not found the second slug will active and so on. here is my code please check on it and solved it with me. please if you have a better solution for that don't hesitate, however, if you have this solution and other solutions it will be better also for the comming generations. urls.py from django.urls import path, re_path from . import views import re urlpatterns = [ path("find/", views.search, name="search"), # path("search-details/<slug:t_slug>/", views.search_details, name="details"), re_path("^search-details/(?P<t_slug>[\u4e00-\u9fff]+)(?P<t_slug>)/$", views.search_details, name="details"), ] views.py def search_details(request, t_slug=None): if t_slug: try: word = Words.objects.get(orth=t_slug) except: return redirect("accounts:index_404") return render(request, 'search/details.html', {'get_sentence': t_slug}) Note: the original table has no slug in the first place but I do pass the argument character as a parameter in the HTML template and the code … -
Updating elements in a for loop real-time using jquery
I'm currently trying to update all the element in the list by just modifying one element $(".input").on('input', function(){ {% for progress in permit_progress_list %} var member_id_value = $("#"+{{progress.pk}}).val(); alert(member_id_value) member_id_value = parseInt(member_id_value); var oldValue = this.defaultValue; oldValue = parseInt(oldValue); var outcome_for_permit_customer = parseInt(({{project.permit_price}} * member_id_value)/({{permit_total}} - oldValue + member_id_value )) var outcome_for_permit_vendor = parseInt(({{project.architect_payout}} * member_id_value)/({{permit_total}} - oldValue + member_id_value)) var outcome_for_construction_vendor = parseInt(({{project.project_manager_payout}} * member_id_value)/({{construction_total}} - oldValue + member_id_value)) var outcome_for_construction_customer = parseInt(({{project.construction_price}} * member_id_value)/({{construction_total}} - oldValue + member_id_value)) var customer_cost_permit = $("#customer_permit"+member_id).val(outcome_for_permit_customer); var vendor_cost_permit = $("#vendor_permit"+member_id).val(outcome_for_permit_vendor); var customer_cost_construction = $("#customer_construction"+member_id).val(outcome_for_construction_customer); var vendor_cost_construction = $("#vendor_construction"+member_id).val(outcome_for_construction_vendor); {% endfor %} }); -
How can I restore my database data with only postgres dump on heroku
I reached to the build limit on my heroku app while there was a lot changes I still wanted to make and I decided to create the another app and use the same database as the first app and thereafter delete the first app and rename the second app I created to the deleted first app's name but when I deleted the first app I ran into an issue database was also deleted but before deleting that app I downloaded postgres dump for backup so now I uploaded it to my github to just restore my data. And now I'm running the following command heroku pg:backups:restore 'https://github.com/myusername/repo/path/branch/latest.dump' --app myappname --c onfirm myappname but I'm getting the following error Restoring... ! ! An error occurred and the backup did not finish. ! ! waiting for restore to complete ! pg_restore finished with errors ! waiting for download to complete ! download finished with errors ! please check the source URL and ensure it is publicly accessible ! So I want to know if there is anything I can do to perfome backup or I'm just wasted, realy need your help Thanks in advance -
Translate SQL max() group by to Django
I have a table with two columns: listing and bid. Each listing can get multiple bids. I want to run a Django query that returns the highest bid for each listing. In SQL I would do this: SELECT listing, max(amount) FROM Bid GROUP BY listing In django I tried this. It only returns the single highest bid in the whole table Bid.objects.values('listing','amount').aggregate(Max('amount')) -
Boolean field is not updated via Queryset or save()
I have this code. def status(request, item_id): item = AuctionList.objects.get(id=item_id) statusitem = bool(item.status) if statusitem == True: item.status = False item.save() return HttpResponseRedirect(reverse("index")) else: item.status = True item.save() return HttpResponseRedirect(reverse("index")) When executing the page, the "view" is executed, but the change of status is not saved in the database. Do you know what could be happening? -
Can you have the same Django App on two different servers?
Can I have a Django App on Machine A, which takes care of all the routing and the same "stripped" App on Machine B (with some more computation power) that's only used for running jobs to modify some fields of a model thus don't have all the views, templates etc. but only used to call some MyModel.objects.get(user=my_user).save()? -
How to make a success ulr for my contact page
I want the client to be redirected to another HTML page as a successfully sent message in my contact form. But I don't know exactly what is wrong here. I can't redirect to my success page but the form works. #my main app's url.py urlpatterns = [ path('^contact/', include('contactus.urls')), ] #my contact app url.py from __future__ import unicode_literals from django.conf.urls import url from django.views.generic import TemplateView from .views import ContactUsView urlpatterns = [ url(r'^$', ContactUsView.as_view(), {}, 'contactus'), url(r'^success/$', TemplateView.as_view(), {}, 'contactus-success'), ] #contact app view.py from __future__ import unicode_literals from django.conf import settings from django.core.mail import EmailMessage from django.template import loader from django.views.generic.edit import FormView from contactus.forms import ContactUsForm class ContactUsView(FormView): template_name = 'contactus/contact.html' email_template_name = 'contactus/contact_notification_email.txt' form_class = ContactUsForm success_url = "/contact/success/" subject = "Contact Us Request" def get_initial(self): initial = super(ContactUsView, self).get_initial() if not self.request.user.is_anonymous: initial['name'] = self.request.user.get_full_name() initial['email'] = self.request.user.email return initial def form_valid(self, form): form_data = form.cleaned_data if not self.request.user.is_anonymous: form_data['username'] = self.request.user.username # POST to the support email sender = settings.SERVER_EMAIL recipients = (getattr(settings, 'CONTACT_US_EMAIL'),) reply_to = form_data.get('email') or sender tmpl = loader.get_template(self.email_template_name) email = EmailMessage( self.subject, tmpl.render(form_data), sender, recipients, reply_to=[reply_to], ) email.send() return super(ContactUsView, self).form_valid(form) #contact app forms.py from __future__ import unicode_literals from django … -
Django: unable to display iunformation using a TemplateView Class Based view
I'm using a Class Based view (TemplateView) to display some information from a User and a UserProfile model (onetoone between User and UserProfile) and this is working as expected. I decided to use the same TemplateView to display some other data from 2 models and I don't understand why I cannot retrieve and display information. I suspect this is because one of the models (UserSubscription) has 2 fks, one to User model, and another one to "Subscription" model. I've tried to use related_name in the fks but not sure I'm using it correctly. Hereunder the code: models.py class UserSubscription(models.Model): user = models.ForeignKey(User, related_name= 'tousers', related_query_name='touser', on_delete=models.CASCADE, null=True, blank=True) subscription = models.ForeignKey("Subscription", related_name = 'tosubscriptions', related_query_name='tosubscription',on_delete=models.CASCADE, null=True, blank=True) created_date = models.DateTimeField(auto_now=True, auto_now_add=False, verbose_name="Created Date") subs_status = models.BooleanField(default=False, verbose_name="Subscription Status") expiry_date = models.DateTimeField(auto_now=False, auto_now_add=False, verbose_name="Expiry Date") class Meta: verbose_name = "User Subscription" verbose_name_plural = "User Subscriptions" def __str__(self): return 'User: ' + str(self.user) + ' ' + 'PK: ' + str(self.pk) + ' Subscription :' + str(self.subscription) + ' ' + 'Expiring the : ' + str(self.expiry_date) class Subscription(models.Model): plan_name = models.CharField(max_length=50, null=True, blank=True, verbose_name="Subscription Plan Name") description = models.TextField(verbose_name="Subscription Plan Description") price = models.FloatField(verbose_name="Subscription Plan Price") start_date = models.DateTimeField(auto_now=False, auto_now_add=False, verbose_name="Subscription … -
json merging two datasets on canvas - django
I have a django application which has a canvas that saves the drawing drawn on to the canvas as jason data with points and lines in the databse i am able to save and retrieve these drawings onto canvas i am trying to merge two datasets into one and get it onto canvas say i have a data-1 below {"points":[{"x":109,"y":286,"r":1,"color":"black"},{"x":108,"y":285,"r":1,"color":"black"},{"x":106,"y":282,"r":1,"color":"black"},{"x":103,"y":276,"r":1,"color":"black"},],"lines":[{"x1":109,"y1":286,"x2":108,"y2":285,"strokeWidth":"2","strokeColor":"black"},{"x1":108,"y1":285,"x2":106,"y2":282,"strokeWidth":"2","strokeColor":"black"},{"x1":106,"y1":282,"x2":103,"y2":276,"strokeWidth":"2","strokeColor":"black"}]} data-2 {"points":[{"x":524,"y":343,"r":1,"color":"black"},{"x":523,"y":342,"r":1,"color":"black"},{"x":521,"y":339,"r":1,"color":"black"},{"x":520,"y":334,"r":1,"color":"black"},{"x":514,"y":319,"r":1,"color":"black"}],"lines":[{"x1":524,"y1":343,"x2":523,"y2":342,"strokeWidth":"2","strokeColor":"black"},{"x1":523,"y1":342,"x2":521,"y2":339,"strokeWidth":"2","strokeColor":"black"},{"x1":521,"y1":339,"x2":520,"y2":334,"strokeWidth":"2","strokeColor":"black"},{"x1":520,"y1":334,"x2":514,"y2":319,"strokeWidth":"2","strokeColor":"black"}]} i am trying to combine these two datasets and load into as a single drawing onto canvas at present i am able to load single data by using following javascript if (document.getElementById('JSONLoadData') != null) { // Parsing the loaded drawing from server to a JSON Object var loadedData = JSON.parse(JSONLoadData.value) // Iterating through all the points in the loaded drawing for(let i = 0; i < loadedData['points'].length; i++) { // Saving the point and drawing the same in the svg canvas const point = svg.append('circle') .attr('cx', loadedData['points'][i]['x']) .attr('cy', loadedData['points'][i]['y']) .attr('r', loadedData['points'][i]['r']) .style('fill', loadedData['points'][i]['color']); // Pushing the point inside points array points.push(point); } // Iterating through all the lines in the loaded drawing for(let i = 0; i < loadedData['lines'].length; i++) { // Saving the line and drawing the same in the svg canvas const line = svg.append('line') .attr('x1', …