Can't extend data from Pin model - sqlite

My models.py looks like this.
model.py
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Pin(models.Model):
proffession = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.proffession
def get_absolute_url(self):
return reverse('pin-detail', kwargs={'pk': self.pk})
Views.py
def home(request):
context = {
'pins': Pin.objects.all(),
}
def get(self, request):
users = User.objects.exclude(id=request.user.id)
return render(request, 'vlog/home.html')
return render(request, 'vlog/home.html', context)
class PinListView(ListView):
model = Pin
template_name = 'vlog/home.html' # <app>/<model>_<view_type>.html
context_object_name = 'pins'
ordering = ['-date_posted']
paginate_by = 5
While extending data from Pin model. It doesn't provide any result.
base.html
<div class="col-md-4">
<div class="content-section">
<h3>Available People</h3>
{% for pin in pins %}
<article class="media content-section">
<!-- <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}"> -->
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'profileu' %}">{{ pin.username }}</a>
</div>
<p class="article-metadata">{{ pin.content }}</p>
</div>
</article>
{% endfor %}
</div>
</div>
How can I extend data from Pin Model in ListView. Please Share your suggestion

Related

Search function in Flask with SQLite

I have a problem in my search function. The search result was not displayed in my web application. I'm trying to search words based on the brand or model. I have no idea what did I make mistake.
This is the backend in app.py
#app.route('/search',methods = ['GET','POST'])
def search():
result = request.form.get('search')
conn = get_db_connection()
searchsmartphones = conn.execute("SELECT * FROM Smartphone WHERE brand OR model = ?",(result,))
conn.commit()
return render_template('smartphone.html',searchsmartphones = searchsmartphones)
This is the search form
<form action="/search" method="GET">
<div class="mb-5 d-flex position-relative">
<!-- Search -->
<div class="input-group w-50 mx-auto">
<input class="form-control py-2" placeholder="Search for smartphone" name="search" value="" />
<button type="submit" class="btn btn-secondary text-muted">Search</button>
</div>
</div>
</form>
This is the output result
<div class="d-flex">
{% for smartphone in searchsmartphones %}
<div class="row row-cols-4 mb-5">
<div class="card mr-5" style="width: 20rem;">
<a href="#">
<img src="{{ url_for('static',filename = smartphone['image_URL']) }}" class="card-img-top" style="height: 250px;">
</a>
<div class="card-body">
<a href="#">
<h5 class="card-title">{{ smartphone['model'] }}</h5>
</a>
<div class="mt-5 d-flex justify-content-between">
<p class="text-muted">{{ smartphone['brand'] }}</p>
<p class="fw-bold">{{ smartphone['lowprice'] }} - {{ smartphone['highprice'] }}</p>
</div>
</div>
</div>
</div>
<div class="col-md-auto">
</div>
{% endfor %}
</div>
Traceback (most recent call last):
File "C:\Users\user\desktop\phonebuddy\.venv\lib\site-packages\flask\app.py", line 2525, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\user\desktop\phonebuddy\.venv\lib\site-packages\flask\app.py", line 1822, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\user\desktop\phonebuddy\.venv\lib\site-packages\flask\app.py", line 1820, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\user\desktop\phonebuddy\.venv\lib\site-packages\flask\app.py", line 1796, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
File "C:\Users\user\Desktop\PhoneBuddy\app.py", line 94, in search
searchsmartphones = conn.execute("SELECT * FROM Smartphone WHERE brand LIKE '%?%' OR model LIKE '%?%'",(result,result))
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 0, and there are 2 supplied.
127.0.0.1 - - [27/Nov/2022 22:15:14] "GET /search?search=Apple&sort=low HTTP/1.1" 500 -
Empty when using my original code
The error indicates that we did not pass enough parameters to the select query. I found that we cannot use %?% directly.
Example of using Flask and Sqlite3 for search query
I reproduced the scenario with dummy data and dummy SQL schema. The SQL schema and dummy query insertion happens at the first view of the root / path. The search path is defined in /search route.
File structure:
.
├── app.py
├── mobile_devices.db
├── schema.sql
├── templates
│   ├── home.html
│   └── search.html
schema.sql:
CREATE TABLE IF NOT EXISTS Smartphone (
id INTEGER PRIMARY KEY AUTOINCREMENT,
brand TEXT NOT NULL,
model TEXT NOT NULL,
lowprice DOUBLE NOT NULL
);
app.py:
from flask import Flask, render_template, g, request
import sqlite3
DATABASE = 'mobile_devices.db'
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your secret key'
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect(DATABASE)
db.row_factory = sqlite3.Row
return db
#app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
if db is not None:
db.close()
def query_db(query, args=(), one=False):
cur = get_db().execute(query, args)
rv = cur.fetchall()
cur.close()
return (rv[0] if rv else None) if one else rv
def insert_db(query, args=()):
msg = ""
with app.app_context():
try:
db = get_db()
cur = db.cursor()
cur.execute(query, args)
db.commit()
msg = "Insertion successful"
except Exception as ex:
msg = f"Insertion failed: {str(ex)}"
finally:
print(msg)
def init_db():
with app.app_context():
db = get_db()
with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
init_db()
def insert_dummy_values():
insert_db(
"INSERT INTO Smartphone (brand, model, lowprice) VALUES (?,?,?)",
("Nokia", "C6", 150))
insert_db(
"INSERT INTO Smartphone (brand, model, lowprice) VALUES (?,?,?)",
("Samsung", "Fold", 250))
insert_db(
"INSERT INTO Smartphone (brand, model, lowprice) VALUES (?,?,?)",
("Nokia", "N95", 300))
insert_db(
"INSERT INTO Smartphone (brand, model, lowprice) VALUES (?,?,?)",
("Sony", "Samsung", 1250))
#app.route('/')
def show_home():
smart_phones = query_db('select brand, model, lowprice from Smartphone')
if len(smart_phones) == 0:
insert_dummy_values()
smart_phones = query_db('select brand, model, lowprice from Smartphone')
return render_template('home.html', smart_phones=smart_phones)
#app.route('/search', methods=['GET', 'POST'])
def search():
if request.method == "POST":
search_value = request.form.get('search_brand_model')
print(search_value)
smart_phones = query_db(
"SELECT * FROM Smartphone WHERE brand LIKE ? OR model LIKE ?",
('%' + search_value + '%', '%' + search_value + '%'))
return render_template('search.html', searchsmartphones=smart_phones)
else:
return render_template('search.html')
templates/home.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>
{% if smart_phones%}
Total smartphones in DB: {{ smart_phones | length }}
<ul>
{% for smartphone in smart_phones %}
<li> {{ smartphone['brand'] }} {{ smartphone['model'] }} :
${{ smartphone['lowprice'] }}
</li>
{% endfor %}
</ul>
{% else %}
<p>No smartphone in db</p>
{% endif %}
</body>
</html>
templates/search.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Search</title>
</head>
<body>
<form action="/search" method="POST">
<div class="mb-5 d-flex position-relative">
<!-- Search -->
<div class="input-group w-50 mx-auto">
<input class="form-control py-2"
placeholder="Search for smartphone" name="search_brand_model" value=""/>
<button type="submit" class="btn btn-secondary text-muted">Search
</button>
</div>
</div>
</form>
{% if searchsmartphones %}
<div class="d-flex">
{% for smartphone in searchsmartphones %}
<div class="row row-cols-4 mb-5">
<div class="card mr-5" style="width: 20rem;">
<div class="card-body">
<a href="#">
<h5 class="card-title">{{ smartphone['model'] }}</h5>
</a>
<div class="mt-5 d-flex justify-content-between">
<p class="text-muted">{{ smartphone['brand'] }}</p>
<p class="fw-bold">{{ smartphone['lowprice'] }}</p>
</div>
</div>
</div>
</div>
<div class="col-md-auto">
</div>
{% endfor %}
</div>
{% endif %}
</body>
</html>
Screenshots:
Initial database rows:
Search using Brand Nokia:
Search using model n95:

Omines Datatables with Turbo and Stimulus

I am trying to use Turbo in a new Symfony development. I'm following Turbo: Drive, Frames & Streams as a reference! and previously Symfony UX: Stimulus. Both topics are new to me and as if that weren't enough, I don't have much experience with Javascript.
All good except that I have not been able to get Omines Datatables to work under this scheme. I understand that I must create a Stimulus component but I have not achieved even the most basic thing, which is to load the Datatable.
I wonder if someone can guide me or if they have gone through the same thing, maybe they can provide a practical example of how to do it. Is it too much to ask?
In general, I usually load the Datatables in the following way:
{% block body %}
...
<div class="row">
<div class="col-12">
<div id="app_provinciaList">
<div class="d-flex justify-content-center">
<div class="spinner-border m-5" role="status">
<span class="sr-only">Cargando...</span>
</div>
</div>
</div>
</div>
</div>
...
{% endblock %}
{% block javascripts %}
{{ parent() }}
<script>
$(function () {
var grillaApp_provincias = $('#app_provinciaList').initDataTables( {{ datatable_settings(datatable) }}, {
searching: true,
}).then(function (dt) {
dt.on('init', function(settings, json) {
$('#dt_filter input').attr("placeholder", "Provincia...");
$('#dt_filter input').width(300);
});
});
});
</script>
{% endblock %}

Flask-WTForms .validate_on_submit() never executes

So basically I want to have a Updateform() form that allows users to update their account details. All my other forms (register, etc.) work perfectly fine but this specific form never validates on submit. Hence when I press the submit button the page just refreshes but the .validate_on_submit() code doesn't execute.
I've looked through the forums and a common issue I found is the .CSRF token missing, but I'm using form.hidden_tag() which I read should work perfectly fine. So it seems that my issue is unique.
I've been looking on the forums for hours but haven't found a solution.
Here is my form code:
class Updateform(FlaskForm):
email = StringField('Email:', validators=[DataRequired(), Email()])
picture = FileField('Update Profile Picture:', validators=[FileAllowed(['jpg', 'png'])])
submit = SubmitField("Update")
def validate_email(self, email):
if email.data != User.email:
if User.query.filter_by(email=email.data).first():
raise ValidationError('Email has already been registered')
Here is the route:
#users.route('/account', methods=['GET', 'POST'])
#login_required
def account():
form = Updateform()
print("hello")
if form.validate_on_submit():
print(form)
print("YES!!!")
name = current_user.name
pic = add_profile_pic(form.picture.data, name)
current_user.profile_image = pic
current_user.email = form.email.data
db.session.commit()
flash("Account Updated")
# elif request.method == "GET":
# form.email = current_user.email
profile_image = url_for('static', filename='profile_pics/'+current_user.profile_image)
return render_template('account.html', profile_image=profile_image, form=form)
And here is the html code:
{% extends "base.html" %}
{% block content %}
<div align="center">
Hi {{ current_user.name }}<br>
<img align="center" src="{{ url_for('static', filename='profile_pics/'+current_user.profile_image) }}">
</div>
<div class="container">
<form method="post">
{{ form.hidden_tag() }}
<div class="form-group">
{{ form.email.label(class='form-group') }}
{{ form.email(class='form-control') }}
</div>
<div class="form-group">
{{ form.picture.label(class='form-group') }}
{{ form.picture(class='form-control') }}
</div>
<div class="form-group">
{{ form.submit() }}
</div>
</form>
</div>
{% endblock %}
The extra classes you see are from the bootstrap library incase anyone is wondering.
Hello you could find out what the problem is by adding a else for you if form.validate_on_submit(): and have it do this
for error in form.email.errors:
print(error)
for error in form.picture.errors:
print(error)
this should tell you what is not working hope this helps and I have not tested this so it could have typos

How can i style my django filter with bootstrap or CSS

i'm new to django here and still learning. So, i created a filter using django-filter and i didn't know how to style it (bootstrap or CSS) because i really don't like the default styling. Can anyone help me with it? i already googled it but didn't find anything useful.
filters.py
`
class CompLink_Filter(django_filters.FilterSet):
start_date = DateFilter(field_name="date_added", label='Date ajout' ,lookup_expr='gte')
company_name = CharFilter(field_name='company_name', label='Nom Entreprise' ,lookup_expr='icontains')
sector = CharFilter(field_name='sector',label='Secteur' , lookup_expr='icontains')
size = CharFilter(field_name='size', label='Taille' ,lookup_expr='icontains')
phone = CharFilter(field_name='phone', label='Téléphone' ,lookup_expr='icontains')
employees_on_linkedin = CharFilter(field_name='employees_on_linkedin', label='Employés sur Linkedin :' ,lookup_expr='icontains')
type = CharFilter(field_name='type', label='Type' ,lookup_expr='icontains')
founded_in = CharFilter(field_name='founded_in', label='Fondée En' ,lookup_expr='icontains')
specializations = CharFilter(field_name='specializations', label='Spécialisations' ,lookup_expr='icontains')
class Meta:
model = Comapny_Profile
fields= '__all__'
exclude= ['company_link','website','head_office','address']`
displaying the filter in my template:
<form class="" action="" method="get">
{% for field in myFilter.form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
<button class="btn btn-primary" type="submit" name="button">Recherche</button>
</form>
You could use jQuery or javascript to manipulate the DOM. When the tags are created you can style it. For example.
$("input").addClass("form-group");

How can I display firebase details in a separate page in Angularfire2

I have a static firebase database which have schema looks below.
This screenshot is a small part of it. There are many cities listed with basic info in my database.
home.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { CityPage} from '../city/city';
import { AngularFire, FirebaseListObservable } from 'angularfire2';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
cityPage = CityPage;
cityinfo: FirebaseListObservable<any>;
constructor(public navCtrl: NavController, af: AngularFire) {
this.cityinfo = af.database.list('/cityinfo');
}
}
I listed firebase items in a grid at home page.
home.html
<div [navPush]="cityPage" class="demo-card-square mdl-card mdl-cell mdl-cell--4-col mdl-cell--4-col-tablet mdl-shadow--2dp" *ngFor="let item of cityinfo | async">
<figure class="mdl-card__media">
<img src="{{ item.image }}" alt="" />
</figure>
{{ item.$key }}
</div>
But my essential problem is;
I want to display city details (summary, geography, population, zipcode, image) information in a separate page ( in city page [ city.html ] ) when I clicked an image in grid at home.html
city.html
<ion-content padding class="recipe">
<p> {{ item.summary }} </p>
<p> {{ item.geography }} </p>
<p> {{ item.population }} </p>
<p> {{ item.zipcode }} </p>
<img src="{{ item.image }}">
</ion-content>
For example, if I click Charlotte city image at home page, I want to display Charlotte city's information in city.html or if I click Raleigh city's picture, I want to display information in city.html
Any help would be appreciated, if someone can help me to success it. I couldn't do that.
Thanks everyone.
You need to pass the city information as a parameter to you city page.
Modify the city figure html to call a function that'll do that, so when you click/tap that image it'll pass the current item of your foreach to the function that'll do the work, like this:
<div [navPush]="cityPage" class="demo-card-square mdl-card mdl-cell mdl-cell--4-col mdl-cell--4-col-tablet mdl-shadow--2dp" *ngFor="let item of cityinfo | async">
<figure class="mdl-card__media" (click)="showCityInfo(item)"> //CAN USE (tap) TOO.
<img src="{{ item.image }}" alt="" />
</figure>
{{ item.$key }}
</div>
In your Home.ts create that function and, using navController, push the city page with the city info.
showCityInfo(item) {
this.navCtrl.push(CityPage, item);
}
in your citypage, grab the city info with navparams and save it in a variable
//IMPORT NAVPARAMS FROM IONIC-ANGULAR
cityInfo: any;
constructor(public navPrms: NavParams){
this.cityInfo = navPrms.data; //here you'll get the data you passed from your home.ts
}
just populate your city.html with your city info
<ion-content padding class="recipe">
<p> {{ cityInfo.summary }} </p>
<p> {{ cityInfo.geography }} </p>
<p> {{ cityInfo.population }} </p>
<p> {{ cityInfo.zipcode }} </p>
<img src="{{ cityInfo.image }}">
</ion-content>
Hope it helps :D

Resources