Python Forum
Creating a website for vehicle management
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Creating a website for vehicle management
#1
Hey people.

I'm doing my final project and i'm having a problem. I'm creating a website and for now i'm dealing with the fact that it does not show what's in the column 'nome_marca' 'nome_categoria' 'nome_tipo' and 'nome_modelo'. These columns are in a database in SQL lite in their respective tables (MarcaVeiculos, CategoriaVeiculos, TipoVeiculos and ModeloVeiculos respectively). Then i have a table named Veiculos where the 'id' column of each table is a foreign key, aggregating the data in that final column (Veiculos). I was only able to make it show the numbers in the 'id_marca' for example or nothing at all.

I would apprecciate your help.

This is the code i have so far:
import flask
from flask import flash
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from werkzeug.security import check_password_hash, generate_password_hash
from datetime import datetime


app = Flask(__name__)
app.config["DEBUG"] = True
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///../database/veiculos.db"
app.config['SECRET_KEY'] = 'random1994'
db = SQLAlchemy(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'

@app.route('/', methods=['GET'])
def home():
    veiculos = Veiculos.query.all()
    return render_template("index.html", veiculos=veiculos)

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password = db.Column(db.String(120), nullable=False)

class MarcaVeiculos(db.Model):
    id_marca = db.Column(db.Integer, primary_key=True)
    nome_marca = db.Column(db.String(255), nullable=False)

class CategoriaVeiculos(db.Model):
    id_categoria = db.Column(db.Integer, primary_key=True)
    nome_categoria = db.Column(db.String(255), nullable=False)

class TipoVeiculos(db.Model):
    id_tipo = db.Column(db.Integer, primary_key=True)
    nome_tipo = db.Column(db.String(255), nullable=False)

class ModeloVeiculos(db.Model):
    id_modelo = db.Column(db.Integer, primary_key=True)
    nome_modelo = db.Column(db.String(255), nullable=False)

class Transmissao(db.Model):
    id_transmissao = db.Column(db.Integer, primary_key=True)
    nome_transmissao = db.Column(db.String(255), nullable=False)

class Veiculos(db.Model):
    id_veiculo = db.Column(db.Integer, primary_key=True)
    id_marca = db.Column(db.Integer, db.ForeignKey('marca_veiculos.id_marca'), nullable=False)
    id_modelo = db.Column(db.Integer, db.ForeignKey('modelo_veiculos.id_modelo'), nullable=False)
    id_categoria = db.Column(db.Integer, db.ForeignKey('categoria_veiculos.id_categoria'), nullable=False)
    id_tipo = db.Column(db.Integer, db.ForeignKey('tipo_veiculos.id_tipo'), nullable=False)
    id_transmissao = db.Column(db.Integer, db.ForeignKey('transmissao.id_transmissao'), nullable=False)
    quantidade_pessoas = db.Column(db.Integer, nullable=False)
    imagem_veiculo = db.Column(db.String(255))
    valor_diario = db.Column(db.Float, nullable=False)
    data_ultima_revisao = db.Column(db.Date)
    data_proxima_revisao = db.Column(db.Date)
    data_ultima_legalizacao = db.Column(db.Date)

    marca = db.relationship('MarcaVeiculos', foreign_keys='Veiculos.id_marca', backref='veiculos', lazy=True)
    modelo = db.relationship('ModeloVeiculos', foreign_keys='Veiculos.id_modelo', backref='veiculos', lazy=True)
    categoria = db.relationship('CategoriaVeiculos', foreign_keys='Veiculos.id_categoria', backref='veiculos', lazy=True)
    tipo = db.relationship('TipoVeiculos', foreign_keys='Veiculos.id_tipo', backref='veiculos', lazy=True)
    transmissao = db.relationship('Transmissao', foreign_keys='Veiculos.id_transmissao', backref='veiculos', lazy=True)


class Reservas(db.Model):
    id_reserva = db.Column(db.Integer, primary_key=True)
    id_cliente = db.Column(db.Integer, db.ForeignKey('usuario.id'), nullable=False)
    id_veiculo = db.Column(db.Integer, db.ForeignKey('veiculos.id_veiculo'), nullable=False)
    data_inicio = db.Column(db.Date, nullable=False)
    data_fim = db.Column(db.Date, nullable=False)
    valor_total = db.Column(db.Float)
    metodo_pagamento = db.Column(db.String(50), nullable=False)

    veiculo = db.relationship('Veiculos', foreign_keys='Reservas.id_veiculo', backref='reservas', lazy=True)



    def calcular_valor_total(self):
        dias_reserva = (self.data_fim - self.data_inicio).days + 1
        veiculo = Veiculos.query.get(self.id_veiculo)
        self.valor_total = dias_reserva * veiculo.valor_diario

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

def obter_marcas():
    marcas = MarcaVeiculos.query.all()
    return marcas

def obter_categorias():
    categorias = CategoriaVeiculos.query.all()
    return categorias

def obter_tipos():
    tipos = TipoVeiculos.query.all()
    return tipos

def obter_modelos():
    modelos = ModeloVeiculos.query.all()
    return modelos

def obter_transmissao():
    transmissao = Transmissao.query.all()
    return transmissao

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        email = request.form['email']
        senha = request.form['senha']
        usuario = User.query.filter_by(email=email).first()
        if usuario and check_password_hash(usuario.password, senha):
            login_user(usuario)
            flash('Login bem-sucedido!', 'success')
            return redirect(url_for('obter_filtros'))
        else:
            flash('Falha no login. Verifique seu email e senha.', 'danger')

    return render_template('login.html')

@app.route('/logout')
@login_required
def logout():
    logout_user()
    flash('Logout bem-sucedido!', 'success')
    return redirect(url_for('obter_filtros'))

@app.route('/filtros', methods=['GET'])
def obter_filtros():
    marcas = obter_marcas()
    categorias = obter_categorias()
    tipos = obter_tipos()
    modelos = obter_modelos()
    transmissao = obter_transmissao()
    return render_template("filtros.html", marcas=marcas, categorias=categorias, tipos=tipos, modelos=modelos,transmissao=transmissao)

@app.route('/reservar', methods=['GET', 'POST'])
@login_required
def reservar():
    if request.method == 'POST':
        data_inicio_str = request.form['data_inicio']
        data_fim_str = request.form['data_fim']
        metodo_pagamento = request.form['metodo_pagamento']

        try:
            data_inicio = datetime.strptime(data_inicio_str, '%Y-%m-%d').date()
            data_fim = datetime.strptime(data_fim_str, '%Y-%m-%d').date()

            reserva = Reservas(
                id_cliente=current_user.id,
                id_veiculo=1,
                data_inicio=data_inicio,
                data_fim=data_fim,
                valor_total=0,
                metodo_pagamento=metodo_pagamento
            )

            reserva.calcular_valor_total()
            db.session.add(reserva)
            db.session.commit()

            flash('Reserva bem-sucedida!', 'success')
            return redirect(url_for('minhas_reservas'))

        except ValueError:
            flash('Erro: Data inválida. Certifique-se de usar o formato YYYY-MM-DD.', 'danger')

    return render_template('reservation.html')

@app.route('/minhas_reservas')
@login_required
def minhas_reservas():
    reservas = Reservas.query.filter_by(id_cliente=current_user.id).all()
    return render_template('minhas_reservas.html', reservas=reservas)

if __name__ == "__main__":
    with app.app_context():
        db.create_all()
    app.run()
I also have this in my index.html file:
Output:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>App de Gestão de Frota</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/slate/bootstrap.min.css"> <link href="https://fonts.googleapis.com/css2?family=Merriweather:ital,wght@1,900&display=swap" rel="stylesheet"> <link rel="stylesheet" href="{{ url_for('static', filename='main.css') }}"> </head> <body> <main class="container p-4"> <h1 class="display-4 text-center mt-4 titulo">App de Gestão de Frota</h1> <form> <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email"> <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> </div> <div class="form-group"> <label for="exampleInputPassword1">Password</label> <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password"> </div> <div class="form-check"> <input type="checkbox" class="form-check-input" id="exampleCheck1"> <label class="form-check-label" for="exampleCheck1">Keep me in</label> </div> <button type="submit" class="btn btn-primary">Login</button> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#signupModal">Sign up</button> </form> <hr> <div class="mt-5"> <h2>Informações sobre Veículos</h2> {% for veiculo in veiculos %} <div class="card mt-3"> <div class="card-body"> <h5 class="card-title">{{ veiculo.modelo.nome_modelo }}</h5> <p class="card-text">Marca: {{ veiculo.marca.nome_marca }}</p> <p class="card-text">Modelo: {{ veiculo.modelo.nome_modelo }}</p> <p class="card-text">Categoria: {{ veiculo.categoria.nome_categoria }}</p> <p class="card-text">Tipo: {{ veiculo.tipo.nome_tipo }}</p> <p class="card-text">Transmissão: {{ veiculo.transmissao.nome_transmissao }}</p> <p class="card-text">Capacidade: {{ veiculo.quantidade_pessoas }} pessoas</p> <p class="card-text">Preço Diário: €{{ veiculo.valor_diario }}</p> <p class="card-text">Última Revisão: {{ veiculo.data_ultima_revisao }}</p> <p class="card-text">Próxima Revisão: {{ veiculo.data_proxima_revisao }}</p> <p class="card-text">Última Legalização: {{ veiculo.data_ultima_legalizacao }}</p> <a href="{{ veiculo.imagem_veiculo }}" target="_blank">Imagem do Veículo</a> </div> </div> {% endfor %} </div> <div class="mt-5"> <h2>Informações sobre Reservas</h2> {% for reserva in reservas %} <div class="card mt-3"> <div class="card-body"> <h5 class="card-title">Reserva #{{ reserva.id_reserva }}</h5> <p class="card-text">Veículo: {{ reserva.veiculo.modelo.nome_modelo }}</p> <p class="card-text">Data de Início: {{ reserva.data_inicio }}</p> <p class="card-text">Data de Fim: {{ reserva.data_fim }}</p> <p class="card-text">Método de Pagamento: {{ reserva.metodo_pagamento }}</p> <p class="card-text">Valor Total: €{{ reserva.valor_total }}</p> </div> </div> {% endfor %} </div> </main> <div class="modal fade" id="signupModal" tabindex="-1" role="dialog" aria-labelledby="signupModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="signupModalLabel">Cadastro de Usuário</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Sign Up</button> </div> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-wD0GXG4lDU3N4uzA+b/QD1eEoU8hKVbE1/zy6EMbfIktO5qih5p+F86pCeHBu1L1" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8sh+Wy6fFE00uKT92QmMlHGz6p8Q9vljj1z9wD" crossorigin="anonymous"></script> </body> </html>
Gribouillis write Feb-11-2024, 07:22 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
Do you know phpMyAdmin?

phpMyAdmin is a programme for interacting with your database. phpMyAdmin runs in your web-browser and connects you with your database. The standard listening port for MySQL is 3306.

You can get phpMyAdmin here.

Then you can open your database, check it, make sure the data you want is actually in the database, try out the SQL queries you want to use, make sure they work, then try to implement them in Python.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Inventory Management Optimization problem Mini_Miudo 1 3,142 Dec-13-2018, 07:49 PM
Last Post: Mini_Miudo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020