Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass all field names to when_any argument of django-lifecycle hook
I am using django-lifecycle to create a function in a model to be run when any input is changed. I'm doing this using the before_update hook, e.g. @hook("before_update", when_any=list_of_fields, has_changed=True) def do_something(self): do something here... I am trying to pass all of the field names to the when_any argument but struggling because the hook argument cannot use self to get this. For example doing: @hook("before_update", when_any=[f.name for f in self._meta.get_fields()], has_changed=True) def do_something(self): do something here... gives the NameError NameError: name 'self' is not defined. Is there a way to get all of the model field names in another way from within the model class? -
Django not rendering the images present in the 'images' folder inside the build folder after merging the react app
I have a React App with a Django rest framework backend. I ran the build command and merged the react app. The react app had an images folder inside the public folder that had some logos and photos that I used during the frontend development. Now after running the build and rendering the site from Django it is unable to render the images. The folder images is present inside the build folder that react gives. Below are my configurations and settings. template settings TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'build'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] static and media files settings STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'build/static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('account/', include("account.urls")), path('teacher/', include("teacher.urls")), path('search/', include("search.urls")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # This is will cath the routes in the frontend and 404 errors urlpatterns += [re_path(r'^.*', TemplateView.as_view(template_name='index.html'))] Please suggest to me what should I do -
DRF using prefetch_related
I have two classes Vessels and Components, each vessel has several components. I just want to fetch all vessels and all their related components in one query, I thought prefretch_related does that trick but in DRF in the api i am only receiving the vessels without their related components models.py class Vessel(models.Model): name = models.CharField(max_length=255, null=True, blank=True) imo = models.CharField(max_length=255, null=True, blank=True) def __str__(self): return self.name class Component(models.Model): vessel = models.ForeignKey( Vessel, blank=True, null=True, on_delete=models.CASCADE, related_name='vessel_components') name = models.CharField(max_length=200, blank=True, null=True) manufacturer = models.CharField(max_length=200, blank=True, null=True) model = models.CharField(max_length=200, blank=True, null=True) type = models.CharField(max_length=200, blank=True, null=True) remarks = models.TextField(blank=True, null=True) def __str__(self): return self.name serializers.py class VesselSerializer(serializers.ModelSerializer): class Meta: model = Vessel fields = '__all__' class ComponentSerializer(serializers.ModelSerializer): class Meta: model = Component fields = '__all__' the view : @api_view(['GET']) def getVessels(request): vessels = Vessel.objects.all().prefetch_related('vessel_components') vSerializer = VesselSerializer(vessels, many=True) return Response(vSerializer.data) the result i am getting : -
Problems with validators in django models
I want to create an edit page where the customer can edit the profile page. I have a problem with the validators and I don't know how to solve this. model.py class UserProfile(models.Model): CAT_G = ( ('W', 'W'), ('M', 'M'), ('do not want to mention', 'do not want to mention'), ) age = models.IntegerField(default=1, validators=[ MaxValueValidator(100), MinValueValidator(1)]) height = models.DecimalField(max_digits=3, validators=[MinValueValidator(Decimal('0.0'))], decimal_places=2) gender = models.CharField(max_length=27, blank=False, null= False, choices=CAT_G) view.py def edit_view(request): context={} if request.method == "POST": form = ProfileUpForm(request.POST, instance=request.user.userprofile) if form.is_valid(): form.save() return redirect('/profPage') else: form = ProfileUpForm( initial={ "age":request.user.userprofile.age, "height":request.user.userprofile.height, "gender":request.user.userprofile.gender, } ) context['profE_form']= form return render(request, 'editPage.html', context) editPage.html {% for fieldProfile in profE_form %} <p> {{fieldProfile.label_tag}} {{fieldProfile}} </p> {% endfor %} The problem is that in the html page, the user can choose a negative number, even if I put that validators in my model. -
Imagefont truetype cannot open resource
Cannot open . ttf file from media folder But it's work Localserver But now the project hosting to pythonanywhere font = ImageFont.truetype("media/arial.ttf", size =16) I got a error this line so i try 3 ways to solve the problem This 3 ways font = ImageFont.truetype("arial.ttf", size =16) font = ImageFont.truetype("fullpath of the file/arial.ttf", size =16) font = ImageFont.truetype("settings.MEDIA_ROOT/arial.ttf", size =16) But it's work ImageFont.load_default() I want 3 different fonts arialbold, arialbt, arialblack, arial So it's work local machine If any package available to install the fonts Thanks to read the question 😊 -
Django query set to display particular field on webpage
I am trying to display the variants(field) that are related to the model RecordVariant on my webpage i have queryset on my view default how can i change my queryset or get queryset method to display variants that are related to particular record. class RecordVariant(models.Model): variants = models.ForeignKey(Variant_model, related_name = 'records', on_delete = models.CASCADE) class Variant(models.Model): name = models.CharField(max_length = 23, blank=True, null=True) class VariantListAPIView(RecordMixin, ListAPIView): lookup_url_kwarg = 'record_id' serializer_class = RecordVariantSerializer permission_classes = [IsAuthenticated] pagination_class = StandardResultsSetPagination filter_backends = (filters.OrderingFilter,) queryset = RecordVariant.objects.all() ordering = 'variants' ordering_param = 'ordering' ordering_fields = ( 'variants', ) def get_total_queryset(self): queryset = ( super() .get_queryset() .filter(record=self.record) ) -
display objects from inline model in DetailView
I have 2 models Product and Resource. Resource has to be a TabularInline model in my admin panel. I am struggling with filtering resource titles that are related only to this product. Since it is a ForeignKey I should use select_related but I am not sure how to use it in my case. For now, the loop in my HTML file gives me all sales files (from all products). models.py class Product(models.Model): id = models.AutoField(primary_key=True) title = models.CharField('title', max_length=400, default='') slug = models.SlugField(unique=True, blank=True, max_length=600) class Resource(models.Model): id = models.AutoField(primary_key=True) type = models.CharField(max_length=32, choices=RESOURCE_TYPE, default='sales') title = models.CharField(max_length=400, blank=False, null=False, default='') related_files = models.FileField(upload_to='recources/', null=True, blank=True) publish = models.DateTimeField('Published on', default=timezone.now) resources = models.ForeignKey(Product, default='', on_delete=models.PROTECT, null=True, related_name='resources') admin.py class Resourceinline(admin.TabularInline): model = Resource class ProductAdmin(ImportExportModelAdmin): inlines = [ Resourceinline, ] resource_class = ProductResource admin.site.register(Product, ProductAdmin) views.py class ProductDetailView(DetailView): template_name = 'ProductDetailView.html' model = Product def get_context_data(self, **kwargs): context = super(ProductDetailView, self).get_context_data(**kwargs) resources_sales = Resource.objects.select_related('resources').filter(type='sales') # not sure what to put here context['resources_sales'] = resources_sales return context ProductDetailView.html {% for resource in resources_sales.all %} <p>{{resource.title}}</p> {% endfor %} Question Where am I making the mistake and how can I display resource objects that are related to type=sales and are related … -
How to update the value of a column in a foreign table in django
I have 2 tables, one of the tables is a foreign table to the other (foreign key). I want to decrease the value of the quantity column of items in the foreign table based on value of the quantity column of the parent table. Below is my code model.py from django.db import models # Create your models here. PAYMENT_METHOD = ( ('CASH', 'cash'), ('TRANSFER', 'transfer'), ) class ItemSold(models.Model): item_name = models.CharField(max_length=80) quantity = models.IntegerField() def __str__(self): return self.item_name class DailySales(models.Model): customername = models.CharField(max_length=100) itemsold = models.ForeignKey(ItemSold, related_name="soldItem", on_delete=models.CASCADE) quantity = models.IntegerField() rate = models.IntegerField() totalprice = models.IntegerField(default=0) datesold = models.DateTimeField(auto_now_add=True, auto_now=False) paymentmethod = models.CharField(max_length=40, choices=PAYMENT_METHOD, default=PAYMENT_METHOD[0][0]) havepaid = models.BooleanField(default=False) datepaid = models.DateTimeField(auto_now_add=False, auto_now=True) class Meta: verbose_name_plural = 'Daily Sales' def __str__(self): return self.customername def save(self, *args, **kwargs): self.totalprice = self.rate * self.quantity super(DailySales, self).save(*args, **kwargs) views.py class DailySalesListView(generics.GenericAPIView): serializer_class = DailySalesSerializer queryset = DailySales.objects.all() name = 'Daily Sales List' filter_backends = (DjangoFilterBackend,) filterset_fields = ('customername','havepaid', 'datesold', 'itemsold', 'datepaid') def get(self, request): sales = self.filter_queryset(self.get_queryset()) serializer = self.serializer_class(instance=sales, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) def post(self, request): data = request.data serializer = self.serializer_class(data=data) if serializer.is_valid(): serializer.save() return Response(data=serializer.data, status=status.HTTP_201_CREATED) return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST) I haven't tried anything yet, I don't know how to go … -
How to install a library and execute the code with a POST request? [Django]
I am trying to execute the python code which I am taking as user input and returning the output of the code but I want to use a library to find the time complexity of the program but it obviously gives module not found error when I try to execute the code with library in it. Here is my frontend which I created using react. Python code is running perfectly when I do not introduce any libraries. What I am doing is I am sending the code to django through REST Api and executing the code writing the output in a file and returning the output as shown below - My viewsets.py file - from rest_framework.viewsets import ModelViewSet from .models import Code from .serializers import CodeSerializer from rest_framework.decorators import action from rest_framework.response import Response from rest_framework.status import HTTP_200_OK, HTTP_204_NO_CONTENT import sys class CodeViewSet(ModelViewSet): queryset = Code.objects.all() serializer_class = CodeSerializer lookup_field = "id" @action(detail=True, methods=["HEAD", "GET", "POST"], url_path="runcode") def runcode(self, request, id=None): if request.method in ("GET", "HEAD"): return Response(status=HTTP_204_NO_CONTENT) else: code_data = self.get_object() try: orig_stdout = sys.stdout sys.stdout = open('file.txt', 'w') exec(code_data.code) sys.stdout.close() sys.stdout = orig_stdout output = open('file.txt', 'r').read() except Exception as e: sys.stdout.close() sys.stdout = orig_stdout output = e … -
python Django running scripts from client side
I have a Python Django project set up. I have a home.HTML file with a button on it. I want the user of the Python Django website to be able to click the button on the home.HTML page and run the Python script. A python script such as scrapy which is located on GitHub (could be any other python script on github). I want the button to trigger the function rather than typing in the console. I then want the result from the script to return in a csv file. How would this be done, can it be done ? -
How to serve phpMyAdmin to localhost/phpMyAdmin instead of localhost:8080 using nginx in docker
In my project, I am using Django and nginx, but I want to manage my cloud databases through phpmyadmin. Django is working fine but I can't do the same with phpmyadmin because it is running in apache at localhost:8080, when I want it to run in nginx at localhost/phpmyadmin. here is the docker-compose.yml version: "3.9" services: web: restart: always build: context: . env_file: - .env volumes: - ./project:/project expose: - 8000 nginx: restart: always build: ./nginx volumes: - ./static:/static ports: - 80:80 depends_on: - web phpmyadmin: image: phpmyadmin/phpmyadmin:latest restart: always environment: PMA_HOST: <host_address> PMA_USER: <user> PMA_PASSWORD: <password> PMA_PORT: 3306 UPLOAD_LIMIT: 300M ports: - 8080:80 and nginx default.conf upstream django{ server web:8000; } server{ listen 80; location / { proxy_pass http://django; } location /pma/ { proxy_pass http://localhost:8080/; proxy_buffering off; } location /static/ { alias /static/; } } I hope somebody will be able to tell me how to make nginx work as a reverse proxy for the phpMyAdmin docker container. If some important information is missing please let me know. -
Django model - can't do aggregate sum with thousand comma separator and decimal points
I have the following model: class Example(models.Model): project_id = models.IntegerField( null=False, blank=False, default=0, ) field1 = models.CharField( max_length=250, null=True, blank=True, ) field2 = models.CharField( max_length=250, null=True, blank=True, ) total = models.CharField( max_length=250, null=True, blank=True, ) Example data: project_id field1 field2 total 1 1,323 4,234.55 5,557.55 2 1,000 2 1,002 3 1.23 3 4.23 total = field1 + field2 I would like to sum all total values. This is what I've tried views.py: context['total'] = Example.objects.filter(project_id=pid).aggregate(Sum('total')) Current output: {'total': 10.23} Expected output: {'total': 6,563.78} Or, if that's not possible at least: 6563.78 so that I can format the numbers later. Since the project requires thousand comma separator and decimal points, I can not change or alter the model fields and use FloatField. Any help would be much appreciated -
how to get the text from user input then set it in to the condition in html template?
I'm doing a lab creating the web view to access the data from mysql, so I have some config below: student\views.py from django.shortcuts import render, redirect from .models import Student # Create your views here. def show(request): students = Student.objects.all() student_dict = {'student':students} return render(request, "show.html",student_dict) student\templates\show.html <!DOCTYPE html> <html lang="en"> <head> <title>Django CRUD Operations</title> <meta charset="utf-8"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <table class="table table-striped"> <thead> <tr> <th>Student ID</th> <th>Roll</th> <th>Class</th> <th>First Name</th> <th>Last Name</th> </tr> </thead> <tbody> {% for stud in student %} <tr> {% if stud.fname == 'abc' %} # I would like to make an input box for user can input here <td>{{stud.id}}</td> <td>{{stud.roll}}</td> <td>{{stud.sclass}}</td> <td>{{stud.fname}}</td> <td>{{stud.lname}}</td> {% endif %} </tr> {% endfor %} </tbody> </table> </div> </body> </html> student\urls.py from django.urls import path from . import views urlpatterns = [ path('show/', views.show), ] I have connectted to database student in mysql already , and could show all or filter which i want by code , now i want to have an input box for user can input their username , then when they click on submit it will show only their info. Could you please assist for my case ? -
How to enable django admin sidebar navigation in a custom view?
I have a view inheriting from LoginRequiredMixin, TemplateView, which renders some data using the admin/base_site.html template as the base. I treat it as a part of the admin interface, so it requires an administrator login. I'd like to make this view a little bit more a part of the Django admin interface by enabling the standard sidebar navigation on the left-hand side. Note that I don't have a custom ModelAdmin definition anywhere, I simply render the template at some predefined URL. There are no models used in the interface either, it parses and displays data from database-unrelated sources. Currently, I just build the required context data manually, e.g.: data = super().get_context_data(**kwargs) data.update(**{ "is_popup": False, "site_header": None, "is_nav_sidebar_enabled": True, "has_permission": True, "title": "My title", "subtitle": None, "site_url": None, "available_apps": [] }) The sidebar is visible, but displays an error message: Adding an app to available_apps ("available_apps": ["my_app"]) doesn't help either: So my question is - how do I do that? Is there a class I can inherit from to achieve this behaviour? Or a method I can call to get all required context data for base_site.html? Or perhaps I should insert some information in my template? Perhaps I need an AdminSite … -
redirect to index page for logged in users in Django
I have a problem if I close a browser page without having logged out and re-enter with another browser tab as the session is still active (and I have the login url in the root, example: http://localhost:8000) it takes me again to the login and I would like that when a user was already logged in it would take me to the index. All are based in function base views. Thank you very much in advance. -
django.db.utils.ProgrammingError: relation "members_profile" does not exist
I am facing this error while creating a profile model of user. IMPORTANT: If I remove the Utility fields it works completely fine. So there must be some issue with it, I Tried removing some lines but nothing seems to work. my code is: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) uusername = models.ForeignKey(User,to_field='username',on_delete=models.CASCADE,related_name="uusername") rolenumber = models.PositiveIntegerField(blank=True,default=0) admission_year = models.PositiveIntegerField(blank=True,default=0) current_class = models.PositiveIntegerField(_('current_class'),choices=CLASS_CHOICES,blank=True,null=True) gender = models.CharField(_('gender'),choices=GENDER_CHOICES,blank=True,null=True,max_length=50) school_branch = models.CharField(_('school_branch'),choices=JAMEA_BRANCH,blank=True,null=True,max_length=50) full_name = models.CharField(_('full_name'),max_length=100,blank=True,null=True) academic_status = models.CharField(_('academic_status'),choices=ACADEMIC_STATUS,blank=True,null=True,max_length=50) #Utility fields uniqueId = models.CharField(null=True, blank=True, max_length=100) slug = models.SlugField(max_length=500, unique=True, blank=True, null=True) date_created = models.DateTimeField(blank=True, null=True) last_updated = models.DateTimeField(blank=True, null=True) def __str__(self): return '{} {} {}'.format(self.uusername, self.full_name, self.uniqueId) def get_absolute_url(self): return reverse('profile-detail', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if self.date_created is None: self.date_created = timezone.localtime(timezone.now()) if self.uniqueId is None: self.uniqueId = str(uuid4()).split('-')[4] self.slug = slugify('{} {} {}'.format(self.uusername, self.full_name, self.uniqueId)) self.slug = slugify('{} {} {}'.format(self.uusername, self.full_name, self.uniqueId)) self.last_updated = timezone.localtime(timezone.now()) super(Profile, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('profile-detail', kwargs={'slug': self.slug}) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() Here is the error: return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "members_profile" does not exist LINE 1: ...e_created", "members_profile"."last_updated" FROM "members_p... I don't know how to solve this please help me! -
Pylance Intellisense not working as expected with Django
I'm trying to understand how to configure Pylance to make it work correctly in my Django project. Below is one of many examples where Pylance is not able to find what I'm looking for. Here, I obviously need models from django.db. But there are only theses 6 suggestions below... Here is what I know or tried: My interpreter is correctly selected (Python 3.10.4) Pylance seems to work perfectly with Python (not Django) related stuff. I'm using Poetry as a package manager, and no virtual env because I work in a self-contained dev container. There is only one python installed on it. In my VS Code config (using devcontainer.json) :"python.analysis.extraPaths": ["${workspaceFolder}/dj_proj/dj_apps"] -> which works to prevent missing imports. I have no false warnings about missing imports, just the inability to see the right suggestions in intellisense. I cleaned __pycache__ and .pyc files -> no effect I ensured there is a __init__.py pretty much everywhere my sys.path (PYTHONPATH) looks like this (where dj_proj is my django project and dj_apps my apps folder): ['/workspace/dj_proj/dj_apps', '/workspace/dj_proj', '/usr/local/lib/python310.zip', '/usr/local/lib/python3.10', '/usr/local/lib/python3.10/lib-dynload', '', '/usr/local/lib/python3.10/site-packages'] I'm suspecting this PYTHONPATH variable to be messy or not sorted the right way, but I'm not sure. Any idea on what … -
even after running migrations Django Programming error column does not exist
At first on my project everthing is works fine but after I added field to model everything is broken.I am working on ubuntu with postgresql.(Django project) .I deleted migrations folder and django_migrations folder but nothing is change.Everytime I get this error.Can anyone please help me?? -
sort meeting timeslot using priority base:python Django
im creating in the one to one meeeting website. and try to do for the sorting section sorting in the vendor need to meet == delligate => V sorting to the deligate need to meet == vendor => D deligate and vendor need to equally meet vendor == deligate && deligate == vendor =>M these conditions are need to done for python django section. im try to fix the section in the pandas but that is not happen. only coming in the 'NaN' values . -
the Django's mongodb support library djongo will close the db automatically
I use MongoDB as the Django's database and I use djongo for operation, it seems that it will close the connection automatically and can't restore. For example, I create a simple view to show all the records like before: book_res = Book.object.all() ... return Response(res) It will work in the first time I get to the view's url address, if i refresh the page or redirect into the same url, the system will crash and shows the error message that "cannot use mongoclient after close" that cause an ambigous error "django.db.utils.DatabseError" -
How to increase query execution time?
I get an error 504 gateway time-out when my user tries to get some data from the database, the query that is to be executed to fetch the data is very complex and takes some time to be executed, so I want to increase the query execution time in my server so user can get the data, so how can I do this from my putty the application is written in Django -
How to search on different models dynamically using Elasticsearch in Django?
Criteria: Front-End templates should be dynamic Scenario: Let's suppose there are three models(Product, Service, Merchant). If we search for the service model, all the services should be listed at the first template and other models like product and merchant can be recommend at second and third template simultaneously. All the section(templates) product, service and merchant should be made dynamic. So that whenever we search for particular model, it must be displayed at top and all other remaining models can be recommended later. Example: Let's suppose there are three models(Product, Service, Merchant). If we search "Bag" the system should return Product model at first template and then service and merchant in other templates respectively. If we search "Laptop Repair" the system should return Service model at first template and then product and merchant in other templates respectively. -
Need to add one model fields in the another model serializers but throwing error while POST the request
models.py class Product(models.Model): product_id = models.AutoField(unique=True, primary_key=True) product_name = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = "product_master" def __str__(self): return self.product_name class Organisation(models.Model): """ Organisation model """ org_id = models.AutoField(unique=True, primary_key=True) org_name = models.CharField(max_length=100) org_code = models.CharField(max_length=20) org_mail_id = models.EmailField(max_length=100) org_phone_number = models.CharField(max_length=20) org_address = models.JSONField(max_length=500, null=True) product = models.ManyToManyField(Product, related_name='products') org_logo = models.ImageField(upload_to='org_logo/') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = "organisation_master" def __str__(self): return self.org_name serializers.py class Product_Serializers(serializers.ModelSerializer): class Meta: model = Product fields = ('product_id', 'product_name',) class Organisation_Serializers(serializers.ModelSerializer): product = Product_Serializers(many=True) class Meta: model = Organisation fields = ('org_id', 'org_name', 'org_address', 'org_phone_number', 'org_mail_id','org_logo','org_code','product') depth = 1 " While i tried to do POST method for the organisation model I have tried giving the input for product as "product: 5" and "product: {"product_id": 5,"product_name": "time"} in the postman form data but it is showing as { "status": "error", "code": 400, "data": { "product": [ "This field is required." ] }, "message": "success" } I need to post like this product: {"product_id": 5,"product_name": "time"}, what fields are available in the product model it should be posted on this product field. Can you please suggest me a way as i tried many ways as … -
Django deploy errors
I just launched the Django app. As an image, everything is in place, but the form and admin panel do not work. Anyone who knows please help I get this error when I run the form. Let me know if I need to share any code. -
How to send post request to properly using Http Client in Angular
I want to create a registration page that holds email, username, first-name, last-name and password. I am using Angular 13 as front-end and Django as back-end. The forms works perfect but I am getting an error on the console. here is my registration form: here is the error on the console: here is the list of services I wrote: 1. code for auth.service.ts: import { Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { ResearcherData } from './../models/researcher-data.interface'; import { Observable, throwError } from 'rxjs'; import { catchError, retry } from 'rxjs/operators'; import { HandleError, HttpErrorHandler } from './http-error-handler.service'; import { HttpHeaders } from '@angular/common/http'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', Authorization: 'my-auth-token' }) }; @Injectable({ providedIn: 'root' }) export class AuthService { private url = 'http://127.0.0.1:2000/auth/users/'; private handleError: HandleError; constructor( private http: HttpClient, httpErrorHandler: HttpErrorHandler, ) { this.handleError = httpErrorHandler.createHandleError('AuthService'); } /** register researcher to the server */ register(researcherdata: ResearcherData): Observable<ResearcherData>{ return this.http.post<ResearcherData>(this.url, researcherdata,httpOptions) .pipe( catchError(this.handleError('register', researcherdata)) )} } code for http-error-handler.service.ts import { Injectable } from '@angular/core'; import { HttpErrorResponse } from '@angular/common/http'; import { Observable, of } from 'rxjs'; import { MessageService } from './message.service'; /** Type of the handleError …