Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
About GROUP BY in Django
I have some question: # models.py class someinfo(models.Model): data1 = models.BigIntegerField(verbose_name='data1') data2 = models.BigIntegerField(verbose_name='data2') data_pubdate = models.DateTimeField(default=timezone.now, verbose_name='data_pubdate') people = models.ForeignKey(Drive, on_delete=models.CASCADE, verbose_name='people') data table have: # row data data1 data2 data_pubdate people 7777129 23232 2017-05-18 05:04:08.377 9 158160 4573279 2017-05-18 05:04:08.737 8 158200 5709307 2017-05-18 05:04:08.787 6 10073 11612 2017-05-18 05:04:19.727 6 2458 5245466 2017-05-18 05:04:19.727 4 2458 5245466 2017-05-18 05:04:19.724 4 14879 9727 2017-05-18 05:04:19.897 7 ...etc I want select data1 and data2 from new data_pubdate in each people, like this table: # select data data1 data2 data_pubdate people 7777129 23232 2017-05-18 05:04:08.377 9 158160 4573279 2017-05-18 05:04:08.737 8 10073 11612 2017-05-18 05:04:19.727 6 2458 5245466 2017-05-18 05:04:19.727 4 14879 9727 2017-05-18 05:04:19.897 7 So...What should I do? P.S. django version is "1.10", database is "MSSQL server 2012" -
Cannot Get Django Template to Print Formatted JSON
I'm struggling with printing a formatted JSON response from Watson's NLU API. I'm using Python 2.7 and Django 1.11. My views.py looks like this: def nlu_analysis(request): if request.method == 'POST': text2send = request.POST.get('text2send') natural_language_understanding = NLUV1( version='2017-02-27', username='####', password='####') response = natural_language_understanding.analyze( text=text2send, features=[features.Entities(), ... features.SemanticRoles()]) parsedData = json.dumps(response, indent=2) return render(request, 'analysis.html', {'data': parsedData}) My analysis.html looks like this: <div class="container text-left"> <p>{{ data }}</p> </div> The result of all of this is the data, with JSON brackets being printed on one line like this: { "semantic_roles": [ { "action": { "text": "are", "verb": { "text": "be", "tense": "present" }, "normalized": "be" }, "sentence": "Batman and Superman are fighting the bad guys", ... "keywords": [ { "relevance": 0.931284, "text": "bad guys" }, { "relevance": 0.790756, "text": "Superman" }, { "relevance": 0.752557, "text": "Batman" } ] } If I run this within a for loop <div class="container text-left"> {% for d in data %} <p>{{ d }}</p> {% endfor %} </div> it simply prints on character on each line { " s e m ... suggesting that {{ data }} is a string, nothing more. Clearly I am fundamentally misunderstanding something. Either it is something with respect to how json.dumps … -
How can i pass multiple variables to my template in django?
Hey guys my files are organized as follows. urls.py: from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^contact/', views.eurusd, name='eur'), url(r'^contact/', views.VaR, name='lol'), ] views.py: from django.shortcuts import render from django.http import HttpResponse from yahoo_finance import Currency def eurusd (request): eur_usd = Currency('EURUSD') eur = ('EUR/USD Bid/Ask Price: ' +eur_usd.get_bid() +' / '+eur_usd.get_ask()) return render(request, 'personal/basic.html', {'eur': eur}) def VaR (request): hallo = "this is a python sting" return render(request, 'personal/basic.html', {'lol': hallo}) basic.html {% extends "personal/header.html" %} {% block content %} <p>{{eur}}</p> <p>{{lol}}</p> {% endblock %} My question now is: why is only the string from eur dictionary being returned in my template named basic.html and not the lol? how can i pass multiple variables to my basic.html? -
Should I make 1 form for each upvote button or 1 form for all the buttons?
Let's say I'm making some page where you can upvote several items in a list. Using django templates I might make a form encompassing the upvote button, or encompassing the entire list of posts, i.e.: <ul> {% for post in posts %} <li> {{ post.url }} <form action="/upvote" method="POST"> <button name="post_id" value="{{ post.id }}" type="submit">Upvote</button> </form> </li> {% endfor %} </ul> or <form action="/upvote" method="POST"> <ul> {% for post in posts %} <li> {{ post.url }} <button name="post_id" value="{{ post.id }}" type="submit">Upvote</button> {% endfor %} </ul> </form> Which one is better practice? I guess this could be a duplicate of this question: Each Radiobutton for each form or 1 Form for all radiobuttons? -
How can I print several forms in the django template in a loop by id?
I have a model with name cutset and detailcut(other model) with foreign key cutset id, I want to print every cutset form with the appropriate detailcuts, my view is this def get_context_data(self, **kwargs): sale = Sale.objects.get(pk=self.kwargs.get('pk')) cutsets = CutSet.objects.filter(sale=sale) print cutsets context = super(SaleUpdate, self).get_context_data(**kwargs) if self.request.POST: context['detailsheet_formset'] = DetailSheetFormSet(self.request.POST,instance=sale) context['cutset_formset'] = CutSetFormSet(self.request.POST,instance=sale) for cutset in cutsets: context['detailcut_formset'] = DetailCutFormSet(self.request.POST,instance=cutset) context['detailproduct_formset'] = DetailProductFormSet(self.request.POST,instance=sale) else: context['detailsheet_formset'] = DetailSheetFormSet(instance=sale) context['cutset_formset'] = CutSetFormSet(instance=sale) for cutset in cutsets: context['detailcut_formset%s' % cutset.type_sheet.id] = DetailCutFormSet(instance=cutset) context['detailproduct_formset'] = DetailProductFormSet(instance=sale) context['cuts'] = 4 return context How can i print this in the template context['detailcut_formset%s' % cutset.type_sheet.id] = DetailCutFormSet(instance=cutset) My template for know is like this {% for detailcut_form in detailcut_formset1.forms %} <div id="detailcut" class="item-cuts_set"> {{ detailcut_form.type_sheet }} {{ detailcut_form.quantity }} {{ detailcut_form.l1 }} {{ detailcut_form.l2 }} {{ detailcut_form.price }} {{ detailcut_form.price_cut }} {{ detailcut_form.sub_total }} {{ detailcut_form.placed }} {{ detailcut_form.obs }} </div> {% endfor %} I try with add but doesn't work -
How to link a model with multiple random Models?
Consider this example:- https://docs.djangoproject.com/en/1.11/topics/db/queries/#making-queries So the task is to connect an Entry object to blog and author models at the same time without writing separate ForeignKeys. because In my database I have many models like blog and author. so I can't write ForeignKeys relationships to all of them. I was thinking about Array Field (I am using PostgreSQL database) but it does not work with relationships and second thought is ManytoMany Field, but in many-to-many we have to define the model class. but in my case model class is variable. I want something like:- Entry: - references [blog, author, .... around 50 others ] -
Displaying images from ImageField
I try to display the same image of a coin in 2 sections of my site (a list of articles and a gallery of coins). The only difference (I guess) is that from the articles page I call it by a foreign key while from the gallery I call it directly. The image is displayed in the article list but not in the gallery. Here is some code: the models: # coinCollection/models.py: class coin(models.Model): #... coin_thumbnail = models.ImageField(max_length=500, upload_to = join(MEDIA_IMAGES_DIR, MEDIA_COINS_DIR), verbose_name='Miniature') #... # blog/models.py: class article(models.Model): #... article_money = models.ForeignKey(coin, null = True, on_delete = models.SET_NULL, related_name="money" ) the views: # coinCollection/views.py: class coinGallery(ListView): model = coin template_name = 'coinsCollection/gallery.html' context_object_name = 'coins_list' def get_queryset(self): sort_choice = self.request.GET.get('sort') if sort_choice: if sort_choice in ('coin_name', 'coin_millesime'): coin_list = coin.objects.values('id', 'coin_name', 'coin_millesime', 'coin_thumbnail').order_by(sort_choice) elif sort_choice == 'coin_date_added': coin_list = coin.objects.values('id', 'coin_name', 'coin_millesime', 'coin_thumbnail').order_by('-'+sort_choice) else: coin_list = coin.objects.values('id', 'coin_name', 'coin_millesime', 'coin_thumbnail').order_by('coin_name') paginator = Paginator(coin_list, 3) # Show n coins per page page = self.request.GET.get('page') try: coins = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. coins = paginator.page(1) except EmptyPage: # If page is out of range, deliver last page of results. coins = paginator.page(paginator.num_pages) return … -
Python CharFields Diff Comparison
I have two CharFields in Django to store multiple lines of text. When I try to compare them with difflib I get "+" for every character in the field rather than lines. first CharField [ def ] second charField [ deff foo test ] output: +f+f+o+o+t+e+s+t. code: first = Model.objects.get(id=id_1).text second = Model.objects.get(id=id_2).text diff = '' for text in difflib.unified_diff(first, second): for prefix in ('---', '+++', '@@'): if text.startswith(prefix): break else: diff += text I want to show it as github diff compare in the commit changes like: 1 def+f + 2 foo 3 test - 4 bar 5 ba-z What could be the solution? -
only foreign key id retrive when i pass model instance to form but i want other field
i am new in django, i have a problem with instance when pass it in form. Because my instance has 10 field including 3 foreign key field. when i pass instance to the form in views, i only see that the foreign key field attribute only retrive their id only but i want to retrive other field from foreign key table. If it possible please help me. this is the model which i use as instance to pass through form class CreateMasterBet(models.Model): owner = models.ForeignKey(User, null=True, related_name='owner') opposite = models.ForeignKey(User, null=True, related_name='opposite') ownerTeam = models.CharField(max_length=100, default='') oppositeTeam = models.CharField(max_length=100, default='') match = models.ForeignKey(Match) ownerProposedRate = models.IntegerField() ownerProposedRateForOpposite = models.IntegerField() betis = models.CharField(max_length=20, default='open') howMany = models.IntegerField(default=1) time = models.DateTimeField(default=now) def __str__(self): return str(self.owner) + "( " + str(self.ownerTeam) + " )" the forms for this model instance is below: class BetEditForm(forms.ModelForm): owner = forms.CharField(max_length=100, required=False, widget=forms.TextInput(attrs={'placeholder': 'Owner', 'class': 'form-control'})) opposite = forms.CharField(max_length=100, required=False, widget=forms.TextInput(attrs={'placeholder': 'Opposite', 'class': 'form-control'})) ownerTeam = forms.CharField(max_length=100, required=False, widget=forms.TextInput(attrs={'placeholder': 'Owner Team', 'class': 'form-control'})) oppositeTeam = forms.CharField(max_length=100, required=False, widget=forms.TextInput(attrs={'placeholder': 'Opposite Team', 'class': 'form-control'})) match = forms.CharField(max_length=100, required=False, widget=forms.TextInput(attrs={'placeholder': 'Match', 'class': 'form-control'})) ownerProposedRate = forms.IntegerField(required=False, widget=forms.TextInput(attrs={'placeholder': 'Owner need to pay', 'class': 'form-control'})) ownerProposedRateForOpposite = forms.IntegerField(required=False, widget=forms.TextInput(attrs={'placeholder': 'Opposite team pay … -
Inheritance from abstract models and one-to-many relationships
Django 1.11.1 Many to one relationships means access via _set. https://docs.djangoproject.com/en/1.11/topics/db/examples/many_to_one/ I have created an abstract model and inherited from it like below. And I would like to access _set like this: frame.wikishistory_wikihistory_related_set. And I get this error: {AttributeError}'Frame' object has no attribute 'wikishistory_wikihistory_related_set' Could you help me cope with this peoblem. general.abstract_models class FrameSubmodelMixin(models.Model): frame = models.ForeignKey( 'frames.Frame', related_name="%(app_label)s_%(class)s_related", related_query_name="%(app_label)s_%(class)ss", on_delete=models.PROTECT, ) class Meta: abstract = True wikishistory.models.WikiHistory class WikiHistory(FrameSubmodelMixin, WikiGeneral, GeneralHistory): pass -
Python/Django how to avoid to update a queryset object in memory while update the database
If I use my view like this: def test(request): order = Order.objects.filter(status='new') context = {} context['order_list'] = order return render(request, 'checkout/order.html',context) The context variable order_list works fine and it's rendered on the template, but after get the queryset objet order I would like to update the database, so I did it like this: def test(request): order = Order.objects.filter(status='new') context = {} context['order_list'] = order Order.objects.filter(id__in=order).update(status='warning') #added this line return render(request, 'checkout/order.html',context) The update works fine on the database but also change my context variable oder_list, it becomes empty on template. Why the order object is also updated? Am I doing something wrong? -
Is node.js or django "request driven" like PHP?
To be honest I'm a Linux admin and haven't done web development in a few years. My tool of choice for making anything web of the past 10+ years has been LAMP. I'm working on a REST API and I'm thinking of branching out. There are ways to do REST in PHP I know but maybe it's not the best way anymore. The PHP model as far as I'm concerned goes like this: User makes request in their browser (or an AJAX call) PHP get's called up. PHP starts at the top and works it's way sequentially to the bottom, connecting to the DB, running queries, doing stuff, and outputting data. Request is over, the user has their data and is ready to make a new one. With PHP each request is a new deal. There are no shared variables (you can pass things with cookies\sessions) and once the script is done it is done. While reading about Node's architecture it seems as if everything runs in this single threaded event loop. Does that mean node is "always running" and you can share variables between requests or is there a new event loop per request? Does that mean you can … -
integrate Stripe into django project
I've installed dj-stripe into my django project and I have some issues. After installing, and according to the documentation, i've configured all settings and now I try to do a custom charge (I have no plan, user defines itself the amount) Then, my code looks like (with 10 as amount to try): @login_required() def charge_balance(request): form = ChargeBalanceForm() if request.POST: form = ChargeBalanceForm(data=request.POST) if form.is_valid(): customer, created = Customer.get_or_create(subscriber=request.user) amount = Decimal(10.00) customer.charge(amount) return render( request, 'merchant/charge_balance.html', { 'form': form, }) It returns a CardError Exception (Request req_Am9abuzxogBmI7: Cannot charge a customer that has no active card) I really do not understand what append, I wanted to find a page where user enter his card information but unfortunately I only have this exception. Can someone help me ? Thanks -
django models that are imported at load but don't exist yet
i created a new model to replace an old model existing in my code, the old model was imported at application start (referred to at the the top level) i replaced the call to the new model but as you can guess - i cannot run the migrations because they load the code that imports the model, and that results in an error: django.db.utils.ProgrammingError: relation "model" does not exist i have tried to use the SimpleLazyObject but that doesn't seem to work (the same error occurs) did anyone encounter this problem and solve it some way? thanks! -
How to show total pages in JSON response in Djngo Pagination?
I am currently working on pagination in django restful framework. i am successfully done with pagination. but the problem i am facing is that, " JSON response does not include information about total pages in my query and other information like total records etc". how can i include this information in my response. my view.py is `from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger #######################View all mobiles @api_view(['GET']) def getAll_Mobiles(request): try: Mobile_all = Mobile.objects.all() paginator = Paginator(Mobile_all, 10) page = request.GET.get('page') try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), # deliver last page of results. users = paginator.page(paginator.num_pages) serializer_context = {'request': request} serializer = Mobile_Serializer(users,many=True,context=serializer_context) return Response(serializer.data) except Mobile.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) ` and my api returns record on changing page in url. but it does not give me response information. Can anybody please tell me how to include this information in response. i will be very thankful for this favor. -
Date Picker does not shown up
I am new to frontend developer. Normally I do backend and infra. how to show datepicker calender on datefield I am trying to add datepicker to my page replace ordinary textfield with validator from django import forms class ReportOneForm(forms.Form): start_date = forms.DateField(widget=forms.TextInput(attrs={'class': 'datepicker'})) end_date = forms.DateField(widget=forms.TextInput(attrs={'class': 'datepicker'})) def clean(self): cleanded_data = super().clean() start_date = cleanded_data.get('start_date') end_date = cleanded_data.get('end_date') if start_date > end_date: raise forms.ValidationError(f"Start Date must not after End Date") Template <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Report 1 Result</title> <form method="post" class="post-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> </head> <body> </body> </html> <script> $(function() { $( ".datepicker" ).datepicker({ changeMonth: true, changeYear: true, yearRange: "1900:2012", // You can put more options here. }); }); </script> I must misunderstand something in this page Any help would be appreciated -
How to include get and include the CSRF token in the header when working with REST API
I am using python Django for creating the REST API's.The client side is developed in react and is made as a standalone app.I am uisng axios for triggering th http request.I nedd to pass th CSRF token with every post request,But not able to get the CSRF token from the browser. -
Django Rest Framework - Set current user on model with unique constraint
I have a model that represents a device identifier and I'd like to create a unique constraint on the device identifier and the current user. I was passing the user on the save method but I had to remove the constraint and now that I'm trying to write tests the poor code that I wrote becomes difficult to test. How can I write a serializer where I could set the currentuser as default and mantain the unique contrasint on the model. This is my model class DeviceIdentifier(models.Model): owner = models.ForeignKey(HDSAuthUser, primary_key=True, on_delete=models.CASCADE) id_device = models.UUIDField(primary_key=True) insert_date = models.DateTimeField(auto_now_add=True) and this is my serializer class DeviceIdentifierSerializer(serializers.ModelSerializer): """ Device identifier serializer """ class Meta: model = DeviceIdentifier fields = ('id_device', 'owner') -
i can link my clients molde with django User models?
Hi im new using django and is a little confusing the part of model for my project now. i need to create a site that user can have their profile and make post of product that they want to offer like a catalog and i'm thinking create this models: class Users_Types(models.Model): user_type = models.CharField(max_length=1) def __str__(self): return self.user_type return self.id_type_user class Users(models.Model): users_types= models.OneToOneField('Users_Types') e_mail = models.EmailField(unique=True) password = models.TextField() salt = models.TextField() def __str__(self): return self.id_user return self.id_type_user return self.e_mail return self.password return self.salt class Clients(models.Model): users = models.OneToOneField('Users') first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) ci = models.CharField(max_length=9) birth_date = models.DateField(null=True, blank=True) phone = models.CharField(max_length=20) city = models.CharField(max_length=20, default=) class products(models.Model): clients = models.ForeignKey('clients') product = models.CharField(max_length=30) description = models.CharField(max_length=30) Category = models.CharField(max_length=30) but i read about django have it user model, i had to use that model instead that my Users model? and how i can link the django user model with my clients model. i appreciate your help! -
Storing Data from a CSV File into a database
I have a Django model of a hostel with one of the field FileUpload from which I will take a CSV file and populate the database, I have been trying for past two days searching how to do that, but could not get that working This how to import csv data into django models question works but only if I have the path for the file, and I tried many ways but were not successful. Also after that I tried searching harder How do I get a files absolute path after being uploaded in Django? I saw this but even then I could not get it working as it shows some errors I used this URL mapping url(r'^test/$',views.FileUpload.as_view(),name="test") And this is models.py class FileUpload(View): def post(self, request): form = DocumentForm(request.POST) if form.is_valid(): initial_obj = form.save(commit=False) initial_obj.save() # return path name from `upload_to='documents/'` in your `models.py` + absolute path of file. # eg; `documents/filename.csv` print(initial_obj.document) # return `MEDIA_URL` + `upload_to` + absolute path of file. # eg; `/media/documents/filename.csv` print(initial_obj.document.url) form.save() return redirect('/') else: return render(request,'file_upload_form.html', {'form':form }) def get(self, request): return render(request, 'file_upload_form.html', {'form': form,}) But it is showing some namespace error. Please tell me how should I do it, if … -
workon not working inside Gunicorn conf file
enter APPNAME=testapp APPDIR=/home/ubuntu/$APPNAME/ LOGFILE=$APPDIR'gunicorn.log' ERRORFILE=$APPFIR'gunicorn-error.log' NUM_WORKERS=3 ADDRESS=127.0.0.1:8000 cd $APPDIR source ~/.bashrc workon $APPNAME exec gunicorn $APPNAME.wsgi:application \ -w $NUM_WORKERS --bind=$ADDRESS \ --log-level=debug \ --log-file=$LOGFILE 2>>$LOGFILE 1>>$ERRORFILE & this is inside start_guniocorn.sh and while running it error shows workon command not found although it works when used outside the file -
Sort a django queryset by using a trending algorithm
I have a Post model and its corresponding PostScore to track its score (upvotes/downvotes): class Post(models.Model): user = models.ForeignKey(User, blank=True, null=True) title = models.TextField(max_length=76) date = models.DateTimeField(auto_now=True) content = models.TextField(null=True, blank=True) def __str__(self): return self.title class PostScore(models.Model): user = models.ForeignKey(User, blank=True, null=True) post = models.ForeignKey(Post, related_name='score') upvotes = models.IntegerField(default=0) downvotes = models.IntegerField(default=0) and my views: ... posts = Post.objects.all().annotate( score_diff=F('score__upvotes')- F('score__downvotes'))\ .order_by(order) So I'm currently ordering the posts via upvotes - downvotes. But I want something more complex, something like reddit's hot algorithm. I don't think it's possible to add a custom model method to order_by, so how do I go about making a complex order_by? -
in django source code, trying to understand "ContextDecorator"?
in django source, I come cross some code which I can't understand. if ContextDecorator is None: # ContextDecorator was introduced in Python 3.2 # See https://docs.python.org/3/library/contextlib.html#contextlib.ContextDecorator class ContextDecorator(object): """ A base class that enables a context manager to also be used as a decorator. """ def __call__(self, func): @wraps(func, assigned=available_attrs(func)) def inner(*args, **kwargs): with self: return func(*args, **kwargs) return inner what is the "self" in inner function.is the "self" an instance of ContextDecorator? does it have two magic functions? __enter__ __exit__ how does this decorater function ? -
Django formset with manytomany through intermediate model
I want to save data to an intermediary model and do some calculations in the model (by overriding model save). The problem I have is with formsets not able to save to the intermediary model. The intermediary model is created only when there is M2M relationship (that's understood I guess). I have 4 models like so: Category(models.Model): name = models.CharField(..) Tax(models.Model): name = models.CharField(..) rate = models.DecimalField(..) CategoryItem(models.Model): category = models.ForeignKey(Category) taxes = models.ManyToManyField(Tax, through='CategoryItemTax', through_fields=('item', 'tax')) quantity = models.DecimalField(..) price = models.DecimalField(..) # intermediary model below CategoryItemTax(models.Model): category = models.ForeignKey(Category) tax = models.ForeignKey(Tax) item = models.ForeignKey(CategoryItem) rate = models.DecimalField(..) #derived from tax object in the model total_tax = models.DecimalField(..) #calculated in model save My I have a Category model form with CategoryItem formset. My views.py as below: class FormsetMixin(object): object = None def post(self, request, *args, **kwargs): if getattr(self, 'is_update_view', False): self.object = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) formset_class = self.get_formset_class() formset = self.get_formset(formset_class) if form.is_valid() and formset.is_valid(): return self.form_valid(form, formset) else: return self.form_invalid(form, formset) # THE SAVE METHOD def form_valid(self, form, formset): self.object = form.save() formset.instance = self.object instances = formset.save(commit=False) for i in instances: CategoryItemTax.objects.create(category=self.object, item=i, tax=i) CategoryItemTax.save() class CategoryCreateView(FormsetMixin, CreateView): template_name='..' model = Category … -
Module has no exported module named PeopleService - Ionic
I have been folllowing the ionic tutorial: 10 Minutes with Ionic 2: Calling an API Typescript Error Module '"C:/Users/grace/imaginemai/client/apiApp/src/providers/people->service/people-service"' has no exported member 'PeopleSevice'. C:/Users/grace/imaginemai/client/apiApp/src/pages/home/home.ts import { NavController } from 'ionic-angular'; import {PeopleSevice} from >'C:\Users\grace\imaginemai\client\apiApp\src\providers\people-> >service\people-service'; I am not sure what I am doing wrong. I noticed that there were possible errors with the original tutorial so I made some amendments as per a correction posted in the comments: https://github.com/ah3243/ionic2ApiExample/blob/master/src/providers/people-search.ts I am still having issues - I've followed the tutorial but used my own API from a blog I am developing with Django. So although the ionic app is called peopleservice, I am expecting it to produce blog posts. The code is pasted below. Please could someone tell me what I am doing wrong. Thanks in advance. people-service.ts: import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/operator/map'; /* Generated class for the PeopleServiceProvider provider. See https://angular.io/docs/ts/latest/guide/dependency-injection.html for more info on providers and Angular 2 DI. */ @Injectable() export class PeopleService { data1: any; constructor(public http: Http) { console.log('Hello PeopleService Provider'); } load() { if (this.data1) { return Promise.resolve(this.data1); } //dont have the data yet return new Promise(resolve => { this.http.get('localhost:8000/posts/') .map(res => res.json()) .subscribe(data => …