Search code examples
flaskjinja2

jinja2 and flask issue


{% extends 'base.html' %}
{% block head %}
<title>Task Master</title>
{% endblock %}
{% block body %}
<div class="content">
    <h1>Task Master</h1>
    {% if tasks|length < 1 %}
    <h4 style="text-align: center">There are no tasks. Create one below!</h4>
    {% else %}
    <table class="center">
        <tr>
            <th>Task</th>
            <th>Added</th>
            <th>Action</th>
        </tr>
        {% for task in tasks %}
            <tr>
            <td> {{ task.content }}</td>
            <td> {{ task.date_created.date()}}</td>
            <td>
                <a href="/delete/{{task.id}}">Delete</a>
                <br>
                <a href="/update/{{task.id}}">Update</a>
            </td>
            </tr>
        {% endfor %}
    </table>
    {% endif %}
    <hr width="100%">
    <form action="/" method="post">
        <input type="text" name="content" id="content"></input>
        <input type="submit" value="Add Task"></input>
    </form>
</div>
{% endblock %}

Hello guys i have a problem in my code that if the use doesn't write any task it can be stored as a task even when i am doing an if else statement i don't know if there is any solution


Solution

  • If I understand you correctly, you want to prevent the user from creating a task that has no content.

    To achieve this, it is possible to add a required attribute to the input field for the content. This way, the form will not be sent until the user has made an entry.
    In addition, however, it is also necessary to validate the entries on the server.
    You could output the message using the flash(...) command in Flask.

    Below is an example application in which the user receives a message if they have made an incorrect entry.

    from datetime import datetime
    from flask import (
        Flask, 
        flash, 
        redirect, 
        render_template, 
        request, 
        url_for
    )
    from flask_sqlalchemy import SQLAlchemy
    from sqlalchemy.sql import func 
    from sqlalchemy.orm import DeclarativeBase 
    
    class Base(DeclarativeBase):
        pass
    
    app = Flask(__name__)
    app.config.from_mapping(
        SECRET_KEY='your secret here',
        SQLALCHEMY_DATABASE_URI='sqlite:///example.db'
    )
    db = SQLAlchemy(app, model_class=Base)
    
    class Task(db.Model):
        id: db.Mapped[int] = db.mapped_column(db.Integer, primary_key=True)
        content: db.Mapped[str] = db.mapped_column(db.String(), nullable=False)
        date_created: db.Mapped[datetime] = db.mapped_column(
            db.DateTime(timezone=True), 
            nullable=False, 
            server_default=func.now()
        )
    
    with app.app_context():
        db.drop_all()
        db.create_all()
    
    @app.route('/', methods=['GET', 'POST'])
    def index():
        if request.method == 'POST':
            content = request.form.get('content', '').strip()
            if content: 
                task = Task(content=content)
                db.session.add(task)
                db.session.commit()
                return redirect(url_for('.index'))
            
            flash('Please provide content when creating a task.')
    
        stmt = db.select(Task)
        tasks = db.session.execute(stmt).scalars().all()
    
        return render_template('index.html', **locals())
    
    # ...
    
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Task Master</title>
    </head>
    <body>
        <div class="content">
            <h1>Task Master</h1>
    
            {% with messages = get_flashed_messages(with_categories=true) %}
                {% if messages %}
                <ul>
                    {% for category, message in messages %}
                    <li>{{ message }}</li>
                    {% endfor %}
                </ul>
                {% endif %}
            {% endwith %}
    
            <form method="post">
                <input type="text" name="content" id="content" required />
                <input type="submit" value="Add Task" />
            </form>
            <hr/>
            {% if tasks  %}
            <table class="center">
                <tr>
                    <th>Task</th>
                    <th>Added</th>
                    <!-- ... -->
                </tr>
                {% for task in tasks %}
                <tr>
                    <td> {{ task.content }}</td>
                    <td> {{ task.date_created.date()}}</td>
                    <!-- ... -->
                </tr>
                {% endfor %}
            </table>
            {% else %}
            <h4 style="text-align: center">There are currently no tasks.</h4>
            {% endif %}
        </div>
    </body>
    </html>