Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why can't create superuser
how can I solve this problem in django[duplicate admin showing][1] "raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: admin" -
Ho to replace default error page in Django?
I have a Django app and in the main urls.py I have the handler500 = 'common.view_utils.custom_500' which is supposed to display my custom error page. The code of the custom_500 is as follows def custom_500(request): logger.error(sys.exc_info()) t = loader.get_template('500.html') type, value, tb = sys.exc_info() return HttpResponseServerError(t.render(request, { 'exception_value': value, 'value': type, 'traceback': traceback.format_exception(type, value, tb) })) However when I tried to test it and raised an Error from the view class then Django displayed the default A server error occurred. Please contact the administrator. error page. I thought if an Error is raised in the code then that is supposed to be a 500 error which will be handled but mu custom error handler but obviously I am mistaken. Could you please help me what I am missing here? Thanks, V. -
Decoupled authentication for multiple applications
I am researching authentication models that would allow me to: Have a single user account managed by the main application, where I can login using various methods (including OAuth): auth.main-app.com Have multiple sub-applications, each with its own unique domain, that use the main application for authenticating users. The sub-applications would have their own separate databases, for app-specific data, some of which would be correlated with the users found in the main-app.com. Notes Planning on using: Kong as an ingress Gateway. Django for all apps. Question Is there an existing authentication solution that could cover these requirements? -
Django Filter error select form invalid data
hi i have a problem with filtering a select field. I know the problem lies in the form but I don't understand what I need to change to make it work. Someone can give me the solution or can tell me how I can test a form with print because I don't understand how to be able to test it. form class EserciziForm(forms.ModelForm): class Meta: model = models.DatiEsercizi exclude = ['gruppo_single'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['dati_esercizio'].queryset = models.DatiEsercizi.objects.none() if 'gruppo' in self.data: try: gruppo_id = int(self.data.get('gruppo_single')) self.fields['dati_esercizio'].queryset = DatiEsercizi.objects.filter(gruppo_single = gruppo_id) except (ValueError, TypeError): pass views def caricamento_esercizi(request): gruppo_id = request.GET.get('gruppo') gruppo_name = DatiGruppi.objects.get(dati_gruppo = gruppo_id) esercizi_add = DatiEsercizi.objects.filter(gruppo_single = gruppo_name) context = {'esercizi_add': esercizi_add} return render(request, 'filtro_esercizi.html', context) file html $("#id_gruppo-dati_gruppo").change(function(){ var gruppoId = $(this).val(); var url = $("#creazione_scheda").attr("data-esercizi-url"); $.ajax({ url: url, data:{ 'gruppo': gruppoId }, success: function(data){ $(".esercizi select").html(data); } }); }); model class Gruppi(models.Model): nome_gruppo = models.CharField(max_length=100) def __str__(self): return self.nome_gruppo class Esercizi(models.Model): nome_esercizio = models.CharField(max_length=100) gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'gruppo' ) -
Create an instance of
My class is called Listing ValueError at /listing/3/ Cannot query "Clothes,Adidas,👏🏻 super quality!,50.00,http://www.pngall.com/wp-content/uploads/2016/06/Adidas-Shoes.png,Ninja ,2021-12-31 00:00:00+00:00": Must be "Listing" instance. Please explain in a simpler form I'm not sure I understand. Do I need to create an instance of the Listing class? -
Django Unit Test Assertion Error for Serialization
I am trying to perform the unit test for a feature in my website, whereby the user uploads a JSON file and I test if the JSON file is valid using serialization and JSON schema. When running the following test code I keep getting assertion error. serializer.py class Serializer(serializers.Serializer): file = serializers.FileField(required=True) format = serializers.CharField(required=True) def validate(self, data): is_valid, message = Validation().is_valid( json.loads(data.read())) if (not (is_valid)): raise serializers.ValidationError(message) tests.py class Validation(TestCase): def test_valid_serializer(self): file_mock = mock.MagicMock(spec=File) file_mock.name = 'mock.json' file_mock.content = { 'mockData': [{ "id": 1, "name": "blue", }] } serializer_class = Serializer(data=file_mock.content) assert serializer_class.is_valid() assert serializer_class.errors == {} -
Numbering cells in a grid using opencv python
I have created grids on an image with open cv, so I am trying to number the cells created from 1,2,3,4,5,... the image shows what the result of this code is. Anyone with an idea how to get all the cells numbered in python x = 0 y = 0 k = 0 while x < self.img.shape[1]: cv2.line(self.img, (x, 0), (x, self.img.shape[0]), color=(220,220,220), lineType=cv2.LINE_AA, thickness=1) while y < self.img.shape[0]: cv2.line(self.img, (0, y), (self.img.shape[1], y), color=(220,220,220), lineType=cv2.LINE_AA, thickness=1) y += 100 k += 1 cv2.putText(self.img, str(k), (x,y), font, 1, (0, 255, 255), 1, cv2.LINE_AA) x += 100 enter image description here -
Django refferal link registration
In my project I need to register User1, and then User2 using refferal link from User1. That link should contain access_code unique for each user, for example http://my_site/register?access_code=some_random_code. All users are registered through one view: class UserCreateAPIView(CreateAPIView): queryset = get_user_model().objects.all() serializer_class = UserSerializer User Model: class User(AbstractUser): pair = models.OneToOneField( "self", null=True, blank=True, on_delete=models.DO_NOTHING) access_code = models.UUIDField( default=uuid.uuid4, editable=False, unique=True) So I need: Check if there is an access_code in request body If access_code exists, then find User1 who sent this code Add User1's id to current user(User2) to the field pair Add User2(current) to User1 field pair so both users had references to each other through pair fields -
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
Unable to store multiple choices using MultiSelectField Package
I am using MultiSelectField for storing multiple choices in django rest framework. But i am unable to this. class CandidateJobDetail(models.Model): class JobType(models.TextChoices): PERMANENT = "Permanent" CONTRACT = "Contract" job_type = MultiSelectField( max_length=50, choices=JobType.choices, null=True, blank=True ) availability_date = models.DateField(null=True, blank=True) class CandidateJobDetailSerializer(serializers.ModelSerializer): job_type = CustomMultipleChoiceField(choices=CandidateJobDetail.JobType.choices) class Meta: model = CandidateJobDetail fields = "__all__" I am getting this error { "job_type": [ "\"['CONTRACT']\" is not a valid choice." ] } -
Reverse for '..' with arguments '('',)' not found. 1 pattern(s) tried: ['common/nut/(?P<pk>[0-9]+)/$']
Hej! I get the error message 'Reverse for 'nuts_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['common/nut/(?P[0-9]+)/$']' when I link my detail_nuts.html like that but I can get to the page via the url-bar so the view seems to be working correctly. And I can get the value of plant.nuts_level_3 when it is not in the link. <!-- detail_plant.html --> <p><b>Address: </b> <b>NUTS (level 3): </b> <a href="{% url 'common:nuts_detail' nuts.id %}"> {{plant.nuts_level_3}} </a> </p> # common/urls.py from django.urls import path import common.views app_name = "common" urlpatterns = [ path("nut/<int:pk>/", common.views.NutsDetail.as_view(), name="nuts_detail") ] # plants/models.py class Plant(models.Model): nuts_level_3 = models.ForeignKey( NutsLevel3, on_delete=models.PROTECT, blank=True, null=True, related_name="nuts_level_3" ) # common/models.py class NutsLevel3(models.Model): code = models.CharField(max_length=5, unique=True) nuts_level_2 = models.ForeignKey(NutsLevel2, on_delete=models.CASCADE) name_native = models.CharField(max_length=100, blank=True) def __str__(self): return f"{self.name_native}" I tried putting the link in {% for nuts in plant.nuts_level_3.all %} <a href="{% url 'common:nuts_detail' nuts.id %}"> {{nuts.name_native}} </a> {% endfor %} The error message dissappears then and the template is rendered but Nuts is not given at all it just remains as an empty field. Does anyone have an idea? Any help appreciated! :) -
Why index on json field not working? Django, large database
I have a model in django that has a json field that holds the nutritional values of a meal. from django.db import models class Meal(models.Model): name = models.CharField(max_length=200) portions_count = models.IntegerField() attributes = models.JSONField() I have a million meal records and would like to search based on attributes (gte, lte). Example atrributes field: {"cep": 21.71, "eng": 23.37, "fep": 40.91, "pep": 27.29} Example view: class MealView(View): def get(self, request, *args, **kwargs): meals = Meal.objects.filter(attributes__eng__gte=12, attributes__cep__gte=12)[:50] return render(request, 'meals.html', { 'meals': meals }) ...and more advanced queries (attributes, portions count and name together). Queries can take a few seconds and if the database is overloaded, it takes longer. We tried: GinIndex(fields=['attributes']), or Index(fields=['attributes']) But indexes was not used. (checked in postgres via sql query, pg_stat_all_indexes table and explain select) I know that it would definitely be better if the attributes were not in JSON. Ultimately we will try to change it, but at the moment we are looking for a JSON solution. -
Populating a table in Django by clicking on the cell
I have the code below that generates a table. I can add names to the table with a form to select the hour (corresponding to rows) and the position (corresponding to columns), as you can see on the 3 following screenshots: First screenshot Second screenshot Third screeshot Instead of selecting the hour and the position with the form, I would like to add the name to the table by directly clicking on a table cell. Do you have any idea on how to proceed ? Thanks ! Here is my code : views.py : def schedule(response, id): try: t = Table.objects.get(id=int(hashids.decode(id)[0])) except: t = None if response.method == "POST": if response.POST.get("add"): form = Activities(response.POST) if form.is_valid(): name = form.cleaned_data["name"] pos = form.cleaned_data["pos"] time = form.cleaned_data["time"] t.activity_set.create(text=name, pos=pos, time=time) elif response.POST.get("delete"): t.activity_set.filter(id=response.POST.get("id")).delete() """to clear the post we redirect to the same page """ return HttpResponseRedirect("/%s" %hashids.encode(t.id)) if t is not None: return render(response, "main/create.html", {'rangeHour':range(24), 'rangeMinute':range(0,60,30), 'rangePos':['CDT', 'CS', 'SQR', 'COO', 'INI', 'ITM', 'DEP', 'ASS DEP', 'LOC', 'ASS LOC', 'SOL', 'ASS SOL', 'PVL', 'RMQ'], 'table':t, 'table_day':t.day.strftime("%d-%m-%Y"), 'TIME_VALUES':TIME_VALUES, 'POS_J1_6H':POS_J1_6H, 'POS_J1_10H':POS_J1_10H, 'POS_J1_15H':POS_J1_15H, 'POS_ALL':POS_ALL}) else: return render(response, "main/create.html", {'rangeHour':range(24), 'rangeMinute':range(0,60,30), 'rangePos':['CDT', 'CS', 'SQR', 'COO', 'INI', 'ITM', 'DEP', 'ASS DEP', 'LOC', 'ASS LOC', 'SOL', 'ASS SOL', … -
django as standalone desktop application - windows
I am using django for building a site which as to be converted as standalone windows exe application and should run as a service whenever the system boots up. I have tried pyinstaller but again I have to open browser for the same. Is there a way to wrap django to electron ? -
SQLITE database error "sqlite3.OperationalError: no such table: table"
I am confused... I have a file "calculation.py" which contains which contains following code: conn = sqlite3.connect('matchprediction.db') c = conn.cursor() c.execute("SELECT * FROM spielplan WHERE table = 8") In addition I run that file via the local host in django to simulate a webserver. Whenever I start the server with python manage.py runserver, I get the error message: sqlite3.OperationalError: no such table: table The database definitely exists and the table itself, too. Have checked it with a DB Browser. The calculations.py works, because it retrieves data from this table to execute the calculation. The output result in the run-window is correct. What am I doing wrong and how may I fix this? -
How to properly pass context from views.py to an HTML template's and call it in pivottable.js function
In views.py I have this code: data2=[{'shape': 'circle', 'color': 'red'}, {'shape': 'circle', 'color': 'blue'}] return render(request, 'pivot.html', {'dataset': data2}) in HTML template I have this code: {% load static %} <script src="https://cdn.plot.ly/plotly-basic-latest.min.js"></script> <script src={% static 'js/jquery-3.6.0.min.js' %}></script> <script src={% static 'js/jqueryui/jquery-ui.min.js' %}></script> <script src={% static 'pivot/dist/pivot.min.js' %}></script> <script type="text/javascript" src={% static 'pivot/dist/pivot.js' %}></script> <link rel="stylesheet" type="text/css" href="{% static 'pivot/dist/pivot.css' %}"> <script type="text/javascript" src={% static 'pivot/dist/pivot.js' %}></script> <script type="text/javascript" src={% static 'pivot/dist/export_renderers.js' %}></script> <script type="text/javascript" src={% static 'pivot/dist/d3_renderers.js' %}></script> <script type="text/javascript" src={% static 'pivot/dist/c3_renderers.js' %}></script> <script type="text/javascript" src={% static 'pivot/dist/plotly_renderers.js' %}></script> <script type="text/javascript"> $(function() { $("#output").pivotUI( {{dataset}} , { renderers: $.extend( $.pivotUtilities.renderers, $.pivotUtilities.plotly_renderers, $.pivotUtilities.export_renderers )} ); }); </script> <div id="output" style="margin: 10px;"> </div> The pivot table does not show at all using the above code. But, if I replace {{dataset}} in the function with [{'shape': 'circle', 'color': 'red'}, {'shape': 'circle', 'color': 'blue'}] , the pivot table shows properly. What am I doing wrong? -
DJango mail working in local but not in production
Below is my code which sends a mail to my users: mail = EmailMultiAlternatives(subject=subject, body=text_content, from_email="email@host.com", to=["email@host.com"], bcc=["email@host.com"]) mail.attach_file(model.document.path) mail.attach_alternative(html_content, "text/html") mail_status = mail.send() And my settings.py is as below: EMAIL_HOST = "mail.host.com" EMAIL_PORT = 587 EMAIL_HOST_USER = "email@host.com" EMAIL_HOST_PASSWORD = str(os.getenv('EMAIL_HOST_PASSWORD')) The problem is that the above code works absolutely fine in my local Windows machine but the code hangs and shows no output when running in my remote server running Ubuntu (Linux). Any idea where I am going wrong? -
botocore ClientError white using collectstatic in django application
I am using AWS S3 bucket form my projects to serve staticfiles and mediafiles. I have used S3 bucket for my previous django projects, it works fine. But for my current project, it raises the following error while using python manage.py collectstatic command. botocore.exceptions.ClientError: An error occurred (403) when calling the HeadObject operation: Forbidden I have used correct S3 setting and also made my S3 bucket public. But don't know why this error occurs. please help me to solve this problem. Thanks in advance. My code if config("USE_S3", cast=bool) == True: # aws settings AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_S3_REGION_NAME = 'us-east-1' AWS_DEFAULT_ACL = None AWS_S3_FILE_OVERWRITE = False AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400' } # s3 static settings STATIC_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{STATIC_LOCATION}/' STATICFILES_STORAGE= 'storages.backends.s3boto3.S3Boto3Storage' else: MEDIA_URL = '/mediafiles/' MEDIA_ROOT = os.path.join(BASE_DIR, "mediafiles") STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] My bucket policy { "Version": "2012-10-17", "Statement": [ { "Sid": "PublicRead", "Effect": "Allow", "Principal": "*", "Action": [ "s3:GetObject", "s3:GetObjectVersion" ], "Resource": "arn:aws:s3:::my-bucket-name/*" } ] } My bucket cors setting, [ { "AllowedHeaders": [ "Authorization", "Content-Range", "Accept", "Content-Type", "Origin", "Range" ], "AllowedMethods": [ "GET" ], "AllowedOrigins": [ … -
ValueError: Field 'id' expected a number but got 'demo@gmail.com'
I am trying to create a User model so users can register through an email address instead of a username. I am getting ValueError: Field 'id' expected a number but got 'demo@gmail.com'. when I try to create superuser their was no issue in makemigrations and migrate also try to delete pycache and all the old migrations and db file but still same. colsole output is also at the end here are Models User model class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_("email address"), unique=True) first_name = models.CharField(_("first name"), max_length=10, blank=True) last_name = models.CharField(_("last name"), max_length=10, blank=True) date_joined = models.DateTimeField(_("date joined"), auto_now_add=True) is_active = models.BooleanField(_("is active"), default=True) # User Manager here objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: verbose_name = _('user') verbose_name_plural = _('users') def get_full_name(self): full_name = self.first_name + " " + self.last_name return full_name.strip() User Manager class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self,email,password, **extra_fields): """ Create and save user """ if not email: raise ValueError("Email is not available") email = self.normalize_email(email) user = self.model(email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self,email, password=None, **extra_fields): """ Create a user """ extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self,email, password, **extra_fields): """ Create super user """ extra_fields.setdefault('is_superuser', True) if extra_fields.get("is_superuser") … -
'utf-8' codec can't decode byte 0xab in position 1183: invalid start byte
enter code Traceback (most recent call last): File "C:\Users\lenovo\Envs\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\lenovo\Envs\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\lenovo\Envs\venv\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\lenovo\Envs\venv\lib\site-packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "D:\readcsv\readapp\views.py", line 61, in get return render(request, 'index.html',{'html_table':js}) File "C:\Users\lenovo\Envs\venv\lib\site-packages\django\template\loaders\filesystem.py", line 24, in get_contents return fp.read() File "c:\users\lenovo\appdata\local\programs\python\python39\lib\codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xab in position 1183: invalid start byte -
how to filter data from database if its saved in different formats in django
let us consider, here my data can be saved in database in two formats. My database looks like id soil_type 1 Acid;Clay;Damp;Loam;Well drained 2 Acid;Clay;Damp;Loam;Neutral;Well drained 3 [u'Clay', u'Damp'] 4 [u'Acidic', u'Alkaline'] 5 [u'Clay'] here is models.py class Items(models.Model): SOIL_TYPE_CHOICES = ( ('Acidic','Acidic'), ('Alkaline','Alkaline'), ('Chalk','Chalk'), ('Clay','Clay'), ('Damp','Damp'), ('Dry','Dry'), ('Loam','Loam'), ('Neutral','Neutral'), ('Sandy','Sandy'), ('Waterlogged','Waterlogged'), ('Well-drained','Well-drained'), ) soil_type = models.CharField(max_length=500, blank=True, null=True) currently how i am filtering in my views.py is soil_type = request.GET.get('soil_type', '') [# print("soil type",soil_type) - ('soil type', u'Clay') ] items = Items.objects.filter(soil_type__icontains = soil_type) Here id = 1,2 are saved when uploading data through csv file And id = 3,4,5 are saved manually(like manually adding item or creating the item) now what i need is if filter we choose clay then i need to get records of id = 1,2,3,5 as clay is present in each of these -
How to auto increment a data whenever click on a button in Django?
I'm working a Django project where i have two models here's my models: class APIDetails(models.Model): test_case_ID = models.CharField(primary_key = True,max_length=500) description= models.CharField(max_length=500, blank=True) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True, blank=True, null=True) class APIParameter(models.Model): parameterName = models.CharField(max_length=100, blank=True) parameterValue = models.CharField(max_length=100, blank=True) TC_ID= models.ForeignKey(APIDetails, on_delete=models.CASCADE, related_name='param', blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True, blank=True, null=True) here's the sreenshot of table I have a HTML form: <div class="panel panel-info atf-form"> <div class="panel-heading text-center" style="background-color: #660099;"> <h1 class="panel-title" style="color: white;">TAF Integration URL</h1> </div> <form action="{% url 'ATFDashboard' %}" method="post" style="margin-top: 10px;"> {% csrf_token %} {% for param in Param %} <div class="form-row "> <div class="form-group col-md-2 "> <label for="param ">TAF Parameter</label> <input type="text " name="{{param.id}} " class="form-control " id="inputapi_param " value="{{param.parameterName}} " readonly> </div> {% if param.parameterName == 'api' or param.parameterName == 'callback' %} <div class="form-group col-md-4 "> <label for="val ">TAF Value</label> <input type="text " name="{{param.id}} " class="form-control " id="inputapi_val " value="{{param.parameterValue}} " readonly> </div> {%else%} <div class="form-group col-md-4 "> <label for="val ">TAF Value</label> <input type="text " name="{{param.id}} " class="form-control " id="inputapi_val " value="{{param.parameterValue}} " required> </div> {% endif %} </div> {% endfor %} <div class="form-row "> <div class="form-group col-md-12 "> <button type="submit " class="btn btn-primary taf-btn "><b>Generate … -
How to change `DIRS` path dynamically in Django?
I want to change DIRS dynamically.based on devices. if request.user_agent.is_pc: request.template_prefix = 'desktop' else: request.template_prefix = 'mobile' Default (settings.py): TEMPLATES = [ { 'DIRS': ['templates'], }, ] I want to change my DIRS path like this (settings.py): TEMPLATES = [ { 'DIRS': [f"templates/{request.template_prefix}"], }, ] Also let me know if you need more codes. Note: I can't use user_agent in settings.py Because it requires a request. that's why I asked. My django version is: 3.2.x In simple words: How to change DIRS path in views.py. Thanks! -
how to create access to ssh terminal for my website users from their own web panel
how to create access to ssh terminal for my website users from their own web panel. I have created a user on the server for each individual user. But I don't want them using a putty or something else. just use only a small terminal inside their panel. The website backend is django. -
React to django CORS issue
Error Details What did I search so far? Axios blocked by CORS policy with Django REST Framework CORS issue with react and django-rest-framework but to no avail What am I doing? Submitting POST request from react to DJango API Django side settings file CORS_ORIGIN_ALLOW_ALL = True ALLOWED_HOSTS = ["http://127.0.0.1:3000"] CORS_ORIGIN_WHITELIST = [ 'http://127.0.0.1:3000' ] INSTALLED_APPS = [ ......, "corsheaders" ] MIDDLEWARE = [ ........., 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] React axios request function authenticate() { let body = { "email": "ac", "password": "def" }; const headers = { 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json', } axios.post("http://127.0.0.1:8000/login/", body, { headers: headers }) .then(function(response) { console.log(response.data); }) .catch(function(error) { console.log(error); }); }