Object relational mapping ('and_' not working) - flask-sqlalchemy

and_ is not working
can anyone help me out. i am new to flask
test.py
from flask import session,Flask,render_template,request
from models import *
import os
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DATABASE_URL")
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.init_app(app)
#app.route('/')
def index():
query= book.query.filter(and_ (book.title=='we all lost',book.publication_year==2050)).all()
for i in query:
print(i.title)
return render_template('hellotesting.html',m=query)
hellotesting.html
<html>
<head></head>
<body>
<ol>
<li>{{m.title}} </li>
<li>{{m.author}} </li>
<li>{{m.publication_year}}</li>
</ol>
</body>
</html>
error
NameError
NameError: name 'and_' is not defined
i dont know why it is not working

You need to import it before you can use it
from sqlalchemy import and_
and then
query = book.query.filter(and_(book.title=='we all lost',book.publication_year==2050)).all()
Also in your hellotesting.html file you try to display attribute of queryset (something like list of your model instances), not particular object and it will raise exception. You have to get any object from queryset in function or in template before call it's attribute.
In function you can do something like
query = book.query.filter(and_(book.title=='we all lost',book.publication_year==2050)).first()
or
book = query[0]
and then put that object to render_template function or you can do something similar in template like
{{ m[0].title }}
Read documentation for more examples and explenations

Related

data i entered in the admin page not reflecting in my webpage,

The data i entered in the admin page not showing up on the web page.
i don't know what is going wrong with my code, please help
webpage
admin.py
from django.contrib import admin
from blog.models import Post
# Register your models here.
class PostAdmin(admin.ModelAdmin):
list_display = ('title','slug','status','created_on')
list_filter = ('status',)
search_fields = ['title','content']
prepopulated_fields = {'slug':('title',)}
admin.site.register(Post, PostAdmin)
urls.py
from . import views
from django.urls import path
urlpatterns = [
path('blogspot/',views.PostList.as_view(), name="b"),
path('<slug:slug>/',views.PostDetail.as_view(), name="post_detail"),
]
views.py
from django.views import generic
from .models import Post
# Create your views here.
class PostList(generic.ListView):
queryset = Post.objects.filter(status=1).order_by('-created_on')
template_name = 'blog/index.html'
class PostDetail(generic.DetailView):
model = Post
template_name = 'blog/post_detail.html'

Why does my old folium app stopped show maps [duplicate]

I wrote a python test program like this to show openstreetmap:
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QUrl
from PyQt5.QtWebEngineWidgets import QWebEngineView
import sys
def mainPyQt5():
url = 'file:///./index.html'
app = QApplication(sys.argv)
browser = QWebEngineView()
browser.load(QUrl(url))
browser.show()
sys.exit(app.exec_())
mainPyQt5()
index.html fetched by QWebEngineView simply calls openstreetmap:
<title>OSM and Leaflet</title>
<link rel = "stylesheet" href = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
<div id = "map" style = "width: 900px; height: 580px"></div><script src = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<script>
// Creating map options
var mapOptions = {
center: [45.641174, 9.114828],
zoom: 10
}
// Creating a map object
var map = new L.map('map', mapOptions);
// Creating a Layer object
var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
// Adding layer to the map
map.addLayer(layer);
</script>
If I fetch index.html with a ordinary browser the map is shown as expected but if I call the simple python program using QWebEngineView no tiles are downloaded from openstreetmap. If I replace openstreetmap with maps.stamen.com everything is fine both with a browser or the python script.
By default QtWebEngine does not set default headers like popular browsers do. In this case the openstreetmap server needs to know the "Accept-Language" to produce the maps since for example the names of the cities will depend on the language to filter non-browser traffic. The solution is to implement a QWebEngineUrlRequestInterceptor that adds that header:
import os.path
import sys
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWebEngineCore import QWebEngineUrlRequestInterceptor
from PyQt5.QtWebEngineWidgets import QWebEngineView
class Interceptor(QWebEngineUrlRequestInterceptor):
def interceptRequest(self, info):
info.setHttpHeader(b"Accept-Language", b"en-US,en;q=0.9,es;q=0.8,de;q=0.7")
def mainPyQt5():
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
filename = os.path.join(CURRENT_DIR, "index.html")
app = QApplication(sys.argv)
browser = QWebEngineView()
interceptor = Interceptor()
browser.page().profile().setUrlRequestInterceptor(interceptor)
browser.load(QUrl.fromLocalFile(filename))
browser.show()
sys.exit(app.exec_())
if __name__ == "__main__":
mainPyQt5()

fill datatable with vueJS

i´m trayin to fill my data table with vueJS and all my data from DB. I´m usign this library:
https://jamesdordoy.github.io/laravel-vue-datatable
It´s ok if i use this in my controller:
User::all()
return response()->json($query);
and in my component:
<div class="">
<data-table :data="data" :columns="columns" #on-table-props-changed="reloadTable"></data-table>
</div>
this library contain method to sortBy, orderBy, search by name, etc... with this:
use JamesDordoy\LaravelVueDatatable\Http\Resources\DataTableCollectionResource;
public function index(Request $request)
{
$length = $request->input('length');
$sortBy = $request->input('column');
$orderBy = $request->input('dir');
$searchValue = $request->input('search');
$query = User::eloquentQuery($sortBy, $orderBy, $searchValue);
$data = $query->paginate($length);
return new DataTableCollectionResource($data);
}
but if i use this in my controller in laravel 8 returned me:
Call to undefined method App\Models\User::eloquentQuery()
i don´t know if this it means to use get(), all().
Also, if i´m not use this and i to do all search manually, for example:
if(isset($sortBy)){
$query = User::all()->sortBy($sortBy);
$data = $query->paginate($length);
}
return response()->json($query);
returned me that:
Method Illuminate\Database\Eloquent\Collection::paginate does not exist
if i removed paginate and return $query, return all my data en my web browser console in network tab, but my table it´s empty...
for back-end i´m using laravel-8
in my web browser console return this message:
Invalid prop: type check failed for prop "data". Expected Object, got Array
if i change :data in my component for :items error in web browser console disappear
i don´t understand that i´m doing wrong for in one case i can fill my table and in other not...
Thanks for read and help me
i resolve my question with this:
$query = \DB::table('users')->orderBy($sortBy, $order)->paginate(10);
with model i can´t

error while generating json object from python dictionary using django_template json_script

I am trying to get a "json" object from a python dictionary using djnago template "json_script",which is throwing "template syntax error"
//html code
{{ value|json_script:"hello-data" }}
<script>
var Value=JSON.parse(document.getElementById("hello-data").textContent);
document.write(Value);
</script>
//views.py
from django.shortcuts import render
from django.http import HttpResponse
import random as ran
# Create your views here.
def indees(request):
vals={"123":"abc","Key":"value","hello":"user"}
return render(request,"verbat.html",context={"value":vals})
The context is the template context dictionary, you cannot access it as a single dict, you can only access its members (keys).
Read here or here for more.
E.g., In your example, you can access 'bool', 'list_' and 'msg', but probably you want to access a dictionary with these three keys.
So you need to put your data inside inner key and use it. Something like:
//views.py
def indes(request):
list_of_vals=[ran.randint(12,34),ran.randint(44,55)]
data={"bool":"True",
"list_":list_of_vals,
"msg":"hello"}
return render(request,"base.html",context={'data':data})
And inside index.html, to have:
{{ data|json_script:"hello-data" }}

Django generic Views with templates

I've added a new template to my project (thing_listings.html) and I've added the views;
from django.views import generic
from .models import Things
class IndexView(generic.ListView):
template_name = 'home/index.html'
def get_queryset(self):
return Things.objects.all()
**class ThingView(generic.ListView):
template_name = 'home/thing_listings.html'
def get_queryset(self):
return Things.objects.all()**
class DetailView(generic.DetailView):
model = Labs
template_name = 'home/detail.html'
and the URl's;
from django.conf.urls import url
from . import views
app_name = 'home'
urlpatterns = [
# /home/
url(r'^$', views.IndexView.as_view(), name = 'index'),
**# /thingview/
url(r'^$', views.ThingView.as_view(), name='thingview'),**
# /home/"details"/
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
]
At the moment the site runs fine, except when I click on the thing_listings link I just get directed to index instead of what thing view is supposed to direct me to. Please help, I'm not sure where I've gone wrong.
Ive used the href: {% url 'home:thingview' %}
I've found the solution if anyone else is having the same issue.
All you should need to do is add the path to your regular expression eg:
url(r'^servicesview/$', views.ServicesView.as_view(), name='services'),
I've repeated the process multiple times to make sure it works.