Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pynecone CRUD #48

Open
ystekno opened this issue Mar 27, 2023 · 0 comments
Open

Pynecone CRUD #48

ystekno opened this issue Mar 27, 2023 · 0 comments

Comments

@ystekno
Copy link

ystekno commented Mar 27, 2023

It gives many errors in Add/Update/Delete errors. When price is float, set cannot input..

import pynecone as pc
import datetime
from typing import List, Optional
from sqlmodel import Field


class Product(pc.Model, table=True):
    id: int = Field(primary_key=True)
    code: str = None
    names: str
    price: float
    image: str

    def __init__(self, id, code, names, price, image):
        self.id = id
        self.code = code
        self.names = names
        self.price = price
        self.image = image

    def __repr__(self) -> str:
        return "("+self.code+","+self.names+","+self.price+")"

class State(pc.State):
    """The app state."""
    code: str = ""
    names: str = ""
    price: float= 0
    image: str = ""

    async def handle_upload(self, file: pc.UploadFile):
        #pc.window_alert(f"image has been added.")
        upload_data = await file.read()
        outfile = f"assets/product/{file.filename}"

        # Save the file.
        with open(outfile, "wb") as file_object:
            file_object.write(upload_data)

        # Update the img var.
        self.image = file.filename

    def add_product_page(self):
        return pc.redirect("/product/add")

    def add_product(self):
        with pc.session() as session:
            session.add(
                Product(
                    code=self.code,
                    names=self.names,
                    price=self.price,
                    image=self.image,
                )
            )
            session.commit()
        #return pc.window_alert(f"Product {self.names} has been added.")
        return pc.redirect("/product/list")

    producsList: list[Product] = []

    @pc.var
    def get_products(self) -> list[Product]:
        """Get all products from the database."""
        with pc.session() as session:
            self.producsList = session.query(Product).all()
            return self.producsList


    def update_product_page(self, id: int):
        with pc.session() as session:
            product = session.query(Product).filter_by(id=id).first()
            if product:
                self.code = product.code
                self.names = product.names
                self.price = product.price
                self.image = product.image
                pc.input(value=self.code)
                return pc.redirect("/product/update")
            else:
                return pc.window_alert("Product not exists!!!")


    def update_product(self, id: str):
        with pc.session() as session:
            product = session.query(Product).filter_by(id=id).first()
            if product:
                pass
            else:
                return pc.window_alert("Product not exists!!!")

    modal_show: bool = False

    def modal_change(self):
        self.modal_show = not (self.modal_show)

    def delete_product(self, names: str):
        with pc.session() as session:
            session.query(Product).filter_by(names=names).delete()
            session.commit()
            self.modal_change()

def index():
    """The main page."""
    return pc.center(
        pc.vstack(
            pc.text("Home"),
            pc.link(
                "Products",
                href="/product/list",
                color="rgb(107,99,246)",
            )
        ),
    )

def show_products(item: Product):
    """Show a product in a table row."""
    return pc.tr(
        pc.td(item.code),
        pc.td(item.names),
        pc.td(item.price),
        pc.td(pc.image(src=item.image, height="60px"),),
        pc.td(
            pc.button("Update", on_click=lambda: State.update_product_page(item.id)),
        ),
        pc.td(

            pc.button("Delete", on_click=State.modal_change),
            pc.modal(
                pc.modal_overlay(
                    pc.modal_content(
                        pc.modal_header("Confirm"),
                        pc.modal_body(
                            "Do you want to delete product?"
                        ),
                        pc.modal_footer(
                            pc.button(
                                "Delete",
                                on_click=lambda: State.delete_product(item.names),
                                bg="red",
                                color="white",
                            ),
                            pc.button(
                                "Close", on_click=State.modal_change
                            )
                        ),
                    )
                ),
                is_open=State.modal_show,
            ),
        ),
    )

def product_list_page():
    return pc.center(
        pc.vstack(
            #navbar(),
            pc.vstack(
                pc.hstack(
                    pc.heading("Products"),
                    pc.button(pc.icon(tag="add"), on_click=State.add_product_page, bg="#F7FAFC", border="1px solid #ddd"),
                ),
                pc.table_container(
                    pc.table(
                        pc.thead(
                            pc.tr(
                                pc.th("Code"),
                                pc.th("Name"),
                                pc.th("Price"),
                                pc.th("Image"),
                            )
                        ),
                        pc.tbody(pc.foreach(State.get_products, show_products)),
                        variant="striped",
                        #size="100px",
                    ),
                    bg="#F7FAFC ",
                    border="1px solid #ddd",
                ),
                align_items="left",
                padding_top="7em",
            ),

        ),
        padding="1em",
    )


def product_add():
    return pc.center(
        pc.vstack(
            #navbar(),
            pc.heading("Product Add Page"),
            pc.vstack(
                pc.hstack(
                    pc.text("Code:"),
                    pc.input(placeholder="Code", on_blur=State.set_code),
                ),
                pc.hstack(
                    pc.text("Name:"),
                    pc.input(placeholder="Name", on_blur=State.set_names),
                ),
                pc.hstack(
                    pc.text("Price:"),
                    pc.input(placeholder="Price", on_blur=State.set_price),
                ),
                pc.hstack(
                    pc.text("Image:"),
                    #pc.input(placeholder="Image", on_blur=State.set_image),
                    pc.image(src=State.image),
                    pc.upload(
                        pc.button("Select File"),
                        pc.text("Drag and drop files here or click to select files"),
                        border="1px dotted black",
                        on_mouse_out=lambda: State.handle_upload(pc.upload_files())
                        #padding="20em",
                    ),
                )
            ),
            pc.button("Save", on_click=State.add_product),

            #box_shadow="lg",
            #bg="#F7FAFC ",
            padding="1em",
            border="1px solid #ddd",
        ),
        padding_top="3em",
    )


def product_update_page():
    return pc.center(
        pc.vstack(
            #navbar(),
            pc.heading("Product Update Page"),
            pc.vstack(
                pc.hstack(
                    pc.text("Code:"),
                    pc.input(placeholder="Code", value=State.code, on_blur=State.set_code),
                ),
                pc.hstack(
                    pc.text("Name:"),
                    pc.input(placeholder="Name", value=State.names, on_blur=State.set_names),
                ),
                pc.hstack(
                    pc.text("Price:"),
                    pc.input(placeholder="Price", value=State.price, on_blur=State.set_price),
                ),
                pc.hstack(
                    pc.text("Image:"),
                    #pc.input(placeholder="Image", on_blur=State.set_price),
                    pc.image(src=State.image),
                    pc.upload(
                        pc.button("Select File"),
                        pc.text("Drag and drop files here or click to select files"),
                        border="1px dotted black",
                        on_mouse_out=lambda: State.handle_upload(pc.upload_files())
                        #padding="20em",
                    ),
                )
            ),
            pc.button("Save", on_click=State.add_product),

            #box_shadow="lg",
            #bg="#F7FAFC ",
            padding="1em",
            border="1px solid #ddd",
        ),
        padding_top="3em",
    )


# Add state and page to the app.
app = pc.App(state=State)
app.add_page(index)
app.add_page(product_list_page, "/product/list")
app.add_page(product_update_page, "/product/update")
app.compile()

err

@ystekno ystekno changed the title Product list How can we set a value to the input? Apr 5, 2023
@ystekno ystekno changed the title How can we set a value to the input? Pynecone CRUD Apr 9, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant