Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get one choice from tuple in django
''' views.py, This works...But my problem is, how can get_or_create from the NOTIFICATION and save in my db ''' b, created = Notification.objects.get_or_create( user = self.request.user, ) b.save() ''' models.py ''' class Book(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) NOTIFICATION = [ ('This is a book', 'This is a book'), ('This is pen', 'This is pen'), ] notification = models.CharField(max_length=200, choices=NOTIFICATION) def __str__(self): return self.user.username -
Url issue for ViewSet retrieve when pk includes a '.'
I have a ViewSet that looks like this: class Client(models.Model): id = models.CharField(max_length=30, primary_key=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) phone = models.CharField(max_length=20, null=True) email = models.EmailField(null=True) And I'm using the built in urls with: router.register(r'clients', ClientsViewSet) I am having an issue where I am getting a 404 if my primary key includes a '.' character. I don't think that the '.' needs to be escaped. If I remove the '.' from the pk in my database, the lookup works fine. The failing url is: http://localhost:8000/clients/Bill.Murray This one works: http://localhost:8000/clients/BillMurray What would be the cause of this not working? Is there a way around it so that I can do a retrieve with the PK and still have the '.' included? -
Django REST throwing a 404 error on DetailView
I am trying to create a RetrieveUpdateDestroyAPIView in my DJango REST application but I get a 404 error when I try to visit the URL. Here is urlpattern in my urls.py file which maps to the views.py file below re_path(r'^snippets/(?P<username>.+)/(?P<snippet_id>\d+)/$', views.SnippetDetailView.as_view(), name="snippet-detail"), Here is my views.py code. class SnippetDetailView(generics.RetrieveUpdateDestroyAPIView): """ Retrieve, update or delete a snippet. """ permission_classes = [IsOwnerOrReadOnly] serializer_class = SnippetSerializer lookup_url_kwarg = 'snippet_id' def get_queryset(self): self.user = get_object_or_404(User, username=self.kwargs['username']) return Snippet.objects.filter(owner__username=self.user.username) And this is my models.py code class Snippet(models.Model): owner = models.ForeignKey('auth.User', related_name='snippets', on_delete=models.CASCADE) highlighted = models.TextField() # to store representation of code created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, default="", blank=True) code = models.TextField() linenos = models.BooleanField(default=False) language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100) style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100) class Meta: ordering = ["created"] I've been trying to understand what could be wrong with it but am relatively new and I have no idea as to why this is not working. Looked up the documentation and a few examples but I don't see any one of them having multiple named parameters in their urls.py file. I would appreciate any help a lot. -
How can I add captcha to Django login page and receive that?
I have an app Django and I want add this JQuery captcha to login page (I don't want to use Google Capture). The Django login form is very confusing to add captcha for me (I read this form document but this problem is very complex). I add JQuerycode as shown in below, But I don't know how can I send and receive the captcha value : login.html: {% block content %} <form class="fadeIn second" method="post">{% csrf_token %} {{ form.as_p }} <p><label>Please enter the letters displayed:</label> <input type="text" id="defaultReal" name="defaultReal"></p> <button type="submit" class="btn btn-primary"> Login </button> [![login page][2]][2] </form> {% endblock %} But I dont know how can i get value captcha for bellow process : import numpy as np #------------------------------ def rpHash(person): hash = 5381 value = person.upper() for caracter in value: hash = (( np.left_shift(hash, 5) + hash) + ord(caracter)) hash = np.int32(hash) #----------------------------- if rpHash(request.form['realPerson']) == request.form['realPersonHash']: # Accepted else: # Rejected This is default user authentication in Django. forms.py: class AuthenticationForm(forms.Form): """ Base class for authenticating users. Extend this to get a form that accepts username/password logins. """ username = UsernameField(widget=forms.TextInput(attrs={'autofocus': True})) password = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput, ) print(username) error_messages = { 'invalid_login': _( "Please enter … -
"xxxx.ngrok.io refused to connect" by shopify Django App
I am trying the official first Shopify Django app "https://github.com/Shopify/shopify_django_app". I could run successfully throw the "https://partners.shopify.com/" see picture 1, but I have a problem to run it throw my own shop (see picture 2). Thank you in advanced for your help -
Django runs fine locally but one field doesn't exist after deploying to Heroku
I'm still relatively new to django. In my website, I created a new field group in AnonymousStudent model. My Django website runs fine on my local machine, but after deploying to Heroku it says the group field doesn't exist. I got couple of errors when trying to access to different parts in my website. One says: ProgrammingError at ... column "group" of relation "student_anonymousstudent" does not exist LINE 1: ...", "last_active_time", "associate_experiment_id", "group") V... Another one says: ProgrammingError at ... column student_anonymousstudent.group does not exist LINE 1: ...dent_anonymousstudent"."associate_experiment_id", "student_a... And the other one says: InvalidCursorName at ... cursor "_django_curs_139758823008000_sync_1" does not exist The traceback for the last one says: /app/.heroku/python/lib/python3.7/site-packages/django/db/backends/utils.py in _execute 86. return self.cursor.execute(sql, params) ▶ Local vars The above exception (column student_anonymousstudent.group does not exist LINE 1: ...dent_anonymousstudent"."associate_experiment_id", "student_a... ^ ) was the direct cause of the following exception: /app/.heroku/python/lib/python3.7/site-packages/django/db/models/sql/compiler.py in execute_sql 1144. cursor.execute(sql, params) It seems like a migration problem, but when I tried to run python manage.py makemigrations it says nothing changed. settings.py DATABASES = { "default": { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3') } } if 'HEROKU_ENV' in os.environ: ALLOWED_HOSTS.append(".herokuapp.com") DATABASES["default"] = dj_database_url.config( ssl_require=True, engine="django_postgrespool2" ) Procfile release: bash release-tasks.sh web: daphne giks.asgi:application -b 0.0.0.0 -p … -
Getting OperationalError in django
When i am trying to access the Home page i am getting the following error OperationalError at / no such column: articles_article.author_id models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Article(models.Model): author = models.ForeignKey(User, default=None, on_delete=models.CASCADE) title = models.CharField(max_length=50) slug = models.SlugField() body = models.TextField() date = models.DateTimeField(auto_now_add=True) thumbnail = models.ImageField(default='default.png', blank=True, upload_to='profile_pics') def __str__(self): return self.title def __repr__(self): return self.title def snippet(self): return self.body[:50]+'...' def getslug(self): return self.title.lower().replace(' ', '-') djangonautic\views.py from django.http import HttpResponse from django.shortcuts import render from django.apps import apps def about(request): return render(request, "about.html") def home(request): article_model = apps.get_model('articles', 'Article') articles = article_model.objects.all()[0:3] return render(request, "home.html", {'articles': articles}) articles\views.py from django.shortcuts import render, redirect from .models import Article from .forms import ArticleForm from django.utils import timezone from django.contrib.auth.decorators import login_required # Create your views here. @login_required(login_url='users:login') def article_list(request): articles = Article.objects.all().order_by('date') return render(request, "articles.html", {'articles': articles }) @login_required(login_url='login') def article_details( request, slug, pk): article = Article.objects.get(pk = pk) return render(request, "article_details.html", {'article': article}) @login_required(login_url='login') def create_article(request): if request.method == 'POST': form = ArticleForm(request.POST, request.FILES or None) if form.is_valid(): article = form.save(commit=False) article.date = timezone.now() article.slug = Article.getslug(article) article.author = request.user article.save() return redirect('articles:details', slug=article.slug, pk=article.pk) else: form = … -
HTML button onclick action with Django function
HTML form on Django. I want to perform or create web page in which the button performs the action, and in backend I am handling the Django function. The code of HTML file is: <form name="bookappointment" class="form" method="POST"> {% csrf_token %} <br> <input type="hidden", name="selecteddoctornumber" value="{{i.doctornumber}}"> <div class="row"> <div class="col-md-1"></div> <div class="col-md-4"> <button class="btn approve" name="approvebtn">Approved</button> </div> <div class="col-md-1"></div> <div class="col-md-4"> <button class="btn notapprove" name="notapprovebtn">Not Approved</button> </div> <br> </div> <a class="btn cancel" href="requests">Cancel</a> <br> </form> and the other side the Django function is: if request.method == 'POST': if request.POST.get('approvebtn'): for i in doctor: if pendingDoctorNumber == i.contactNumber: i.status = 'Approved' return redirect('request') if request.POST.get('notapprovebtn'): for i in doctor: if pendingDoctorNumber == i.contactNumber: i.status = 'Not Approved' return redirect('request') but its not working any action just get me back to same page -
Adding taxes to a total function in Django
I have made a model for a cart with products in it I just added taxes in the model with a default of 0.14 (as an example in order to change it every time an order is made) I am unable to write it in a function that reads from this model and is multiplied by the taxes percentage. class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) ordered = models.BooleanField(default=False) taxes = models.FloatField(default=0.14) def __str__(self): return self.user.username def get_total(self): total = 0 amount = models.FloatField() for order_item in self.items.all(): total += order_item.get_final_price() if self.coupon: total -= self.coupon.amount return total -
python/Html code to extract entire row based on the primary key onclick
I am beginner into python scripting, however I request help to give me a solution or code inorder to extract entire row on a new page based upon onClick my dictionary text. Here is my code from app: from 'display' app, def hyper(request): context2 = {'post2': ddetails.objects.all()} return render(request, 'display.html', context2) class postListView2(ListView): model = ddetails template_name = 'display.html' context_object_name = 'context2' ordering = ['date_published'] ******display.html**** {% extends 'base.html' %} {% block content %} <div> <form method="post"> {% csrf_token %} <table> {% for post2 in post2 %} <tr> <td>{{ post2.id }}</td> <td>{{ post2.username }}</td> <td>{{ post2.email_id }} </td> <td>{{ post2.job }}</td> </tr> {% endfor %} </table> </form> {% endblock content %} however the above display.html is rendering based on the anchor tag of another html file (home.html) <table> <tr> <th>ID number</th> <th>User Name</th> </tr> {% for post1 in post1 %} <tr> <td><a href="display" target="_blank"><center>{{ post1.id }}</center></a></td> <td><center>{{ post1.username }}</center></td> </tr> {% endfor %} </table> after running the command my page displays as ID Number Username 1 xxxxxx 2 yyyyyy 3 uusdfiasifd I made primary key(ID Number) as anchor and by clicking on 1, it should render display.html in new window with relevant details. -
ReactJS POST error to Django Rest Framework server using axios
I use Django Rest framework session authentication,after user logged in I can do successful POST request (/api/post/1/like/) using browsable API. Why can't I post using axios ? (user instance is must for Django server to save the above API ) I hope POST signal may not know logged in user even though I am loggedin as admin user AXIOS FUNCTION const likebutton = (id)=>{ axios.post(`/api/post/${id}/like/`) } ERROR Error: Request failed with status code 403 at createError (createError.js:16) at settle (settle.js:17) at XMLHttpRequest.handleLoad (xhr.js:61) -
MultiValueDictKeyError at /aarm/signup/ 'email'
if request.method == 'POST': try: is_private = request.POST['is_private'] except MultiValueDictKeyError: is_private = False email = request.POST['email'] print(email,99) first_name = request.data['first_name'] last_name = request.data['last_name'] phonenumber = request.data['phonenumber'] avatar = request.data['avatar'] if email is None: return Response({'error': ' please enter your email '}, status=status.HTTP_400_BAD_REQUEST) if first_name is None: return Response({'error': ' please enter your first name '}, status=status.HTTP_400_BAD_REQUEST) if last_name is None: return Response({'error': ' please enter your last name '}, status=status.HTTP_400_BAD_REQUEST) if phonenumber is None: return Response({'error': ' please enter your phone name '}, status=status.HTTP_400_BAD_REQUEST) if avatar is None: return Response({'error': ' please enter your avatar name '}, status=status.HTTP_400_BAD_REQUEST) user = User.objects.create_user(phonenumber, email, first_name, last_name, avatar) token1 = Token.objects.create(user=user) token = token1.key return Response({'message': 'user register success', 'token': token}, status=status.HTTP_201_CREATED) when email was not sent in post request it gives MultiValueDictKeyError same error gives with other field, I want to give my own error message -
How to write QuerySet for Count as to be Zero
class InventoryData(models.Model): CHOICES = [('In Stock', 'In Stock'), ('Issued', 'Issued'), ('Not Issued', 'Not Issued'), ('Unmanaged', 'Unmanaged'), ('Damaged', 'Damaged'),('Theft', 'Theft'), ('Auctioned', 'Auctioned'), ('Disposed', 'Disposed')] AssetID = models.CharField('Asset ID', max_length=30, unique=True) Make = models.CharField(max_length=30, blank=True, null=True) Model = models.CharField(max_length=30, blank=True, null=True) Status = models.CharField(max_length=30, choices=CHOICES, blank=True, null=True, default='In Stock') Comments = models.TextField(max_length=2000, blank=True, null=True, default="None") class Meta: verbose_name = 'Inventory Data' verbose_name_plural = 'Inventory Data' def __str__(self): return self.AssetID views.py def home(request): #------------- For Models -------------# stnd = obj.objects.filter(AssetID__startswith='ASPL-LAPT').order_by('Model').values_list('Model', flat=True).distinct() dev = obj.objects.filter(AssetID__startswith='ASPLB-DEV').order_by('Model').values_list('Model', flat=True).distinct() mac = obj.objects.filter(Make__startswith='Apple').order_by('Model').values_list('Model', flat=True).distinct() desk = obj.objects.filter(AssetID__startswith='ASPLB-DSK').order_by('Model').values_list('Model', flat=True).distinct() #------------- For count -------------# cnt = obj.objects.filter(Model__in=stnd).values('Model').annotate(Count('id')) cnt1 = obj.objects.filter(Model__in=stnd, Status='In Stock').values('Model').annotate(Total=Count('id')) cnt2 = obj.objects.filter(Model__in=stnd, Status='Issued').values('Model').annotate(Total=Count('id')) cnt3 = obj.objects.filter(Model__in=stnd, Status='Theft').values('Model').annotate(Total=Count('id')) cnt4 = obj.objects.filter(Model__in=stnd, Status='Damaged').values('Model').annotate(Total=Count('id')) cnt5 = obj.objects.filter(Model__in=stnd, Status='Auctioned').values('Model').annotate(Total=Count('id')) cnt6 = obj.objects.filter(Model__in=stnd, Status='Disposed').values('Model').annotate(Total=Count('id')) render_out = zip_longest(stnd, cnt1, cnt2 , cnt3, cnt4, cnt5, cnt6, cnt7, fillvalue=0 context = {'render_out': render_out,} return render(request, 'App/home.html', context) ` In my DB i have 4 models laptops [E5470, E5480, T440, T450], each model has 10 laptops but with below query i am getting below table,for below query i getting as below queryset. a = Obj.objects.filter(Model__in=stnd, Status='In Stock').values('Model').annotate(Total=Count('id')) if i don't have any laptops in "In Stock" i have get respective model with "Total: 0" can any … -
Why my html button is not able to execute the method called update_student stored in my views.py file
---------Here is the html code of the Button by clicking which i want to execte the method-------- Update -
Why does Django App return an empty page?
I am learning how to program using the book Python Crush Course 2nd ed. Currently, I am doing a project that involves building a simple web app using Django. The app allows users to make journal entries about specific topics. I am currently stuck at trying to allow users to add a new topic. Basically, I am adding a form-based page using Django form-bulding tools. My problem: when I go to http://localhost:8000/new_topic/ , it returns an empty white page. But it should return a page that allows users to enter a new topic. What I tried: I reviewed every line of code multiple times, but I cannot find a mistake. I am a newbie, so maybe I have missed something that more experienced eyes would see. Appreciate any and all help. Below is my code so far: models.py from django.db import models class Topic(models.Model): """A topic the user is learning about.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.text forms.py from django import forms from .models import Topic class TopicForm(forms.ModelForm): class Meta: model = Topic fields = ['text'] labels = {'text': ''} urls.py from django.urls import path from . import views … -
"non_field_errors": [ "No data provided" ]
I am trying to get data from the serializer ,but i have a problem that says "non_field_errors": [ "No data provided" ] Here is the part that i am trying to get the data Serializers class ArticleCreateSerializer(serializers.ModelSerializer): author = serializers.SerializerMethodField('_user') def _user(self, obj): request = getattr(self.context, 'request', None) if request: return request.user.profile else: return HttpResponse("User Not Found") caption = serializers.CharField(required=False) details = serializers.CharField(required=False) class Meta: model = Post fields = ('id','author','caption','details') def create(self, validated_data): article = Post.objects.create(author=author,**validated_data) return article Does anybody have any solution to this? -
Encountring an error while doing django development in pycharm i.e operational error/admin
IAM usin pycharm version 3.8.2 for doing web development. While iam running django 2.1 in pycharm it worked everything fine. At /admin while I was trying to add products it is showing OPERATIONAL ERROR/ADMIN/PRODUCTS/ADD. I tried to install django version 2.1.7 it is showing same error again.I tried again with version 3.0.2 it is showing again the same above error. I even tried python manage.py makemigrations command to see if it works nothing change the same error keeps coming in yellow page I want to know what's the problem that iam facing -
django relation "accounts_user" does not exist after heroku upload
I upload my Django web app to Heroku successfully and login page appears as well as expected but when I try login I getting this error: relation "accounts_user" does not exist LINE 1: ...ser"."is_active", "accounts_user"."is_staff" FROM "accounts_... Also I am getting this error when I try to acces ulrs by typing cursor "_django_curs_140062995079296_sync_1" does not exist I don't know where this error Is generating from. But I am using custom user models that I seems the error to be there here is the custom user model I used class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( unique=True) name = models.CharField(max_length=200, null=True) staffType = models.ForeignKey(staffType, null=True, on_delete= models.SET_NULL) date_joined = models.DateTimeField( auto_now_add=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField( default=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = … -
How can i redirect when person type in url browser?
I have two methods ,(register and confirm methods),when submit register,send message in mobile for verification,then person type and the code is correct return return JsonResponse({'code':1,'url': '/user/confirm'}) in jquery code with window.location() ,it will redirect into confirm page, but i want to when person type this url and Enter ,he can not open this page(confirm page) and redirect into other page. -
how do I import my python script into Django views?
The script is a simple guessing game. The end goal is to keep a log of the results. I have tried importing the script 'from guessItApp import gg.Py' in my views but does not work. I was told I can use the tag and that will put my script in the views but will this still record the users input? I am getting all sort of errors. I want to accomplish this without any frameworks just Vanilla JS. What is the best way to do this and how? like step by step. -
Pass multiple parameters in Django
class Article(models.Model): Title = models.CharField(max_length = 255) writing = models.TextField() category = models.CharField(max_length = 225) published = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug = models.SlugField(blank=True, editable=False) def save(self): self.slug = slugify(self.Title) super().save() def get_absolute_url(self): url_slug = {'slug':self.slug} return reverse('artikel:ArticleDetail', kwargs = url_slug) def __str__(self): return "{}.{}".format(self.id, self.Title) i want to build a simple website using django where it could post some articles by form. The problem is how could i post multiple category in one article ? this is form.py below. from .models import Article from django.forms import ModelForm class ArticleForm(ModelForm): class Meta: model = Article fields = [ 'title', 'writing', 'category', ] -
request.user returning abstract user
I am trying to type the following: user: Final[CustomUser] = self.request.user Where CustomUser is my custom user model defined in settings.py. My IDE complains that Expected type 'CustomUser', got 'AbstractBaseUser' instead. Looking at the documentation, it says that self.request.user returns an instance of AUTH_USER_MODEL however clearly this is not happening. -
Django: return same data as PostListView in def post()
Is there a simple way for me to return the same data in post method using PostListView? class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 def post(self, request, *args, **kwargs): *create like in db* *flash message* return *same data as get request* I have a simple Instagram replica app and this post list view shows all posts. Each posts has a like button. If a user clicks on this button it will create a new like object in db and will show a flash message. After that I want to show the same data as there were before clicking the button. Is there a way to do so? -
Django 3.x Python 3.x Forms - 'NoneType' object has no attribute '_prefetch_related_lookups'
I have this form below that cause the error. class ErkbRamsis(forms.Form): def __init__(self, *args, **kwargs): self.transfer_id = kwargs.pop('transfer_id') transfer = Transfer.objects.get(pk = self.transfer_id) if 'coach_id' in kwargs: self.coach_id = kwargs.pop('coach_id') leg = Leg.objects.get(pk = self.coach_id) else: leg = Leg.objects.filter(service = transfer.service).first() super(ErkbRamsis, self).__init__(*args, **kwargs) self.fields['transfer_clients'] = forms.ModelMultipleChoiceField( queryset=Client.objects.filter(related_pnr = transfer.service.related_pnr), widget=forms.SelectMultiple(), required=False, ) self.fields['coach'] = forms.ModelChoiceField( queryset=Leg.objects.filter(service = transfer.service), widget=forms.Select(), empty_label=None, initial=leg, #### for non assigned legs cause error required=False, ) self.fields['coach_clients'] = forms.ModelMultipleChoiceField( queryset = leg.clients, #### for non assigned legs cause error widget=forms.SelectMultiple(), required=False, ) def clean(self, *args, **kwargs): transfer_clients = self.cleaned_data.get('transfer_clients') coach = self.cleaned_data.get('coach') coach_clients = self.cleaned_data.get('coach_clients') return super(ErkbRamsis, self).clean(*args, **kwargs) Scenario: I have 4 models Transfer<= OneToOne => Service <= OneToMany => Leg<= ManyToMany => Client, The form attach the Client objects to the Leg by clients.add(Client). the form cause error when rendering when the Transfer.Service have no Leg objects created and attached to Service. The lines cause the error is marked by comment. -
Javascript is not executing when javascript
I have created a simple javascript function to run in django that automatically changes text within a svg file. The function works fine if I run it inside the webpage console. But nothing inside the script tags will run and I can't figure out why. Looking at the source the template tag is importing the data correctly and the javascript file is found. But nothing runs inside, not even code unrelated to the function - you can see the console.log code I have added. I am quite new to django and website development, so it is unclear to me where I shoud be looking for why this isnt' executing - is there somewhere that errors should be arising? home.html {% extends 'kb/base.html' %} {% load static %} {% block extrahead %} <link rel="stylesheet" href="{% static 'css/kb.css' %}"> <script type="text/javascript" src="{% static "js/fillKinshipDiagram.js" %}"> console.log(4 + 10); var terms = {{ terms|safe }}; window.onload = function() { main(terms); }; </script> {% endblock %} {% block content %} <div class="home-content"> <div class="kinshipdiagram-container"> <object type="image/svg+xml" data="{% static "img/diagrams/nuclear_diagram.svg" %}" id="kinshipdiagram" width="50%" height="50%"></object> </div> </div> {% endblock %} fillKinshipDiagram.js function main(terms){ var svgDocument svgObject = document.getElementById('kinshipdiagram'); svgDocument = svgObject.contentDocument; for (var i = 0; …