Flask stores and count the number of view - database

I'm making a flask blog, I add a new feature InIt, and It can help to count how many views does current post has, but is there any way that I can present with html code instead of return. Because If I want to get the number of viewer, I won't see the post, but If I want to see the post, I won't see the number, so i want to see the number of view for different post, how should I fix the problem?
routes.py
#app.route("/post/<int:post_id>", methods=['GET', 'POST'])
#login_required
def post(post_id):
post = Post.query.get_or_404(post_id) # post = Get post by post_id
return render_template('post.html', title=post.title, post=post)
#app.route("/visit")
#login_required
def visit():
v = Visit.query.first()
if not v:
v = Visit()
v.count += 1
db.session.add(v)
v.count +=1
db.session.commit()
return jsonify(counter=v.count)
post.html
<html>
<!-- <p>{{ visit.count }}</p> -->
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ url_for('static', filename='profile_pics/' + post.author.image_file) }}">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{{ url_for('user_posts', username=post.author.username) }}">{{ post.author.username }}</a>
<br>
<small class="text-muted">{{ post.date_posted.strftime('%Y-%m-%d %H:%M') }}</small>
{% if post.author == current_user %}
<div>
<a class="btn btn-secondary btn-sm mt-1 mb-1" href="{{ url_for('update_post', post_id=post.id) }}">Update</a>
<button type="button" class="btn btn-danger btn-sm m-1" data-toggle="modal" data-target="#deleteModal">Delete</button>
</div>
{% endif %}
</div>
<div class="post-title">
<h2 class="article-title">{{ post.title }}</h2>
</div>
<article>
<div class="container">
<div class="row">
{{ post.content }}
</div>
</div>
</article>
<br>
<div class="post-tag">
<button type="button" class="btn btn-outline-info">{{ post.tag }}</button>
</div>
<br>
<hr>
<br>
<div>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script src='https://kit.fontawesome.com/a076d05399.js'></script>
<a class="nav-item nav-link" href="{{ url_for('allcomment', post_id=post.id ) }}"><i class='far fa-comment-alt'></i>See all comments</a>
<a class="nav-item nav-link" href="{{ url_for('commentpost', post_id=post.id ) }}"><i class='far fa-comment-alt'></i>Write comments</a>
</div>
</div>
</article>
</html>

return redirect(next_page) if next_page else redirect(url_for('home'))
This line looks suspicious, shouldn't the return be inside the if ?

Related

Undefined variable in app.blade.php laravel5.4

i want to list the name of courses from my database in my navbar menu (app view) :
#foreach ($cours as $cour)
<li><a class="dropdown-item">{{ $cour->nom }}</a></li>
#endforeach
and i created my layoutcontroller to display the view :
class layoutController extends Controller
{
public function showView()
{
$cours = DB::table('cours')->select('id','nom')->get();
return view('app',['cours' => $cours]);
}
}
then i made a route for it :
Route::get('#','layoutController#showView');
the problem is when i navigate to login view for exemple it shows an error that the variable cours is undefined in my app layout view :
Undefined variable: cours (View: C:\wamp64\www\opencourses\resources\views\layouts\app.blade.php) (View: C:\wamp64\www\opencourses\resources\views\layouts\app.blade.php)
here is my login view :
#extends('layouts.app')
#section('content')
<div class="container-fluid">
<div class="row">
<div class="col-md-8 offset-md-2 px-3 py-3 pt-md-4 pb-md-4">
<div class="card">
<div class="card-header">Connexion</div>
<div class="card-body">
<form class="form-horizontal" method="POST">
{{ csrf_field() }}
<div class="row mb-3">
<label for="email" class="col-sm-3 offset-sm-1 col-form-label">Adresse Email</label>
<div class="col-sm-7">
<input type="text" class="form-control" id="email" name="email">
</div>
</div>
<div class="row mb-3">
<label for="password" class="col-sm-3 offset-sm-1 col-form-label">Mot de passe</label>
<div class="col-sm-7">
<input type="password" class="form-control" id="password" name="password">
</div>
</div>
<div class="row mb-3">
<div class="offset-sm-4 col-sm-7">
<button type="submit" class="btn btn-primary">Envoyer</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
and here is my app view :
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<title>Mon blog</title>
<link rel="icon" href="https://www.jsdelivr.com/img/icon_256x256.png">
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css">
<!-- other CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/2.3.1/css/flag-icon.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/font-awesome#4.7.0/css/font-awesome.min.css" rel="stylesheet">
<!-- Bootstrap javascript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<nav class="navbar navbar-expand-md navbar-light p-3 px-md-4 mb-3 bg-body border-bottom shadow-sm">
<div class="container-fluid">
<a class="navbar-brand" href="welcome.html">
<img src="https://www.jsdelivr.com/img/icon_256x256.png" width="30" height="30" class="d-inline-block align-top" alt=""> Mon blog
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ms-auto mb-2 mb-lg-0 d-flex">
<li class="nav-item px-2">
<a class="nav-link active" aria-current="page" href="<?php echo url('')?>">Accueil</a>
</li>
<li class="nav-item dropdown px-2">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Articles
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
#foreach ($cours as $cour)
<li><a class="dropdown-item">{{ $cour->nom }}</a></li>
#endforeach
</ul>
</li>
<!-- si utilisateur non authentifié -->
#guest
<li class="nav-item px-2">
<a class="btn btn-outline-primary me-2" href="<?php echo url('login')?>">Connexion</a>
</li>
<li class="nav-item px-2">
<a class="btn btn-primary" href="<?php echo url('register')?>">S'inscrire</a>
</li>
#else
<!-- si utilisateur authentifié -->
<li class="nav-item px-2">
<a class="nav-link" href="home">Mon compte</a>
</li>
<li class="nav-item px-2">
<a class="nav-link" href="{{ route('logout') }}" onclick="event.preventDefault();
document.getElementById('logout-form').submit();">Déconnexion</a>
</li>
#endguest
</ul>
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
{{ csrf_field() }}
</form>
</div>
</div>
</nav>
#yield('content')
<footer class="container pt-4 my-md-5 pt-md-5 border-top">
<div class="row">
<div class="col-12 col-md">
<img class="mb-2" src="https://www.jsdelivr.com/img/icon_256x256.png" alt="" width="24" height="24">
<small class="d-block mb-3 text-muted">© 2017–2021</small>
</div>
<div class="col-6 col-md">
<h5>Features</h5>
<ul class="list-unstyled text-small">
<li><a class="link-secondary" href="#">Team feature</a></li>
<li><a class="link-secondary" href="#">Stuff for developers</a></li>
<li><a class="link-secondary" href="#">Another one</a></li>
<li><a class="link-secondary" href="#">Last time</a></li>
</ul>
</div>
<div class="col-6 col-md">
<h5>Resources</h5>
<ul class="list-unstyled text-small">
<li><a class="link-secondary" href="#">Resource name</a></li>
<li><a class="link-secondary" href="#">Another resource</a></li>
</ul>
</div>
<div class="col-6 col-md">
<h5>About</h5>
<ul class="list-unstyled text-small">
<li><a class="link-secondary" href="#">Privacy</a></li>
<li><a class="link-secondary" href="#">Terms</a></li>
</ul>
</div>
</div>
</footer>
</body>
</html>
In your existing action you've sent $cours variable only for login view blade. In this kind of situations you can use share() method via "View" facade. This will allow you to share the variable to all your blades (which includes your whole layout blade).
// don't forget to include this class in the top
use Illuminate\Support\Facades\View;
public function showView()
{
$cours = DB::table('cours')->select('id','nom')->get();
View::share('action', $action);
return view('login'); // here not need to pass shared variable
}
In other words, with this you can increase the visibility scope of your sent variables.
I use model class to get data from DB. I hope this will help for you,
class Course extends Model
{
//
protected $table = 'cours';
protected $fillable = array('nom');
}
class LayoutController extends Controller
{
public function showView()
{
$cours = Course::select('id','nom')->get();
$data['cours'] = $cours;
return view('app', $data);
}
}

I want to fetch section wise categories in home page's sections but I am unable to do this. Only one category section is working

I want to fetch category wise data in home page's sections but I am unable to do this. Only one category section is working
I made Category model with belongs to Section model
My Indexcontroller code
namespace App\Http\Controllers\Front;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Slider;
use App\Category;
use App\Section;
class IndexController extends Controller
{
public function index(){
$sliders = Slider::where('status',1)->get();
$categories = Category::with('sections')->where('status',1)->get();
//dd($categories);die;
return view('frontend.index')->with(compact('sliders','categories'));
}
}
My Blade file
#extends('layouts.frontLayout.layout')
#section('content')
<div class="slider_block">
<div class="flexslider top_slider">
<ul class="slides">
#foreach($sliders as $slider)
<li class="slide1">
<div class="container">
<div class="flex_caption1">
<p class="slide-heading FromTop">{{ $slider['slider_title'] }}</p><br/>
<p class="sub-line FromRight" style="width: 60%;line-height: 20px;font-size: 16px;">{{ $slider->slider_text }} </p><br>
{{ $slider['button_text'] }}
</div>
<div class="flex_caption2 FromRight" style="background-image: url(/images/sliders/{{ $slider['slider_image'] }});"></div>
</div>
</li>
#endforeach
</ul>
</div>
</div>
</header>
<section class="wrapper">
<section class="promo_box dark wow fadeInDown">
<div class="container">
<div class="row">
<div class="col-sm-9">
<div class="promo_content">
<h3>go2tourism</h3>
<p>Lorem ipsum dolor sit amet, cons adipiscing elit. Aenean commodo ligula eget dolor. </p>
</div>
</div>
<div class="col-sm-3">
<div class="pb_action">
<a class="btn btn-lg btn-default" href="#fakelink">
<i class="fa fa-shopping-cart"></i>
Order Now
</a>
</div>
</div>
</div>
</div>
</section>
<section class="latest_work">
<div class="container">
<div class="row sub_content">
<div class="col-md-12">
<div class="dividerHeading">
<h4><span>Find your best tours</span></h4>
</div>
<div id="recent-work-slider" class="owl-carousel">
#foreach($categories as $category)
#if($category['sections']['section_name'] == "Tours")
<div class="product">
<figure class="touching effect-bubba">
<div class="product-img">
<img class="img-responsive" src="{{ asset('images/categories/'.$category['category_banner']) }}">
<div class="option">
<a class="fa fa-shopping-cart" href="portfolio_single.html"></a>
<a class="fa fa-search mfp-image" href="{{ asset('images/categories/'.$category['category_banner']) }}"></a>
</div>
</div>
</figure>
<div class="product-info">
<div class="product-title">
<h3>
{{ $category['category_name'] }}
</h3>
</div><br>
</div>
</div>
#endif
#endforeach
</div>
</div>
</div>
</div>
</section>
<section class="latest_work">
<div class="container">
<div class="row sub_content">
<div class="col-md-12">
<div class="dividerHeading">
<h4><span>Find your best stays</span></h4>
</div>
<div id="recent-work-slider" class="owl-carousel">
#foreach($categories as $category)
#if($category['sections']['section_name'] == "Stays")
<div class="product">
<figure class="touching effect-bubba">
<div class="product-img">
<img class="img-responsive" src="{{ asset('images/categories/'.$category['category_banner']) }}">
<div class="option">
<a class="fa fa-shopping-cart" href="portfolio_single.html"></a>
<a class="fa fa-search mfp-image" href="{{ asset('images/categories/'.$category['category_banner']) }}"></a>
</div>
</div>
</figure>
<div class="product-info">
<div class="product-title">
<h3>
{{ $category['category_name'] }}
</h3>
</div><br>
</div>
</div>
#endif
#endforeach
</div>
</div>
</div>
</div>
</section>
<section class="latest_work">
<div class="container">
<div class="row sub_content">
<div class="col-md-12">
<div class="dividerHeading">
<h4><span>Find your best cars</span></h4>
</div>
<div id="recent-work-slider" class="owl-carousel">
#foreach($categories as $category)
#if($category['sections']['section_name'] == "Cars")
<div class="product">
<figure class="touching effect-bubba">
<div class="product-img">
<img class="img-responsive" src="{{ asset('images/categories/'.$category['category_banner']) }}">
<div class="option">
<a class="fa fa-shopping-cart" href="portfolio_single.html"></a>
<a class="fa fa-search mfp-image" href="{{ asset('images/categories/'.$category['category_banner']) }}"></a>
</div>
</div>
</figure>
<div class="product-info">
<div class="product-title">
<h3>
{{ $category['category_name'] }}
</h3>
</div><br>
</div>
</div>
#endif
#endforeach
</div>
</div>
</div>
</div>
</section>
<section class="promo_box reverse wow bounceInUp" data-wow-offset="50">
<div class="container">
<div class="row">
<div class="col-sm-9 col-md-9 col-lg-9">
<div class="promo_content">
<h3>Do you have any questions to us?</h3>
<p>Please contact us without any hesitation </p>
</div>
</div>
<div class="col-sm-3 col-md-3 col-lg-3">
<div class="pb_action">
<a class="btn btn-lg btn-default" href="#">
Contact Us
</a>
</div>
</div>
</div>
</div>
</section>
</section>
#endsection
Only first section's categories are showing but others section categories are not showing
Please help me

Why float-right, float-left don't working properly?

This is snippet code.
<div class="row col-xs-12">
<a *ngFor="let rec of recipe "href="#" class="list-group-item clearfix">
<div class="float-left">
<h4 class="list-group-item-heading">{{rec.name}}</h4>
<p class="list-group-item-text">{{rec.description}}</p>
</div>
<span class="float-right">
<img [src]="rec.imagePath" alt="{{rec.name}}" class="img-responsive" style="max-height: 50px;">
</span>
</a>
<app-recipe-item></app-recipe-item>
I wonder why float-right don't align image to right side. If i use insetead pull-right it's working.I have read that bootstrap 4 we should float rather than pull.
I deleted list-group-item, list-group-item-heading , list-group-item-text and it worked.
<a href="#" class="clearfix" *ngFor="let recipe of recipes">
<div class="float-left">
<h4>{{ recipe.name }}</h4>
<p>{{ recipe.description }}</p>
I solved this by removing the xs-12 specifier in the col class.
<div class="row">
<div class="col">
<a href="#" class="list-group-item clearfix" *ngFor="let recipe of recipes">
<div class="float-left">
<h4 class="list-group-item-heading">{{ recipe.name }}</h4>
<p class="list-group-item-text">{{ recipe.description }}</p>
</div>
<span class="float-right">
<img
[src]="recipe.imagePath"
alt="{{ recipe.name }}"
class="img-responsive"
style="max-height: 50px"
/>
</span>
</a>
<app-recipe-item></app-recipe-item>
</div>
</div>

Service (factory) error - json api not displaying data

I have spent like a good 4 to 6 hours on trying to solve my issue - maybe I am looking at it completely wrong.
controller.js file:
'use strict';
/* Controllers */
var bookControllers = angular.module('bookControllers', []);
bookControllers.controller('BookListCtrl', ['$scope', 'Book',
function($scope, Book) {
$scope.books = Book.query();
$scope.orderProp = 'name';
}]);
bookControllers.controller('BookDetailCtrl', ['$scope', '$routeParams', 'Book',
function($scope, $routeParams, Book) {
$scope.book = Book.get({bookId: $routeParams.bookId}, function(book) {
$scope.mainImageUrl = book.avatar;
});
$scope.setImage = function(imageUrl) {
$scope.mainImageUrl = imageUrl;
};
}]);
My service.js file
'use strict';
/* Services */
var bookServices = angular.module('bookServices', ['ngResource']);
bookServices.factory('Book', ['$resource',
function($resource){
return $resource('https://api.myjson.com/bins/1oofv', {}, {
query: {method:'GET', params:{bookId:'bookId'}, isArray:true}
});
}]);
So what is happening.
My SHOW file - which displays all books within my book.json file which I have hosted on myjson displays all the content I need.
It displays all thumbnails accordingly with the following html:
<div class="container">
<!--Nav Bar-->
<div class="row">
<div class="col-md-4">
Find me the best
<select ng-model="orderProp" class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown">
<option value="name">Alphabetical</option>
<option value="age">Newest</option>
</select>
</div>
<div class="col-md-4">
Books about
<select ng-model="orderProp" class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown">
<option ng-repeat="book in books" value="">{{ book.genre.name }}</option>
</select>
</div>
<div class="col-md-4">
<div class="input-group">
<input ng-model="query" type="text" class="form-control" placeholder="Search books">
<span class="input-group-btn">
<button class="btn btn-default" type="button"><span class="glyphicon glyphicon-search" ></span></button>
</span>
</div>
</div>
</div>
<!--Body content-->
<div class="row">
<div class="col-md-4" ng-repeat="book in books | filter:query | orderBy:orderProp">
<div class="thumbnail" id="books">
<img ng-src="{{ book.cover }}">
<div class="caption">
<h4>{{ book.name }}</h4>
<h5>{{ book.author.name }}</h5>
<span class="glyphicon glyphicon-heart likes">{{ book.likes }}</span>
<span style="float: right;">{{ book.published | date:'yyyy-MM-dd' }}</span>
</div>
</div>
</div>
</div>
</div>
This is all fine - now when I click a specific book or author I am expecting the app to nav to the next page a detail ALL the details I need in the following template (but it doesn't):
<div class="container">
<div class="row">
<header>
<h1></h1>
<h4></h4>
<p></p>
<h6>Categories:</h6>
<span>{{ book.genre.category }}</span>
</header>
</div>
<div class="row">
<h3>Introduction</h3>
<h1></h1>
<p></p>
<div class="line-sep"></div>
<img ng-src="{{ avatar }}" class="img-round" />
<h2></h2>
</div>
<div class="row">
<h1>Similar reading</h1>
<p></p>
<div class="col-md-4">
<div class="thumbnail" id="books">
<img ng-src="http://placehold.it/350x500">
<div class="caption">
<h4>Lorem Ipsum Dolar Asar</h4>
<h5>By Mr Lorem Ipsum</h5>
<span class="glyphicon glyphicon-heart likes">1032</span>
<span style="float: right;">3 days ago</span>
</div>
</div>
</div>
<div class="col-md-4">
<div class="thumbnail" id="books">
<img ng-src="http://placehold.it/350x500">
<div class="caption">
<h4>Lorem Ipsum Dolar Asar</h4>
<h5>By Mr Lorem Ipsum</h5>
<span class="glyphicon glyphicon-heart likes">1032</span>
<span style="float: right;">3 days ago</span>
</div>
</div>
</div>
<div class="col-md-4">
<div class="thumbnail" id="books">
<img ng-src="http://placehold.it/350x500">
<div class="caption">
<h4>Lorem Ipsum Dolar Asar</h4>
<h5>By Mr Lorem Ipsum</h5>
<span class="glyphicon glyphicon-heart likes">1032</span>
<span style="float: right;">3 days ago</span>
</div>
</div>
</div>
</div>
</div>
Look at my josn file on the site: https://api.myjson.com/bins/1oofv
All I need to do is the following:
Use the json file to display the books (with some details) on the list page - in whatever display style I feel is appropriate.
Then - once all the books are displayed (with search and filter abilities) - be able to click on a book and be taken to a BOOK DETAIL page where we will delve into more detail about the book and show books that are similar to them.
stop stressing, and follow the Flatlander Gemstore tutorial.
First problem I could spot is, you use Book.get but defined Book.query
Secondly, using href="#" breaks angular, either use an <a href="">or, as I prefer, simply use a button, a hyperlink that goes nowhere isn't a link.
as yeouuu said, href="{{ book.id }}" seems wrong, this is either a semantical error and should be href="{{ book.url }}" or this is simply an error and should have been something else entirely.
Do the tutorial, it is a great resource.

Angularjs : How to display data after update on my UI

I have angular project My Requirement is : How to display data after update on my UI without refreshing, Data store in server i want it to display on Contact and Recent Tab immediately after Updating.
UI Bindings:
<li class="media contact-card">
<div class="media-left">
<a ui-sref=".viewClient({'clientId':client._id})">
<img class="media-object img-circle" src="https://placehold.it/42x42" alt="https://placehold.it/64x64">
<!--<div class="circle" ng-class="getRandomColorClass('Xipesh Gandhi')"><p>{{generateInitialChar('Dipesh Gandhi')}}</p></div>-->
</a>
</div>
<div class="media-body">
<div class="pull-left">
<h4 class="media-heading pull-left">{{client.firstName}} {{client.lastName}}</h4>
</div>
<div class="pull-right">
<a class="" ui-sref=".editClient({'clientId':client._id})"> <i class="glyphicon glyphicon-pencil" ></i></a>
<a class=""> <i class="glyphicon glyphicon-trash" ></i></a>
</div>
<div class="clearfix"></div>
<span>{{client.address}}</span>
<span>{{client.birthDate | date:'mediumDate'}}</span>
</div>
</li>
View :
<div class="tab-wrapper">
<tabset justified="true">
<tab heading="CONTACTS">
<div class="tab-content">
<div>
<div class="pull-right">
<a class="add-client-link" ui-sref=".client"> <i class="glyphicon glyphicon-plus" ></i> Add Contact </a>
</div>
<div class="clearfix"></div>
</div>
<div class="hr"></div>
<div class="scrollable-container">
<ul class="media-list">
<contact-card data-client="client" ng-repeat="client in clientList"></contact-card>
</ul>
</div>
</div>
</tab>
<tab heading="RECENT">
<div class="tab-content">
<div>
<div class="pull-right">
<a class="add-client-link" ui-sref=".client"> <i class="glyphicon glyphicon-plus" ></i> Create Meeting </a>
</div>
<div class="clearfix"></div>
</div>
<div class="hr"></div>
<div class="scrollable-container">
<ul class="media-list">
<contact-card data-client="client" ng-repeat="client in clientList"></contact-card>
</ul>
</div>
</div>
</tab>
</tabset>
</div>
Controller:
$scope.updateClientList = function(client, operation){
if(operations.ADD === operation){
//$scope.clientList.push({firstname: $scope.client.firstName, lastname: $scope.client.lastName});
//$scope.clientList.push(client);
$scope.clientList.push (client);
// $scope.clientList = [];
} else if(operations.EDIT === operation){
} else if(operations.DELETE === operation){
}
$state.go('meeting-home.viewClient', {'clientId':client._id});
};
Does anyone know how to do it?
Please comment $scope.clientList = []; in your code. it will work. Any how you are not mentioning UI binding details.

Resources