Django Aggregation in View - html

I would like to show the result of the query from the database on my html view.
When I run my raw sql aggregate query in the Django shell, I get the result I'm looking for. But when I pass the data into my html from the view, it does not show any data.
My views.py and I also have the model imported
def officehome(request):
"""Renders the office home page."""
assert isinstance(request, HttpRequest)
ordersrecieved = FbsOrderT.objects.count()
return render(
request,
'app/officehome.html',
{"ordersrecieved": ordersrecieved}
)
this is in the html view
<ul class="list-group">
<li class="list-group-item">
<h5 class="list-group-item-heading">Orders Received <span {ordersrecieved}></span></h5>
</li>
Would angular routing be a problem and not knowing when to execute the query.

This is wrong:
<h5 class="list-group-item-heading">Orders Received <span {ordersrecieved}></span></h5>
what you want is:
<h5 class="list-group-item-heading">Orders Received <span> {{ ordersrecieved }}</span></h5>
The way templating works is it converts {things which are in here to the python variable context} so if it is in the text of the html it will work if its an attribute of the span (as in <span {gergerg}>) then that might render but as nothing visible to the user. Also use {{ }} rather than { unless you specified a custom templating parser.

Related

Get the last 2rd item in HTML

I have used Django to develop a webapp
In the admin model, I used Django simple UI package, I want to choose the last 2rd one in the list(models)
How could I slice in the below?
<div v-for="(c,j) in models" :key="c.name" class="quick-wrap">
<a href="javascript:;" #click="openTab(c,(j+1)+'')">
<span class="icon" :class="c.icon"></span>
<span class="card-name" v-text="c.name"></span>
</a>
</div>
Not sure what last 2rd means, but if you want the last 2 items in what appears to be a context variable called models you can do that in the view you use to call this html file. Using a slice on your queryset you should be able to pass models[-2:] to get the last two and pass that instead of models. Vue may have a way to slice as well, but if you can do it in the view, it probably makes sense to do so.

Angular 8 routerLinks create decoded href with # to %23

I have one problem with generating routerLinks in my application.
I retrieve the menu structure from API. Fetch it when app initializes, store it in the Observable and then simply show it.
The part of the structure im showing is pretty straightforward.
<ng-container *ngFor="let item of menuItems">
<h5 class="dekstop-submenu-heading">{{ item.name }}</h5>
<ul class="desktop-submenu-list" [ngClass]="{'desktop-submenu-list-wrap': item.subItems.length > 5}">
<li *ngFor="let subItem of item.subItems" class="desktop-submenu-item">
<a [attr.aria-label]="subItem.name" [routerLink]="subItem.url">{{ subItem.name }}</a>
</li>
</ul>
</ng-container>
The problem comes when there is an url with an anchor to specific page part, i.e. /some-component/description#specific.
Angular routerLink is generated properly but the href isn't, it is decoded to /some-component/description%23specific.
I can't get rid of this behaviour, I've tried decoding it with decodeURIComponent but with no effects..
Do you have any idea what causes such behaviour? Such a simply thing makes a lot of troubles..
You just need to send the urlĀ and the element id in a separate directive.
If you have control over the subItem.url then just rename it to /description and subItem.fragment to specific and then change the template like this:
[routerLink]="subItem.url" [fragment]="subItem.fragment"
If you don't have control over subItem.url, then just perform a split on %23:
const [url, ...fragment] = subItem.url.split('%23');
[routerLink]="url" [fragment]="fragent.join('%23')"
You can handle query params in routerLink directive
I think this will help you
<a [attr.aria-label]="subItem.name" [routerLink]="subItem.url"
queryParamsHandling="preserve">{{ subItem.name }}</a>

asp-route-{value} tag helper not respecting route template

I'm working on a breadcrumb implementation in .net core 2.0,
The requirement is to be able to create a hierarchical menu, where the previous bread crumb item will take to the parent and so on...
the implementation is based on a bread crumb ViewComponent model, which reads the current route data and embeds the params as part of the breadcrumb links as tag helpers (asp-route-{value})
Problems:
I have 2 problems:
The ViewContext.RouteData.Values in the Razor View for the breadcrumb Component does not contain the key "id" thats supposed to get passed as query string parameter
Even if I hard code the above for testing purpose, injecting it back into the anchor tab in Razor view using asp-route-id - doesn't inject it as query string parameter at the end of the action but inserts it as "{controller}/{action}/{id}" after the action
Here's the URL from the browser:
http://127.0.0.1:5100/XXX/Service/{item_id}/Hardware/UpdateOrder?orderId={order_id}
for the previous breadcrumb, it should generate
http://127.0.0.1:5100/XXX/Service/{item_id}/Hardware/Detail?orderId={order_id}
the Id's are GUID
The Route template in Startup.asp
routes.MapRoute(
name: "areaRouteWithWholesaleCustomerCodeAndTargetId",
template: "{wholesaleCustomerCode}/{area:exists}/{baseItemId:guid}/{controller=Home}/{action=Index}/{id:guid?}"
);
The Breadcrumb ViewComponent Razor View:
#model BreadcrumbModel
<ul class="list-unstyled breadcrumbs" id="breadcrumbs">
#{
var baseItemId = ViewContext.RouteData.Values["baseItemId"] ?? "";
var id = ViewContext.HttpContext.Request.QueryString.Value ?? "";
id = "orderid=testid-123";
}
#foreach(var li in Model.Breadcrumb)
{
<li>
<a asp-area="#li.AreaName" asp-controller="#li.ControllerName" asp-action="#li.ActionName" class="#li.Class" asp-route-baseItemId="#baseItemId" asp-route-id="#id">
#li.DisplayName
</a>
</li>
}
</ul>
Data Available in ViewContext.RouteData - note that there's no id being passed as part of the route data -
ViewContext.HttpContext.Request.QueryString value:
Using the asp-route-{value} tag helper I'm injecting 2 id's into the anchor tag, baseItemId which is part of the route mapping and id - which is also part of the route mapping but as query string
when the menu is rendered this is what I get at the breadcrumb :
<a class="" href="/XXX/Service/Hardware/Detail/orderid%3DtestId-123?baseItemId=09185d87-5e3f">
Hardware
</a>
somehow, it isn't respecting the route template at all
I expected it to render it as follows:
Hardware
Expected Behavior:
I would have expected it to work as follows:
I should be able to get the value "id" from route values, rather than relying on query string parameters
on injecting the 2 id's based on the documentation, they should appear at their respective positions as defined in the routing template, baseItemId first as part of the route - then id as a query string part of the last action
Any Suggestions or insights into this ?
It's doing exactly what you're telling it to do. You're setting the id to the query string or simply orderId=test123. As a result, it's cramming that string into the id part of the route (while escaping the = sign, since it's invalid in that portion of the URI). What you should be doing instead, if you want the orderId as part of the query string, is to pass that as a route param: asp-route-orderId="#orderId".
As far as your baseItemId not going into the route goes, there's most likely another route that's being matched, which doesn't include this param. Routing short-circuits, so it will always choose the least specific route it can match, and then just dump anything else it doesn't need as the query string. You should either change the order of your routes or use a custom named route instead, to remove ambiguity.
If that's not the issue, the only other possibility is that the guid constraint on baseItemId is somehow not being satisfied by what you're passing for that param.

Is it bad practice to create Divs just to have multiple controllers?

Is a bad practice to be creating divs in your HTML just to be able to have multiple controllers?
Since you cannot have them in one also the approach of having multiple directives with separate controllers seems like a hack, but correct me if I am wrong.
So I have 2 controllers - one is called ConvertController and the other one is called YouTubeLinkUIController.
The responsibility of the first one is to hit my Web API controller and convert the given YouTube link into an audio.
The responsibility of the second one is to control some of the UI functionality.
In order to follow the single responsibility principle, I have separated them into 2 different controllers and therein lies the problem.
My last commit, specifically Index.cshtml shows the full code, but for the sake of not making this messy I will abreviate it for this post.
https://github.com/AvetisG/TubeToTune/commit/e68ba42f20498c9a4e032328aed6d68c27b9b2cb
<div class="container" ng-app="TubeToTuneApp" ng-controller="YouTubeLinkUIController">
... more code
#*Scoping the Convert Controller*#
<div ng-controller="ConvertController">
... more code
</div>
</div>
Looking at your github commit message it looks like you split the controllers because you didn't want to have too much code in your ui controller.
This is a perfect example of when an angular service is in order. You can think of a service like a controller without all the overhead and that can be easily called from another controller
Angular Service Documentation
What you should do is define a service that calls your api and then
angular.module('youTube', [])
.controller('YouTubeLinkController', ['$scope', 'convert',
function($scope, convert) {
$scope.convertLink = function() {
$scope.convertMessage = convert.convertYoutube()
};
}
])
.factory('convert', [
function() {
var convertService = {};
convertService.convertYoutube = function(data) {
//Make api call
return "Conversion Done";
}
return convertService;
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="youTube">
<div ng-controller="YouTubeLinkController">
{{convertMessage}}
<button ng-click="convertLink()">Convert</button>
</div>
</body>
Naturally you should define the service in it's own page. That way controllers are only used for interacting with UI. It also solves your problem
It's absolutely fine to use divs\spans and nested structures and use ng-controller with it.
When you add ng-controller to a html element in a way you are creating a component with a model-view and controller.
A complex component can have nested sub components that perform very specific functionality and in a way you are demarcating such parts with ng-controller . To take it a step further if you convert these component into directives, with their own controller + template(view) and that accept model from a data source, then you have a reusable component that you can use throughout the app.
To me, it looks more like your ConvertController should be written as a service, rather than as a controller. This would still follow single responsibility, but would probably align closer to your intended functionality: UI functionality and view data in the controller, business logic in the service.
That said, having two controllers on a single view might not be bad practice, this leads to confusing mark-up in cases like the following:
<button type="submit" class="btn btn-xlarge btn-warning btn-block" ng-if="AreThereYouTubeLinks() == true" ng-click="ConvertToTunes(YouTubeLinks)">
You may know personally which controllers AreThereYouTubeLinks(), ConvertToTunes(), and YouTubeLinks belong to, but this will be confusing in the long-term (and can lead to issues with scope-bound variables like YouTubeLinks.
Luckily, there's a syntax for helping clear this up- Controller As - and Todd Motto wrote an excellent article explaining how to use it and what problems it helps solve. In brief, it would turn something like this:
<div ng-controller="MainCtrl">
{{ title }}
<div ng-controller="AnotherCtrl">
{{ title }}
<div ng-controller="YetAnotherCtrl">
{{ title }}
</div>
</div>
</div>
in to this:
<div ng-controller="MainCtrl as main">
{{ main.title }}
<div ng-controller="AnotherCtrl as another">
{{ another.title }}
<div ng-controller="YetAnotherCtrl as yet">
{{ yet.title }}
</div>
</div>
</div>
In your case, you would end up with this safer, more understandable mark-up:
<div class="container" ng-app="TubeToTuneApp" ng-controller="YouTubeLinkUIController as linkCtrl">
... more code
#*Scoping the Convert Controller*#
<div ng-controller="ConvertController as converter">
<button type="submit" class="btn btn-xlarge btn-warning btn-block" ng-if="linkCtrl.AreThereYouTubeLinks() == true" ng-click="converter.ConvertToTunes(linkCtrl.YouTubeLinks)">
</div>
</div>
If you're going to stick with two controllers, you probably want to consider investing the time to getting comfortable with Controller As.

display binary image from db to angular partial view

I was trying to display image which is coming within the json object returning from an web api request. I'm able to display string, number and date/time in my angular partial but couldn't get the image displaying.
here is my json object which contains each field of my topic (model) class
<Topic>
<Body>dsadfsaadsfds</Body>
<Created>2014-06-15T00:00:00</Created>
<Flagged>false</Flagged>
<Id>1022</Id>
<PhotoFile>
iVBORw0KGgoAAAANSUhEUgAAB2wAAAOiCAIAAAAzNbBAAAABiWlDQ1BJQ0MgUHJvZmlsZQAAKBWtkT1LA0EQht+L0SgJGCRoCpEFRSzu5IxFTLTJB5iIRYgKane5nImQj+NyIfoD7Gy0EG0U9S+INhaWYqGFIAjB3yAEAi..........
(I want to post screen shot but i can't due to lack of reputations.....)
</PhotoFile>
<Replies i:nil="true"/>
<Title>csdaadsf</Title>
and here is my angular html partial:
<a data-ng-href="#/message/{{ i.id }}">{{ i.title }}</a>
</div>
<div class="date span2">
{{ i.created | date:"medium" }}
</div>
<div class="contents span12">
{{ i.body }}
</div>
<img ng-alt="" src="{{'data:image'+i.photofile}}" /> </div>
`
Since i can get other attributes working, my angular factory and controller should be working. Are there anything wrong with my syntax in angular partial view for displaying images? Thanks
You shouldn't be using the src attribute when using Angular expression as the value. Use ng-src instead, it will ensure the image don't show up before Angular has a chance to replace the expression.
If the sample payload you've shown is complete, the way you are forming the data URI is incomplete. Depending on the format of the image, the header should look like
data:image/png;base64,[things in the JSON]
You can read more about the format here