Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
There is another cms for django?(not "django CMS") or why i should use django cms?
I own a site that sells WordPress templates. Recently, I was trying to create Django-based templates, which I found after a bit of searching on the Django CMS site. But then I went to install it and figure out how to make a template for it, I just realized Just installing Django CMS is difficult for the simple user, but even for me, the programmer, it is difficult to install. Is there no substitute for it? Or how can I make it easier for my users to install? -
Django Manage.py Vlaidation Error if value exist
i want to create a custom validation, but its not working with this conditions. if self.orange==True and self.mango==True: raise ValidationError( { "pineapple": _("do not need to filled"), "grape": _("do not need to filled") } ) -
Shared Post Doesn't Post Images to the Shared Object In the backend
I am having a had time sharing post with my function, My challenge is when ever i share a post the share images in the original post doesn't post the images to the new post image field, but rather it repost the images in the original share post field and so it makes it not possible to show the shared image! my question why am I getting this effect of post being reposted in the original image field and not the new shared post field! hoping for a solution ? Here is my function for sharing post: def share_post(request, pk): original_post = Post.objects.prefetch_related('groupimage_set').get(pk=pk) form = ShareForm(request.POST, request.FILES) if form.is_valid(): new_post = Post( shared_body = request.POST.get('description'), description = original_post.description, username = original_post.username, date_posted = original_post.date_posted, group = original_post.group, video = original_post.video, shared_on = datetime.now(), shared_user = request.user) new_post.save() form = GroupImageForm(request.POST, request.FILES) if form.is_valid(): new_post = form.save(commit=False) for image in original_post.groupimage_set.all(): new_post = GroupImage(post=original_post, group=original_post.group, shared_user=request.user, image=image.image) new_post.save() return redirect('group:main',original_post.group.pk) else: form = GroupImageForm(request.POST, request.FILES) ctx = {'form':form, 'original_post':original_post} return render(request,'group/share_form.html', ctx) Here is my model for images and post class Post(models.Model): group = models.ForeignKey(GroupEx, on_delete=models.CASCADE, related_name="group_post") username = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE ,related_name="group_user") description = models.TextField(max_length=500, blank=True) video = models.FileField(upload_to="group_videos", blank=True) shared_body … -
Convert Django function view to class based view
I do not know how to convert those functions to a class-based view. How to call a filter, add, and remove functions in a class-based view? Should I overwrite functions somehow in the TemplateView? @ login_required def favourite_list(request): new = Post.newmanager.filter(favourites=request.user) return render(request, 'accounts/favourites.html', {'new': new}) @ login_required def favourite_add(request, id): post = get_object_or_404(Post, id=id) if post.favourites.filter(id=request.user.id).exists(): post.favourites.remove(request.user) else: post.favourites.add(request.user) return HttpResponseRedirect(request.META['HTTP_REFERER']) -
How to parse json parallel in django to speed up application
This question is regarding django. How can I parse json and insert them in database in most fastest way possible. Here is the code below identifier = str(uuid.uuid4()) insert = report() insert.id = identifier insert.title = var google_autocomplete_url = "https://google.com/complete/search?client=chrome&q=" insert.null_keywords = ujson.loads(requests.get(google_autocomplete_url+var, headers=headers).text)[1] insert.vs_keywords = ujson.loads(requests.get(google_autocomplete_url+var+"+vs", headers=headers).text)[1] insert.versus_keywords = ujson.loads(requests.get(google_autocomplete_url+var+"+versus", headers=headers).text)[1] insert.or_keywords = ujson.loads(requests.get(google_autocomplete_url+var+"+or", headers=headers).text)[1] insert.and_keywords = ujson.loads(requests.get(google_autocomplete_url+var+"+and", headers=headers).text)[1] insert.like_keywords = ujson.loads(requests.get(google_autocomplete_url+var+"+like", headers=headers).text)[1] insert.with_keywords = ujson.loads(requests.get(google_autocomplete_url+var+"+with", headers=headers).text)[1] insert.near_keywords = ujson.loads(requests.get(google_autocomplete_url+var+"+near", headers=headers).text)[1] insert.is_keywords = ujson.loads(requests.get(google_autocomplete_url+var+"+is", headers=headers).text)[1] insert.for_keywords = ujson.loads(requests.get(google_autocomplete_url+var+"+for", headers=headers).text)[1] insert.to_keywords = ujson.loads(requests.get(google_autocomplete_url+var+"+to", headers=headers).text)[1] insert.without_keywords = ujson.loads(requests.get(google_autocomplete_url+var+"+without", headers=headers).text)[1] insert.can_keywords = ujson.loads(requests.get(google_autocomplete_url+var+"+can", headers=headers).text)[1] insert.why_keywords = ujson.loads(requests.get("https://google.com/complete/search?client=chrome&q=why+"+var, headers=headers).text)[1] insert.where_keywords = ujson.loads(requests.get("https://google.com/complete/search?client=chrome&q=where+"+var, headers=headers).text)[1] insert.who_keywords = ujson.loads(requests.get("https://google.com/complete/search?client=chrome&q=who+"+var, headers=headers).text)[1] insert.when_keywords = ujson.loads(requests.get("https://google.com/complete/search?client=chrome&q=when+"+var, headers=headers).text)[1] insert.will_keywords = ujson.loads(requests.get("https://google.com/complete/search?client=chrome&q=will+"+var, headers=headers).text)[1] insert.are_keywords = ujson.loads(requests.get("https://google.com/complete/search?client=chrome&q=are+"+var, headers=headers).text)[1] insert.which_keywords = ujson.loads(requests.get("https://google.com/complete/search?client=chrome&q=which+"+var, headers=headers).text)[1] insert.can_keywords = ujson.loads(requests.get("https://google.com/complete/search?client=chrome&q=can+"+var, headers=headers).text)[1] insert.how_keywords = ujson.loads(requests.get("https://google.com/complete/search?client=chrome&q=how+"+var, headers=headers).text)[1] insert.what_keywords = ujson.loads(requests.get("https://google.com/complete/search?client=chrome&q=what+"+var, headers=headers).text)[1] insert.save() return HttpResponsePermanentRedirect(identifier+'/') This code is making tremendeous network request over 12 seconds. Because of this the page is just loading and loading. As you can see, there are nearly 22 request which are extremely slow. Any help is appreciated. -
Django custom queryset class slicing not working
We are using a custom object(pas1_objects). Once we perform some filter operation we are getting the below query set. all_users_queryset = ( User.pas1_objects.select_related("userlogindetails", "usermeta", "tenant").filter(data_filter) .exclude( userrolepermissions__role_id__in=["PG", "PD"], tenant_id__in=tenant_ids ) .order_by(*sort_array) ) the output of the above query is - <KafkaPushQuerySet [<User: User object (bbc306a1-3a75-4e5e-a9b4-6dce0b31b4b3)>, <User: User object (8830ecc1-944a-43e3-a701-331122a26c2b)>, <User: User object (25255aa5-31f9-45d4-9158-5225fba24cb3)>, <User: User object (4a24f883-210b-43a6-9b57-f51fac624a09)>, <User: User object (b6b044c6-cf9b-46f9-91d9-3a31cd4f6d30)>]> Slicing on this query set is not consistent. (Pdb) all_users_queryset[0:1] # first slice is giving correct output <KafkaPushQuerySet [<User: User object (bbc306a1-3a75-4e5e-a9b4-6dce0b31b4b3)>]> (Pdb) all_users_queryset[1:2] # this should return 2nd obj in the query set but it return 1st object <KafkaPushQuerySet [<User: User object (bbc306a1-3a75-4e5e-a9b4-6dce0b31b4b3)>]> (Pdb) all_users_queryset[2:3] # this works fine <KafkaPushQuerySet [<User: User object (25255aa5-31f9-45d4-9158-5225fba24cb3)>]> (Pdb) all_users_queryset[0:2] # this is returning 1st two objects but in reversed order. <KafkaPushQuerySet [<User: User object (8830ecc1-944a-43e3-a701-331122a26c2b)>, <User: User object (bbc306a1-3a75-4e5e-a9b4-6dce0b31b4b3)>]> (Pdb) all_users_queryset[0:3] # this is returning correct objets and in correct order. <KafkaPushQuerySet [<User: User object (bbc306a1-3a75-4e5e-a9b4-6dce0b31b4b3)>, <User: User object (8830ecc1-944a-43e3-a701-331122a26c2b)>, <User: User object (25255aa5-31f9-45d4-9158-5225fba24cb3)>]> What can be causing this inconsistency? Thanks!!! -
How do I optimize ORM queries for faster results?
I have 80k+ Entries in table(Model) Calendar. When I run either of the following 2 methods, the filter or get is taking too Long to execute and due to which server is getting crashed after sometime and no new entries are getting added. I want to know if there are any more methods from which I can solve this issue? Method 1: date_list = [] d1 = date(2022, 5, 1) d2 = date(2022, 6, 30) delta = d2 - d1 for i in range(delta.days + 1): date_list.append(d1 + timedelta(days=i)) profiles = Profile.objects.all() for j in date_list: for i in profiles: try: Calendar.objects.get(date=j,emp_id = i.emp_id) except Calendar.DoesNotExist: e = Calander() e.team = i.emp_process e.date = j e.emp_name = i.emp_name e.emp_id = i.emp_id e.emp_desi = i.emp_desi e.att_actual = "Unmarked" e.save() and another method (Method 2): date_list = [] d1 = date(2022, 5, 1) d2 = date(2022, 6, 30) delta = d2 - d1 for i in range(delta.days + 1): date_list.append(d1 + timedelta(days=i)) profiles = Profile.objects.all() for j in date_list: for i in profiles: cal = Calander.objects.filter(date=j,emp_id = i.emp_id).count() if cal < 1: e = Calander() e.team = i.emp_process e.date = j e.emp_name = i.emp_name e.emp_id = i.emp_id e.emp_desi = i.emp_desi e.att_actual = … -
Save a CSV to a model in Django
I am trying to develop a view that saves a CSV fields to a table in a Django model and then save the whole CSVto another table with a fileField. However when I try to save the whole CSV I get: The 'file' attribute has no file associated with it. Why is this? how should I save the CSV to the fileField? models.py: class wordsFile(models.Model): table = models.ForeignKey(WordsTable, on_delete=models.CASCADE) file = models.FileField(upload_to='uploads/%Y/%m/%d/') def save(self, *args, **kwargs): self.file.save(self.file.name, self.file) views.py: def home(request): tp = request.POST.get('tp') elif tp == "Upload CSV": if request.user.is_authenticated: upCSV = request.FILES.get('upload') decoded_file = upCSV.read().decode('utf-8') file = wordsFile().save(decoded_file, save=True) #Here is where I try to save the whole CSV to the fileField of the wordsFile model. io_string = io.StringIO(decoded_file) usr = User.objects.get(username=request.user) for idx,row in enumerate(csv.reader(io_string, delimiter=',')): if idx!=0: wt = WordsTable() wt.user = usr wt.word1 = row[0] wt.word2 = row[1] wt.word3 = row[2] wt.word4 = row[3] wt.word5 = row[4] wt.save() return redirect("home") -
utilisation des relation many to many et one to many entre 3 models en meme temps
Bonjour, je suis nouveau avec django, je souhaite si possible avoir votre apport sur un sujet qui me bloque. je sais faire des relation one to many et many to many avec Django, seulement je suis particulièrement bloqué pour le coup. j'ai trois table(motif,document,dossier), les table motif et document sont lié par une relation many to many,et les table motif et dossier liés par une relation one ton many. je souhaite que en choisissant un motif dans dossiers, tous les document qui sont lié à lui apparaissent dans dossiers. class Motif(models.Model): m_designation=models.CharField(max_length=50) document=models.ManyToManyField(Document) create_time=models.DateTimeField(auto_now_add=True) def __str__(self): return self.m_designation # Create your models here. class Dossier(models.Model): statut=(('Valider en Agance','Valider en Agance'), ('Valider controle BEAC','Valider controle BEAC'), ('Rejeter Controleur BEAC','Rejeter Controleur BEAC') ) devise=(('Euro','EUR'), ('Dollar Americain', 'USD'), ('YEN','JPY'), ('MAD','MAD') ) agence=models.ForeignKey(Agence,null=True,on_delete=models.SET_NULL) raison_sociale=models.CharField(max_length=50) Numero_de_Compte=models.CharField(max_length=50) motif=models.ForeignKey(Motif,null=True,on_delete=models.SET_NULL) devise=models.CharField(max_length=50,choices=devise,default='EUR') cours=models.FloatField(default=650) mt_devise=models.FloatField() beneficiaire=models.CharField(max_length=50) statut=models.CharField(max_length=50,choices=statut,default='Valider en Agance') create_time=models.DateTimeField(auto_now_add=True) def mt_xaf(self,): return int (self.mt_devise * self.cours) # Create your models here. class Document(models.Model): designation=models.CharField(max_length=50) create_time=models.DateTimeField(auto_now_add=True) def __str__(self): return self.designation -
need help in django form ajax implementation, 500 (Internal Server Error)
I'm trying to make a app just like facebook or any social media, the problem starts in my comment section where I implemented ajax. I'm guessing the problem lays in csrfmiddlewaretoken html file script tag here's the view.py Views.py -
How can i filter parents that has at least one active child on parent child relationship model
I have "Category" model which has multiple parent/child relationship. class Category(models.Model): pass class CategoryParent(models.Model): parent_category = models.ForeignKey("Category", related_name="children", on_delete=models.CASCADE) child_category = models.ForeignKey("Category", related_name="parents", on_delete=models.CASCADE) is_active = models.BooleanField(verbose_name=_("Is active?"), default=True) class CategoryExlusion(models.Model): browser = models.ForeignKey("Browser", on_delete=models.CASCADE) country = models.ForeignKey("Country", on_delete=models.CASCADE) category = models.ForeignKey("Category", on_delete=models.CASCADE) I want to list all top-level categories that have at least one active child category. If there is a record on the CategoryExlusion list for a category and the requested user's browser and country, that means this category is not active for this user. I can reach the user's browser and country with request.user.browser and request.user.country. The most difficult issue I'm dealing with is the possibility that my child will have children. -
Creating model and views
I would need help creating models and views for my project. I need a model that will extend the auth.user model that I use to authorize users. There should also be three int columns, game1-score, game2-score, and game3-score, in this model, into which I will insert data using views. I need to make sure that the logged-in user is found in views and then find out if his record already exists in the created model and insert the score into the correct column using the value game_id, which also comes with a score to views, and if the column already has a value he has to compare it with the new one and save the bigger one. I would really appreciate the help, especially with the views part, I have a model created somehow, but I don't know if well, see below. class UserGameScore(models.Model): user_rec = models.ForeignKey(User, on_delete=models.CASCADE) game1_score = models.IntegerField(null=True, blank=True) game2_score = models.IntegerField(null=True, blank=True) game3_score = models.IntegerField(null=True, blank=True) -
UnboundLocalError: local variable 'currency' referenced before assignment Django
There are many questions with this similar error but can't find the particular solution to my case. I have a form that has a list of currency symbols, when selected by the user, the values on the page will change. I am using the symbol selected by the user as a dict key to change the rates. However, I'm getting the error in the title. FORM class CurrencyForm(forms.Form): currency = forms.ChoiceField(initial=('USD', 'USD'), choices=['USD', 'AUD', 'GBP' 'CAD'], label='Choose Currency:') VIEW class MyDashboardView(TemplateView): template_name = 'coinprices/my-dashboard.html' def get(self, request, **kwargs): form_c = CurrencyForm(prefix='form_c') return render(request, self.template_name, { 'form_c': form_c, }) def post(self, request): form_c = CurrencyForm(request.POST, prefix='form_c') if request.method == 'POST': if form_c.is_valid(): currency = form_c.cleaned_data['currency'] rates = {'USD': 1.0, 'AUD': 1.321, 'GBP': 0.764, 'CAD': 1.249} deposit = 10000 / rates['currency'] context = { 'deposit': deposit } return render(request, 'coinprices/my-dashboard.html', context) HTML <span> <form method="post"> {% csrf_token %} {{ form_c.as_p }} <button class="btn btn-outline-success btn-sm">Submit</button> </form> </span> UnboundLocalError: local variable 'currency' referenced before assignment -
Dynamic Extraction from MySQL cloud database
I have a django project connected to a MySQL cloud table that extracts charts from the downloaded data. the database is huge (more than 10M rows and 30 columns), I want to dynamically extract data from the table in the fastest and most efficient way so that users don't have to wait 10 minutes to load the charts. I'm thinking about doing a one time full extraction and then saving the extracted data somehow in the django project, and then tell the script to only download new data on the table. what would be the best approach for this? -
Django Unit Testing for standalone variables (coverage)
I'm starting to write unit tests for a django project, and running coverage shows I have 0% coverage over a simple list of tuples. Example: STATE_CHOICES = [ ("MO", "Missouri",), ("AL", "Alabama",), ] Is there some kind of test I could write to get coverage over this list of tuples? I assumed simple len() > 0 and is not None tests would cover it, but apparently not. -
django: pass json string to url as parameter
How can I define a regex for pass json string to url as parameter in django framework? Now I use (?P<query>\w+) but it doesn't work because json string is a entire string made with different words. Using the URLconf defined in giustiziasite.urls, Django tried these URL patterns, in this order: ^pygiustizia/ ^exportcsv-show-results/q/(?P<query>\w+)$ [name='exportcsv-show-results'] admin/ The current path, pygiustizia/exportcsv-show-results/q/{"query": {"bool": {"must": [], "should": []}}, "_source": ["annoruolo", "annosentenza", "codiceoggetto"]}, didn’t match any of these. -
why i am unable to load static files in django?
SCREENSHOT IMAGE you can check my project structure and code in the above screen shot. when I give the command 'python manage.py collectstatic' in my terminal, it's collecting only the default django admin dashboard related static files, but it's not collecting the static files which are in the folder 'home/static/' can you please check what's wrong in that? -
How to do SELECT/DELETE WHERE column IN list in Django
Let us say I have model like this: class Tmp(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) Then we have a list of id's let us say (1, 4, 5, 9, 10) and let us say I want to run: SELECT * FROM tmp WHERE id IN (1, 4, 5, 9, 10) or I want to delete these users: DELETE FROM tmp WHERE id IN (1, 4, 5, 9, 10) How do I achieve this in Django? I believe if I only wanna do it on primary keys, I can use filter and achieve something like this for select: Tmp.objects.filter(pk__in=(1, 4, 5, 9, 10)).get() or like this for delete: Tmp.objects.filter(pk__in=(1, 4, 5, 9, 10)).delete() However, what if I do not want to use the primary key? How can I achieve the same effect? As an example what if I wanted to delete or select by name? -
How do I pass a specific CustomUser to the class-based CreateView in Django?
After finishing a tutorial, I decided to convert the function-based views in the app to class-based views as a way to learn both better. But I got stumped with passing the fields of a CustomUser to the CreateView: #model: class CustomUser(AbstractUser): user_type_data=((1,"HOD"),(2,"Staff"),(3,"Student")) user_type=models.CharField(default=1, choices=user_type_data, max_length=10) class Staff(models.Model): id=models.AutoField(primary_key=True) admin=models.OneToOneField(CustomUser, on_delete=models.CASCADE) email=models.EmailField() address=models.TextField(blank=True) objects=models.Manager() #view: @method_decorator(csrf_exempt, name='dispatch') class SubjectCreateView(CreateView): model = Subject fields = ['id', ... ] What I want to put in the fields= are: staff.first_name, staff.last_name, but none of the combinations I tried worked. This is my first encounter with CustomUser, so my searches weren't fruitful. Appreciate some pointers. -
I am unable to use function inside another function in django
@csrf_exempt def handlerequest(request): # paytm will send you post request here form = request.POST response_dict = {} for i in form.keys(): response_dict[i] = form[i] if i == 'CHECKSUMHASH': checksum = form[i] verify = Checksum.verify_checksum(response_dict, MERCHANT_KEY, checksum) if verify: if response_dict['RESPCODE'] == '01': print('payment succesfull') def function_name(request): UserProfile.objects.filter(user=request.user).update(payment=True) else: print('payment was not successful because' + response_dict['RESPMSG']) return render(request, 'app/paymentstatus.html', {'response': response_dict}) -
'flex' applies the same CSS property as 'hidden'
The error is 'flex' applies the same CSS property as 'hidden'. and also vice versa 'hidden' applies the same CSS property as 'flex'. -
Django websites not loading
I have two Django websites on one server running off Apache with mod_wsgi on Windows 10. For some reason the Django websites don't load, however, I have a normal website that does. I've had it work in the past when I was using one, but I had to change some stuff to make two work. I understand Linux is better for this, however, I understand Windows better as I have more experience with it. Here is my config file and WSGI files for both websites, thank you WSGI 1 import os import sys from django.core.wsgi import get_wsgi_application # Add the site-packages of the chosen virtualenv to work with sys.path.append('C:/xampp/htdocs/neostorm') sys.path.append('C:/xampp/htdocs/neostorm/neostorm') os.environ["DJANGO_SETTINGS_MODULE"] = "neostorm.settings" application = get_wsgi_application() WSGI 2 import os import sys from django.core.wsgi import get_wsgi_application import site # Add the site-packages of the chosen virtualenv to work with site.addsitedir('C:/Users/taber/.virtualenvs/htdocs-auttCy-h/Lib/site-packages') sys.path.append('C:/xampp/htdocs/astinarts') sys.path.append('C:/xampp/htdocs/astinarts/astinarts') os.environ["DJANGO_SETTINGS_MODULE"] = "astinarts.settings" application = get_wsgi_application() My Vhosts ##<VirtualHost *:80> ##ServerAdmin webmaster@dummy-host.example.com ##DocumentRoot "C:/xampp/htdocs/dummy-host.example.com" ##ServerName dummy-host.example.com ##ServerAlias www.dummy-host.example.com ##ErrorLog "logs/dummy-host.example.com-error.log" ##CustomLog "logs/dummy-host.example.com-access.log" common ##</VirtualHost> #LoadModule wsgi_module "C:/Users/taber/AppData/Local/Programs/Python/Python310/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd" ##<VirtualHost *:80> ##ServerAdmin webmaster@dummy-host2.example.com ##DocumentRoot "C:/xampp/htdocs/dummy-host2.example.com" ##ServerName dummy-host2.example.com ##ErrorLog "logs/dummy-host2.example.com-error.log" ##CustomLog "logs/dummy-host2.example.com-access.log" common ##</VirtualHost> LoadFile "C:/Users/taber/AppData/Local/Programs/Python/Python310/python310.dll" LoadModule wsgi_module "C:/Users/taber/.virtualenvs/htdocs-auttCy-h/Lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd" WSGIPythonHome "C:/Users/taber/.virtualenvs/htdocs-auttCy-h" ################################################################################################## # ASTINARTS.UK.TO VIRTUAL HOST # ################################################################################################## <VirtualHost *:443> ServerName … -
How can I use the django as database layer in the API application developed in Flask?
I want to use the Django as database module like an installable module in an API application developed in Flask -
django 'str' object has no attribute 'id' in getlist()
I have this function that I tried to use to perform a delete operation on some items def return_buk(request): books = Books.objects.all() selected = request.POST.getlist('marked_delete') for book in books: for select in selected: if select.book_id_id == book.id: print(select.id) However, when I try to access the attributes, I get an error like this. Obviously the items in the getlist are coming as in str format. How can I get their attributes? 'str' object has no attribute 'id' -
Browser not setting cookie (set-cookie is in the header) - Django backend, Express fetch frontend
Apologies if this has been asked before, but I've scoured Google for 5 days and am just plain stuck. I have a Django/DRF API backend that I'm POSTing login credentials to and expecting a "sessionid" cookie in return. It's running at https://url.com/api/. The login endpoint is https://url.com/api/api_login/. I'm using ExpressJS and fetch on the frontend to make the call. It's running at https://url.com/. The login form is located at https://url.com/login. I have an Nginx reverse proxy mapping "url.com/api" to "url.com:8002", and "url.com" to "url.com:8003". Here is the simplified code for the backend: # views.py @method_decorator(csrf_exempt, name='dispatch') class ApiLogin(APIView): def post(self, request): form = LoginForm(request.POST) if form.is_valid(): user = authenticate(request, username=form.cleaned_data['username'], password=form.cleaned_data['password']) if user is not None: auth_login(request, user) # at this point, you are either logged in or not if request.user.is_authenticated: response = HttpResponse(f"Successful login for {form.cleaned_data['username']}.") return response else: response = HttpResponse("Login failed.") return response Here is the full code for the frontend: //*** server.js const express = require('express'); const app = express(); app.use(express.static('static')); app.use(express.json()); app.use(express.urlencoded({extended: true})); const router = require('./router'); app.use(router); //*** router.js const express = require('express'); const router = express.Router(); const qs = require('qs'); const fetch = require('node-fetch'); // temporarily running on a self-signed cert, so this …