Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
passing 2D array from JavaScript template to Django web framework
I have a 2D array of values in JavaScript. How do I pass it to the Django framework to perform the operations without saving into the database? -
Django Database Connection
I am simply using Django for endpoints and don't want to use the Django functionality of connecting to databases. Instead, I want to connect to Postgresql and Redis database by creating it at time of starting server. One of the ways I did it was created these connection object in the django app init file and it works. But I don't thinks its the right way as I am not able to close the connection and also each time the server starts a new connection is created. Please help me out with the most efficient way of doing this task. I just need to create the connection to both Redis and postgresql by normal sqlalchemy command while starting server and then disconnect theses connections as soon as teh server stops or crashes. Something like finally block. -
schedule_task() argument after * must be an iterable, not int
Here I am using apply_async method with countdown and expires arguments to execute the task after some countdown and expires the task at certain datetime. But I got this error Django Version: 3.0.6 Exception Type: TypeError Exception Value: schedule_task() argument after * must be an iterable, not int How to solve this error ? tasks @periodic_task(run_every=crontab(minute=1), ignore_result=False) def schedule_task(pk): task = Task.objects.get(pk=pk) unique_id = str(uuid4()) views form = CreateTaskForm(request.POST) if form.is_valid(): unique_id = str(uuid4()) obj = form.save(commit=False) obj.created_by = request.user obj.unique_id = unique_id obj.status = 0 obj.save() form.save_m2m() # schedule_task.delay(obj.pk) schedule_task.apply_async((obj.pk),expires=datetime.datetime.now() + datetime.timedelta(minutes=5), countdown=int(obj.search_frequency)) return redirect('crawler:task-list') -
Reverse for 'openapi-schema' not found. 'openapi-schema' is not a valid view function or pattern name
I am trying to document my Django REST API with built-in methods. Here is the urls.py : from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url from django.views.generic.base import TemplateView from rest_framework.documentation import include_docs_urls urlpatterns = [ path('api/', include('api.urls')), path('admin/', admin.site.urls), path('', include('main.urls')), path('swagger-ui/', TemplateView.as_view( template_name='swagger-ui.html', extra_context={'schema_url': 'openapi-schema'} ), name='swagger-ui'), url(r'^.*', TemplateView.as_view(template_name="home.html")), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) static/templates/swagger-ui.html : <html> <head> <title>Swagger</title> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="//unpkg.com/swagger-ui-dist@3/swagger-ui.css" /> </head> <body> <div id="swagger-ui"></div> <script src="//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script> <script> const ui = SwaggerUIBundle({ url: "{% url schema_url %}", dom_id: '#swagger-ui', presets: [ SwaggerUIBundle.presets.apis, SwaggerUIBundle.SwaggerUIStandalonePreset ], layout: "BaseLayout" }) </script> </body> </html> However I don't understand where should we allocate openapi-schema file? Is it .yml file or .js? And is there a way to generate it authomatically? -
Django - error message: IndentationError: unindent does not match any outer indentation level
enter image description here I'm having trouble solving this portion of my code. This is the model.py inside my app. The "image = models.ImageField(null=True, blank=True)" keeps giving me an error. I install Pillow library but didn't solve the problem from django.db import models from django.contrib.auth.models import User # Create your models here. class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() digital = models.BooleanField(default=False,null=True, blank=False) image = models.ImageField(null=True, blank=True) def __str__(self): return self.name class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True, blank=False) def __str__(self): return str(self.id) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, blank=True, null=True) date_added = models.DateTimeField(auto_now_add=True) class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) address = models.CharField(max_length=200, null=True) city = models.CharField(max_length=200, null=True) state = models.CharField(max_length=200, null=True) zipcode = models.CharField(max_length=200, null=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.address -
How to pass selected row as DB table row value by clicking on button in Django page
function:- def reportposts(request): print("Hello i am from reportposts") query=request.GET.get('q') submitbutton= request.GET.get('submit') CountryID = request.GET.get('Country') print(query) print(submitbutton) print(CountryID) if request.method == 'GET': query=request.GET.get('q') submitbutton= request.GET.get('submit') CountryID = request.GET.get('Country') if query is not None: lookups= Q(id__icontains=query) | Q(name__icontains=query) results= Company.objects.filter(lookups).distinct() data = scraper(object_id=query, object_type='index', Country_ID=CountryID) context={'results': results,'models': json.dumps(data), 'submitbutton': submitbutton} return render(request, 'post/report.html') else: return render(request, 'post/report.html') Above code here is code that not able to receive anything from Django page. -
How to add the LIKE feature in a Django Blog?
enter image description hereI am adding a LIKE feature in my Twitter Clone builded with Django. I added this feature successfully but when I click on a like button only the recent post get liked. I created a model for post and one for likes and dislikes called Preference. Only the first post get liked when i click in the like buttons of other posts. How can i fix this? Below i have pasted the code of models, views and template. models.py class Post(models.Model): content = models.TextField(max_length=1000) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) likes= models.IntegerField(default=0) dislikes= models.IntegerField(default=0) def __str__(self): return self.content[:5] @property def number_of_comments(self): return Comment.objects.filter(post_connected=self).count() class Preference(models.Model): user= models.ForeignKey(User, on_delete=models.CASCADE) post= models.ForeignKey(Post, on_delete=models.CASCADE) value= models.IntegerField() date= models.DateTimeField(auto_now= True) def __str__(self): return str(self.user) + ':' + str(self.post) +':' + str(self.value) class Meta: unique_together = ("user", "post", "value") views.py @login_required def postpreference(request, postid, userpreference): if request.method == "POST": eachpost= get_object_or_404(Post, id=postid) obj='' valueobj='' try: obj= Preference.objects.get(user= request.user, post= eachpost) valueobj= obj.value valueobj= int(valueobj) userpreference= int(userpreference) if valueobj != userpreference: obj.delete() upref= Preference() upref.user= request.user upref.post= eachpost upref.value= userpreference if userpreference == 1 and valueobj != 1: eachpost.likes += 1 eachpost.dislikes -=1 elif userpreference == 2 and valueobj != 2: eachpost.dislikes … -
python/Django - Need to display filename first and contents of searched string in below for multiple file
views.py def sindex(request): search_path = "C:/AUTOMATE/STRING/TESTFILE/" file_type = ".txt" Sstringform = stringform() Scontext = {'Sstringform' : Sstringform} if request.method == 'POST': SVRFTEXT = Scontext['Enter_VRF_Name_To_Search'] = request.POST['Enter_VRF_Name_To_Search'] ftext = [] Scontext['resultlist'] = ftext for fname in os.listdir(path=search_path): fo = open(search_path + fname) fread = fo.readline() line_no = 1 while fread != '': fread = fo.readline() if SVRFTEXT in fread: ftext.append(fname + fread) line_no +=1 fo.close() return render(request, 'demoapp/VRFFILELIST.html', Scontext) VRFFILELIST.HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>VRF FILE LIST</title> </head> <body> <form method="POST"> {% csrf_token %} <table> {{Sstringform.as_table}} </table> <button type="submit">Send Command</button> </form> <table> <h3>VRF IN LIST OF FILES</h3> <textarea rows="25" cols="120" name="conf" form="conf" id="conf">{% for result in resultlist%}{{result}}{% endfor %}</textarea> </table> </body> </body> </html> managed to get output as below TEST-FILE-A.txt ip vrf forwarding TEST:VRFA TEST-FILE-A.txt ip vrf forwarding TEST:VRFA TEST-FILE-A.txt address-family ipv4 vrf TEST:VRFA TEST-FILE-A.txt neighbor 192.168.252.241 route-map TEST:VRFA-IN in TEST-FILE-A.txt neighbor 192.168.252.241 route-map TEST:VRFA-OUT out TEST-FILE-C.txt ip vrf forwarding TEST:VRFA TEST-FILE-C.txt neighbor 192.168.10.2 route-map TEST:VRFA-IN in TEST-FILE-C.txt neighbor 192.168.10.2 route-map TEST:VRFA-OUT out Required output as below TEST-FILE-A.txt ip vrf forwarding TEST:VRFA ip vrf forwarding TEST:VRFA address-family ipv4 vrf TEST:VRFA neighbor 192.168.252.241 route-map TEST:VRFA-IN in neighbor 192.168.252.241 route-map TEST:VRFA-OUT out TEST-FILE-C.txt ip vrf forwarding TEST:VRFA neighbor 192.168.10.2 route-map … -
Reverse for 'article-create' not found. 'article-create' is not a valid view function or pattern name
I started getting this error all of the sudden. I don't have any thing related to article-create in my urls.py or models.py or views.py After adding the below code: slug = models.SlugField(blank=True, default=False) and the below related i encountered this error. def get_add_to_cart_url(self): return reverse("add-to-cart", kwargs={ 'slug': self.slug }) def get_remove_from_cart_url(self): return reverse("remove-from-cart", kwargs={ 'slug': self.slug }) urls.py shop/urls.py models.py -
How to fix the problem 'No module named myModule'
when start the service,as the command 'gunicorn -w 4 -b 0.0.0.0:8000 ApiWangYinParse:server', it shows the error log. plz look the code structure, what command I can start the python service. [2020-06-09 17:24:20 +0800] [28785] [INFO] Starting gunicorn 20.0.4 [2020-06-09 17:24:20 +0800] [28785] [INFO] Listening at: http://0.0.0.0:8000 (28785) [2020-06-09 17:24:20 +0800] [28785] [INFO] Using worker: sync [2020-06-09 17:24:20 +0800] [28788] [INFO] Booting worker with pid: 28788 [2020-06-09 17:24:20 +0800] [28789] [INFO] Booting worker with pid: 28789 [2020-06-09 17:24:20 +0800] [28788] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 119, in init_process self.load_wsgi() File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/local/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 49, in load return self.load_wsgiapp() File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 358, in import_app mod = importlib.import_module(module) File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/signdraft2/ShenDuTool/API/ApiWangYinParse.py", … -
Writing in /tmp in Azure app service linux with django
We have an Azure linux app service running django. When we upload a file to it that is greater than 2.5MB it written by default in the /tmp. When this happens we notice increase in response time from the app service before it eventually crash. Is there a restriction on writing in the /tmp for a linux web app ? If so where can we write our temporary file ? How could I make sure that the /tmp is in fact the issue ? We don't want to increase FILE_UPLOAD_MAX_MEMORY_SIZE value of django. We looked at this documentation but it doesn't talk of any issue on the tmp for linux. -
How to identify number of connections to a Postgres Database (heroku)?
I am trying to identify the number of connections to a postgres database. This is in context of the connection limit on heroku-postgres for dev and hobby plans, which is limited to 20. I have a python django application using the database. I want to understand what constitute a connection. Will each instance of an user using the application count as one connection ? Or The connection from the application to the database is counted as one. To figure this out I tried the following. Opened multiple instances of the application from different clients (3 separate machines). Connected to the database using an online Adminer tool(https://adminer.cs50.net/) Connected to the database using pgAdmin installed in my local system. Created and ran dataclips (query reports) on the database from heroku. Ran the following query from adminer and pgadmin to observe the number of records: select * from pg_stat_activity where datname ='db_name'; Initial it seemed there was a new record for each for the instance of the application I opened and 1 record for the adminer instance. After some time the query from adminer was showing 6 records (2 connections for adminer, 2 for the pgadmin and 2 for the web-app). Unfortunately I … -
Django: Custom Model Manager does not pass updated id values
my data in policy model is as follows : | id |policy_start_date| amount | is_renewed | original_policy |renewed_counter| | 10 | 01-06-2019 | 134 | 0 | NULL | 0 | | 12 | 05-06-2019 | 454 | 0 | NULL | 0 | | 35 | 04-06-2020 | 121 | 1 | 12 | 1 | I'm trying to use a custom model in models.py to change the id if is_renewed flag is set to True. With the help of print statements, I can see that my desired output is being printed when the custom model manager gets fired but the required output is not passed down to the final queryset i'm getting. my model manager and model class CustomManager(models.Manager): def get_queryset(self): temp = super(CustomManager, self).get_queryset().all() for a in temp: if a.is_renewal: a.id = str("R" + str(a.original_policy)) print(a.id) return temp class Policy(models.Model): objects = CustomManager() policy_start_date = models.DateField() amount = models.IntegerField() is_renewed = models.BooleanField(default = False) original_policy = models.IntegerField(Null = False) renewed_counter = models.IntegerField(default = 0) in shell, if i do test = Policy.objects.all() i get print output R12 but the same is not available in test. -
Django Modelling for staggered database config
I have a query; I would be using a explicitly defined primary key field in my user table, what I want is to attach a number like '111'+ i as the primary key where i is auto incremented... but if the server stops by some chance, I would have to reload i, so I would have to save the value of i in database after each run also i would be reading i each time from database Concerns: What if before i is saved server crashes, so the value of I would be corrupted If I has been read once, can I be able to not read it at each run My use case is : I have one US server which is seperated by UK server, but I want to have a global server too where US and UK users are both present Purpose: I am building an app where you can share and view ideas, at first you can only share n view ideas in your country, after reaching a certain level, you can share and view ideas of alll the countries... So I thought, I would have 1 db associated with each country. Say DB-UK for ideas … -
REST API listener vs polling
I have a mobile application which is calling my Django REST API for data, one of the calls looks at open orders. At the moment I refresh the list every x seconds on the mobile app. This isn't a great user experience and I'd like it to be more instant/less intrusive than a full reload. Is it possible to create something like a listener or open connection to a REST API endpoint? Would this be resource intensive if there are a lot of mobile clients? Many thanks! -
Django: Authentication system errors and bugs. (value too long for type character varying(80))
I'm trying to code the login/register system on Django, but I'm getting errors. So my main task is to make a custom auth system that the user can easily login/logout/register. I don't want to use the in-built User model, I want to use my main from flask. So the thing is that I'm trying to move from flask to Django and set-up the models and stuff. So I have this models.py file which concludes: import datetime import uuid from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.db import models from werkzeug.security import generate_password_hash, check_password_hash class UserManager(BaseUserManager): def create_user(self, username, password, primary_telephone_number, secondary_telephone_number, primary_email_address, first_name, last_name, registration_ip): if not username or not password or not primary_telephone_number or not secondary_telephone_number or not primary_email_address or not first_name or not last_name or not registration_ip: raise ValueError('Not enough values') user_obj = self.model(username=username, password=generate_password_hash(password), primary_telephone_number=primary_telephone_number, secondary_telephone_number=secondary_telephone_number, primary_email_address=primary_email_address, first_name=first_name, last_name=last_name, registration_ip=last_name) user_obj.save(using=self._db) return user_obj class Users(AbstractBaseUser): """Model for Winteka.IOT Users.""" public_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, blank=False, null=False, max_length=36) username = models.CharField(max_length=50, unique=True, blank=False, null=False) password = models.CharField(max_length=80, blank=False, null=False) # Third-party social (Emails, Phone numbers, Verifications) primary_telephone_number = models.CharField(max_length=15, unique=False, null=True, blank=False) secondary_telephone_number = models.CharField(max_length=15, unique=False, null=True, blank=True) primary_telephone_number_verified = models.BooleanField(default=False, null=False, blank=False) #Default secondary_telephone_number_verified = models.BooleanField(default=False, null=False, blank=False) … -
What web framework to use to implement deep learning-based image processing website?
I am currently working on developing an interactive image segmentation tool using deep learning. I developed a desktop application based on PyQt5 for the tool and tensorflow 2 for image processing. Now, I am intending to build a website so that the user can do the same task on web. However, I do not have experience on web programming and I want to build a quick prototype of my tool on web. Can you recommend web framework to do the job? I used PyQt5 for my desktop application, because I found Python relatively easy to study and PyQt5 is based on Python. So I searched for Python-based web framework and thought of using either Django or Flask. I do not mind using other frameworks based on different languages. This is the outline of the process. User upload image of size around 10k x 10k pixels. Zoom-in and zoom-out to examine the image Brush function so that user can annotate seed points Deep learning model to run on background to process segmentation -
Django: I am new to Django framework I want to submit three related model Forms with one submit button and render detail view
I want to admit(register) a new student with father and mother information in one form. I am able to save the father and mother form but not the student form it returns "NONE" but when i print the request.POST value I can see all the information. And I want to render a student detail with the father and mother information also but only the student information is displayed with out the father and mother info Model.p from django.db import models from django.db.models import PROTECT from django.urls import reverse # Create your models here. # Student Model class Father(models.Model): first_name = models.CharField(max_length=255) middle_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) father_pic = models.CharField(max_length=255) ASC = models.IntegerField() zoba = models.CharField(max_length=255) sub_zoba = models.CharField(max_length=255) religion = models.CharField(max_length=255) phone_no = models.IntegerField() parent_occupation = models.CharField(max_length=255) is_guardian = models.BooleanField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.id = self.id def __str__(self): return self.first_name def get_absolute_url(self): return reverse('student-detail', args=[str(self.id)]) class Mother(models.Model): first_name = models.CharField(max_length=255) middle_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) mother_pic = models.CharField(max_length=255) ASC = models.IntegerField(default='00000') zoba = models.CharField(max_length=255) sub_zoba = models.CharField(max_length=255) religion = models.CharField(max_length=255) phone_no = models.IntegerField() occupation = models.CharField(max_length=255) is_guardian = models.BooleanField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.id = self.id def __str__(self): return self.first_name def get_absolute_url(self): return … -
How to get list of functions or methods where data is coming through requests in Django?
I want to get the list of methods or functions where request.POST or similar is implemented. I don't want to look through the IDE search and then manually list down all methods/functions name. I'm using Python 3.8, Django 2.2.10 and pycharm professional. Thanks -
Django App Implementing Auth0 won't render on iOS devices after logging in
I have a nice Django app that implements Auth0. It works on all browsers on pcs and on browsers on Android. When testing on iOS devices however, after the user logs in through Auth0, the device asks to download a file and then downloads it and does nothing. If I try to redirect to my english page, it downloads a file called "en", if I try to redirect to my french version of the page, it downloads a file called "fr". Not sure why - it is at the end of the url myurl.something.org/myForm/en for English for example. At first I thought the issue had to do with Apple not allowing Same-Site cookies, so I added the CSRF_COOKIE_SAMESITE = None setting. But I see now that after logging in, in the address bar there is the url that I want the user to be redirected to. When I tried using the Web Inspector for Safari on Iphone, I see that there are no same-site cookies, so it seems that this is not the problem. I see the document "en" in the list of resources on the Web Inspector when on the login page. It is type "document" and shows that … -
How to create Peer Groups in Django?
How can I create a Peer Group in Django? I have tried the following: class Person(models.Model): name = models.CharField(max_length=100, unique=True) peers = models.ManyToManyField("self", blank=True, null=True) Now there are for example 3 Persons (A, B, C). A is connected to B. B is connected to C. A is not connected to C. The problem: A should also be connected to C, because B and C are connected. How can i do this? -
How to use Python selenium in cPanel?
Can somebody tell me "How can I use Python selenium in my cPanel or backend?" I want this for my web app developed in Django: Adsense Eligibility Checker Tool -
How is it possible for QuerySet.count() to return non-zero values but for list(QuerySet.all()) to yield an empty list?
I am running a script using django-extensions and here is the paused execution of it. How is this possible? I am running Django 2.2.1 on Windows with a local postgres instance. The database itself was restored using psql from a dump created with pg_dump | gzip. There is another database, which was restored using pgAdmin from a custom format file, on which the code works fine, so I guess I messed up the restoration, but how? -
Django - How to append to a Django queryset (values)
how do I append a dictionary into a Django queryset? I did .values on the queryset already, but it still classifies as a queryset and when I try to use .append on it, this error came up AttributeError: 'QuerySet' object has no attribute 'append' Here is my code: (start and end are variables passed in to denote the start month and end month of the selected range) qs = CustomerInformation.objects.filter(salesDepartment__in=[d]).filter(created_date__range=(start,end)) qs = qs.annotate(date=TruncMonth('created_date')).values('date').annotate(lead_count=Count('status',filter=Q(status="lead"))).annotate(client_count=Count('status',filter=Q(status="client"))) qs = qs.values('date', 'client_count', 'lead_count') All I want to do is to add the missing dates to the queryset, like for example if my queryset has date: April 2020 and June 2020, but is missing May 2020 due to CustomerInformation not having any instances with created_date in range of May 2020, hence I want to be able to insert a dictionary with date: May 2020 and lead_count and client_count 0 so that my data visualisation would work properly Thanks all, all help is appreciated! -
How to show error message when login fails in angular 8
i want to show error when user entered his login details if it is match with database then it login if not valid details then want to show credential are not a valid like... this is my login component.ts import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { FormGroup, FormBuilder, Validators} from '@angular/forms'; import { emailValidator } from '../../theme/utils/app-validators'; import { AppSettings } from '../../app.settings'; import { Settings } from '../../app.settings.model'; import { LoginService } from '../../services/login.service'; @Component({ selector: 'app-login', templateUrl: './login.component.html', providers: [LoginService] }) export class LoginComponent { public form:FormGroup; public settings: Settings; constructor(public appSettings:AppSettings, public fb: FormBuilder, public router:Router, private userService:LoginService){ this.settings = this.appSettings.settings; this.form = this.fb.group({ 'username': [null, Validators.compose([Validators.required, Validators.minLength(3)])], 'password': [null, Validators.compose([Validators.required, Validators.minLength(6)])] }); } public onSubmit(values:Object):void { this.userService.loginUser(this.form.value).subscribe( response => { console.log(response) this.router.navigate(['/client/clientdetails']) alert('User' + this.form.value.username + 'Logged') }, error => console.log('error', console.error) ); } ngAfterViewInit(){ this.settings.loadingSpinner = false; } } this is my login component.html page <mat-sidenav-container> <div fxLayout="row" fxLayoutAlign="center center" class="h-100" style="background-color: rgb(195, 38, 46)"> <form [formGroup]="form" (ngSubmit)="onSubmit(form.value)" fxFlex="80" fxFlex.gt-sm="30" fxFlex.sm="60"> <mat-card class="p-0 mat-elevation-z24 box"> <div fxLayout="column" fxLayoutAlign="center center" class="bg-primary box-header" style="background-color: #231F20;"> <!-- (click)="onSubmit(form.value);" --> <!-- <button mat-fab color="accent" class="mat-elevation-z12"> <mat-icon>exit_to_app</mat-icon> </button> --> <img src="assets/img/Ops_logo.png" style="float:right; …