<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: AricayaJohn</title>
    <description>The latest articles on Forem by AricayaJohn (@aricayajohn).</description>
    <link>https://forem.com/aricayajohn</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1415459%2F86ff5f97-ccea-4c8d-a2a0-f0e3e0b6504f.png</url>
      <title>Forem: AricayaJohn</title>
      <link>https://forem.com/aricayajohn</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/aricayajohn"/>
    <language>en</language>
    <item>
      <title>Flask-Login for Class Management Application</title>
      <dc:creator>AricayaJohn</dc:creator>
      <pubDate>Sun, 23 Mar 2025 05:36:59 +0000</pubDate>
      <link>https://forem.com/aricayajohn/flask-login-for-class-management-application-d4m</link>
      <guid>https://forem.com/aricayajohn/flask-login-for-class-management-application-d4m</guid>
      <description>&lt;p&gt;In this blog, we’ll explain flask Login with examples from a Class Management System Application. &lt;/p&gt;

&lt;p&gt;We’ll explore how Flask-Login works, how to integrate it with a React frontend, and how to secure your application. &lt;/p&gt;

&lt;p&gt;By the end, you’ll have an idea of the concept of functional system where a professors can log in, and bring them to a dashboard page where they can manage semesters, classes, and students, and securely log out.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is Flask-Login?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Flask-Login is a Flask extension that simplifies user authentication. &lt;/p&gt;

&lt;p&gt;It handles:&lt;/p&gt;

&lt;p&gt;User sessions: Keeping users logged in across requests.&lt;br&gt;
Access control: Protecting routes from unauthorized access.&lt;br&gt;
User loading: Fetching user data from the database based on session information.&lt;br&gt;
Remember me: Persisting user sessions across browser restarts.&lt;br&gt;
Flask-Login doesn’t handle password hashing or database management directly. Instead, it integrates seamlessly with other libraries like bcrypt for password hashing and SQLAlchemy for database interactions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Core Components in My Code&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Create a model for user
-&amp;gt; Professor model:  It represents a professor in the database and includes methods required by Flask-Login.
&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Professor(db.Model, SerializerMixin):
    __tablename__ = "professors"
    serialize_rules = ('-_password_hash', '-semesters.professor',) 

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String, nullable=False, unique=True)
    name = db.Column(db.String, nullable=False)
    department = db.Column(db.String, nullable=False)
    office_location = db.Column(db.String, nullable=True)
    _password_hash = db.Column(db.String, nullable=False)

    semesters = db.relationship('Semester', back_populates='professor', cascade='all, delete-orphan')

    def get_id(self):
        return str(self.id)

    @property
    def is_authenticated(self):
        return True

    @property
    def is_active(self):
        return True

    @property
    def is_anonymous(self):
        return False

    @hybrid_property
    def password_hash(self):
        raise Exception('Password hashes may not be viewed')

    @password_hash.setter
    def password_hash(self, password):
        if len(password) &amp;lt; 5:
            raise ValueError("Password should be 5 characters or longer")
        self._password_hash = bcrypt.generate_password_hash(password.encode('utf-8')).decode('utf-8')

    def authenticate(self, password):
        return bcrypt.check_password_hash(self._password_hash, password.encode('utf-8'))

    @validates('username')
    def validate_username(self, key, username):
        if not username or not isinstance(username, str):
            raise ValueError('Username should be a string')
        if len(username) &amp;lt; 3:
            raise ValueError('Username should be at 3 characters or more')
        return username

    @validates('name')
    def validate_name(self, key, name):
        if not name or not isinstance(name, str):
            raise ValueError('Name must be a string')
        return name

    @validates('department')
    def validate_department(self, key, department):
        if not department or not isinstance(department, str):
            raise ValueError('Department must be a non-empty string.')
        return department

    @validates('office_location')
    def validate_office_location(self, key, office_location):
        if office_location and not isinstance(office_location, str):
            raise ValueError('Office location should be a string.')
        return office_location

    def to_dict(self, rules=()):
        professor_dict = {
            "id": self.id,
            "username": self.username,
            "name": self.name,
            "department": self.department,
            "office_location": self.office_location,
            "semesters": [semester.to_dict() for semester in self.semesters]
        }
        for rule in rules:
            if rule in professor_dict:
                del professor_dict[rule]
        return professor_dict

    def __repr__(self):
        return f'&amp;lt;Professor ID: {self.id} | Username: {self.username} | Name: {self.name}&amp;gt;'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Key Features:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;get_id(): Flask-Login uses this method to identify the user. It must return a unique identifier (e.g., the user’s ID).&lt;/li&gt;
&lt;li&gt;is_authenticated: This property checks if the user is logged in. It’s used by Flask-Login to determine if a user can access protected routes.&lt;/li&gt;
&lt;li&gt;is_active: This property checks if the user account is active. For example, you could deactivate accounts without deleting them.&lt;/li&gt;
&lt;li&gt;is_anonymous: This property checks if the user is anonymous (not logged in).&lt;/li&gt;
&lt;li&gt;Password Handling:&lt;/li&gt;
&lt;li&gt;The password_hash setter hashes the password using bcrypt.&lt;/li&gt;
&lt;li&gt;The authenticate method compares a provided password with the stored hash.&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;Create a backend user loader in config.py
The user loader is a callback function that Flask-Login uses to reload a user from their session ID.
&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@login_manager.user_loader
def load_user(professor_id):
    return db.session.get(Professor, int(professor_id))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;What it Does:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;When a user logs in, Flask-Login stores their ID in the session cookie.&lt;/li&gt;
&lt;li&gt;On subsequent requests, Flask-Login calls load_user to reload the user from the database using the stored ID.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;2.1 Add Security figure in config.py&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.config['SESSION_COOKIE_SECURE'] = True  # HTTPS only
app.config['SECRET_KEY'] = 'your-secret-key'  # Encrypts cookies
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Password Security&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;bcrypt hashes passwords before storage
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;self._password_hash = bcrypt.generate_password_hash(password).decode('utf-8')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Plain passwords never stored in the database&lt;/li&gt;
&lt;li&gt;authenticate() method compares hashes
 Authentication: Passwords are verified using bcrypt.check_password_hash().&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;Create a Login/Logout Route(Backend) 
-&amp;gt;Make sure to include the resource in the app.py file
-&amp;gt;The Login and Logout routes handle user authentication and session management.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Login(Resource):
    def post(self):
        professor = Professor.query.filter_by(username=username).first()
        if professor.authenticate(password):
            login_user(professor)  # Flask-Login magic!
            return current_user.to_dict()

class Logout(Resource):
    @login_required
    def post(self):
        logout_user()  # Ends the session
        return {'message': 'Logged out!'}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;How it Works:&lt;/p&gt;

&lt;p&gt;Login:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The frontend sends a username and password.&lt;/li&gt;
&lt;li&gt;The backend verifies the credentials using the authenticate method.&lt;/li&gt;
&lt;li&gt;If valid, login_user() starts a session and stores the user’s ID in a secure cookie.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Logout:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;logout_user() clears the session cookie, effectively logging the user out.&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;Protected Routes
You can protect routes using the @login_required decorator.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Semesters(Resource):
    @login_required
    def get(self):
        return Semester.query.filter_by(professor_id=current_user.id).all()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What Happens:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If a user tries to access a protected route without logging in, Flask-Login redirects them to the login page.&lt;/li&gt;
&lt;li&gt;current_user is a proxy for the logged-in user, accessible in all routes.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;*&lt;em&gt;Integrating in frontEnd (React Context) *&lt;/em&gt;&lt;br&gt;
-&amp;gt; Create a global state file useContext that include login fetch request to the back end&lt;br&gt;
-&amp;gt; The frontend uses React Context to manage the authenticated user’s state.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// UserContext.js
const UserContext = createContext();

function UserProvider({ children }) {
  const [user, setUser] = useState(null);

  // Auto-login on page load
  useEffect(() =&amp;gt; {
    fetch("/check_session")
      .then(res =&amp;gt; res.json())
      .then(data =&amp;gt; setUser(data));
  }, []);

  // Login function
  const login = (credentials) =&amp;gt; {
    fetch("/login", { method: "POST", body: JSON.stringify(credentials) })
      .then(() =&amp;gt; fetch("/check_session"))
      .then(res =&amp;gt; setUser(res.json()));
  };

  // Logout function
  const logout = () =&amp;gt; {
    fetch("/logout", { method: "POST" })
      .then(() =&amp;gt; setUser(null));
  };
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Key Flows:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Auto-Login: On page load, the app checks if the user is already logged in by calling /check_session.&lt;/li&gt;
&lt;li&gt;Persistent Login: The user’s data is stored in React state and shared across components via context.&lt;/li&gt;
&lt;li&gt;Protected Components: Use the user state to conditionally render UI elements.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;WorkFlow:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;1) Signup&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A professor creates an account.&lt;/li&gt;
&lt;li&gt;The password is hashed and stored in the database.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;2)Login&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Frontend: The professor logs in with their username and password.&lt;/li&gt;
&lt;li&gt;Backend: verifies credentials, starts session&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;3)Access Control&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Protected routes use @login_required&lt;/li&gt;
&lt;li&gt;Protected routes (e.g., managing semesters) are only accessible to logged-in users.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;4)Access Control:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Protected routes (e.g., managing semesters) are only accessible to logged-in users.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;5)Logout&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The session is destroyed, and the user is logged out.&lt;/li&gt;
&lt;li&gt;Client-side user state cleared&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Flask-Login manages user authentication, especially when paired with secure password handling via bcrypt and frontend integration. With proper setup, your application can efficiently handle signup, login, logout, and session management while maintaining a level of security.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>python</category>
      <category>programming</category>
    </item>
    <item>
      <title>RESTful API in Flask: Resources and CRUD Operations through Conventions Project</title>
      <dc:creator>AricayaJohn</dc:creator>
      <pubDate>Tue, 28 Jan 2025 20:47:07 +0000</pubDate>
      <link>https://forem.com/aricayajohn/restful-api-in-flask-resources-and-crud-operations-through-conventions-project-5gfk</link>
      <guid>https://forem.com/aricayajohn/restful-api-in-flask-resources-and-crud-operations-through-conventions-project-5gfk</guid>
      <description>&lt;p&gt;What is RESTful API?&lt;br&gt;
  Representational State Transfer that allows clients to interact with a server by performing HTTP operation (GET, POST, PATCH, DELETE) on resources. &lt;/p&gt;

&lt;p&gt;In our project our resources are Convention Areas, Conventions, Host companies.&lt;/p&gt;

&lt;p&gt;In our project we create and define the models for the resources so that we can have a database that will be the foundation of our API resources.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class ConventionArea(db.Model, SerializerMixin):
    __tablename__ = 'convention_areas'

    id = db.Column(db.Integer, primary_key=True)
    location_name = db.Column(db.String, nullable=False)
    venue = db.Column(db.String, nullable=False)

    conventions = db.relationship('Convention', backref='convention_area', cascade='all, delete-orphan')
    host_companies = association_proxy('conventions', 'host_company')

    serialize_rules = ('-conventions.convention_area',)

class HostCompany(db.Model, SerializerMixin):
    __tablename__ = 'host_companies'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False)
    industry = db.Column(db.String, nullable=False)

    conventions = db.relationship('Convention', backref='host_company')
    convention_names = association_proxy('conventions', 'convention_name')

    serialize_rules = ('-conventions.host_company',)

    @validates('name')
    def validate_name(self, key, name):
        if not name:
            raise ValueError('HostCompany name cannot be empty')
        return name

    @validates('industry')
    def validate_industry(self, key, industry):
        if not industry:
            raise ValueError('Industry cannot be empty')
        return industry

class Convention(db.Model, SerializerMixin):
    __tablename__ = 'conventions'

    id = db.Column(db.Integer, primary_key=True)
    convention_name = db.Column(db.String, nullable=False)
    days = db.Column(db.Integer, nullable=False)

    convention_area_id = db.Column(db.Integer, db.ForeignKey('convention_areas.id'))
    host_company_id = db.Column(db.Integer, db.ForeignKey('host_companies.id'))

    serialize_rules = ('-convention_area.conventions', '-host_company.conventions')

    host_company = association_proxy('host_company_id', 'host_company')

    @validates('days')
    def validate_days(self, key, days):
        if not isinstance(days, int):
            raise ValueError('Days must be an integer')
        return days
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The key component for our Resource Code are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;CRUD Operations: Each resource class implements methods for Create, Read, Update, Delete operations.&lt;/li&gt;
&lt;li&gt;Endpoints: This defines the routes and the corresponding resource classes&lt;/li&gt;
&lt;li&gt;Serialization: Convert database objects to JSON format using the  to_dict method&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Here is the breakdown of each resource:&lt;br&gt;
ConventionAreas Resource:&lt;br&gt;
     -&amp;gt; This class manages the convention areas and the places where the conventions are being held&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class ConventionAreas(Resource):
    def get(self):
        areas = ConventionArea.query.all()
        return [area.to_dict(only=('id', 'location_name', 'venue')) for area in areas]

    def post(self):
        data = request.get_json()
        try:
            new_area = ConventionArea(
                location_name=data['location_name'],
                venue=data['venue']
            )
            db.session.add(new_area)
            db.session.commit()
            return make_response(new_area.to_dict(), 200)
        except ValueError as e:
            print('Error', e)
            return make_response({'errors': ['validation errors']}, 400)

api.add_resource(ConventionAreas, '/convention_areas')

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;GET: Retrieves all convention areas from the database and returns a list of dictionaries&lt;br&gt;
    -Process: &lt;br&gt;
        &amp;gt;Query the database to get all convention areas.&lt;br&gt;
        &amp;gt;Convert each convention area to a dictionary format(to_dict)&lt;br&gt;
        &amp;gt;Return the list of convention areas as JSON&lt;br&gt;
POST: Creates a new convention area from the provided JSON data and saves it to the database&lt;br&gt;
    -Process:&lt;br&gt;
        &amp;gt;Retrieve the JSON data from the request&lt;br&gt;
        &amp;gt;Create a new ConventionArea object using the data&lt;br&gt;
        &amp;gt;Add the new object to the database and commit the transaction&lt;br&gt;
        &amp;gt;Return the new convention area as JSON&lt;/p&gt;

&lt;p&gt;ConventionAreasById Resource:&lt;br&gt;
    -&amp;gt; this handle request for specific convention areas, we need to use this resource to to get the id parameter of the ConventionAreas.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class ConventionAreasById(Resource):
    def get(self, id):
        area = db.session.get(ConventionArea, id)
        if area:
            return area.to_dict(), 200
        return {'error': 'ConventionArea not found'}, 404

    def patch(self, id):
        area = ConventionArea.query.filter_by(id=id).first()
        if area:
            try:
                data = request.get_json()
                for attr, value in data.items():
                    setattr(area, attr, value)
                db.session.add(area)
                db.session.commit()
                return make_response(area.to_dict(), 202)
            except ValueError:
                return make_response({'errors': ['validation errors']}, 400)
        else:
            return make_response(jsonify({'error': 'ConventionArea not found'}), 404)

    def delete(self, id):
        area = db.session.get(ConventionArea, id)
        if area:
            db.session.delete(area)
            db.session.commit()
            return '', 204
        return {'error': 'ConventionArea not found'}, 404

api.add_resource(ConventionAreasById, '/convention_areas/&amp;lt;int:id&amp;gt;')

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;GET: Fetches a specific convention area by its ID.&lt;br&gt;
    -Process:&lt;br&gt;
        &amp;gt;Query the database to get the convention area by ID&lt;br&gt;
        &amp;gt;Return the convention area as JSON&lt;/p&gt;

&lt;p&gt;PATCH: Updates an existing convention area.&lt;br&gt;
    -Process:&lt;br&gt;
        &amp;gt;Retrieve the JSON data from the request&lt;br&gt;
        &amp;gt;Update the convention area with the new data&lt;br&gt;
        &amp;gt;Commmit the changes to the database&lt;br&gt;
        &amp;gt;Return the updated convention area as JSON&lt;br&gt;
DELETE: Deletes a convention area by its ID.&lt;br&gt;
    -Process:&lt;br&gt;
        &amp;gt;Query the database to get the convention area by Id&lt;br&gt;
        &amp;gt;Delete the convention area from the database&lt;br&gt;
        &amp;gt;Commit the changes&lt;/p&gt;

&lt;p&gt;Hosts Resource:&lt;br&gt;
    -&amp;gt; This resource manages the companies that host conventions&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Hosts(Resource):
    def get(self):
        convention_id = request.args.get('convention_id', type=int)
        if (convention_id):
            conventions = Convention.query.filter_by(id=convention_id).all()
            hosts = [convention.host_company for convention in conventions if convention.host_company is not None]
        else:
            hosts = HostCompany.query.all()
        return [host.to_dict(only=('id', 'name', 'industry')) for host in hosts]

    def post(self):
        data = request.get_json()
        try:
            new_host = HostCompany(
                name=data['name'],
                industry=data['industry']
            )
            db.session.add(new_host)
            db.session.commit()

            convention = Convention.query.get(data['convention_id'])
            if (convention):
                convention.host_company_id = new_host.id
                db.session.commit()

            return make_response(new_host.to_dict(), 201)
        except ValueError:
            return make_response({'errors': ['validation errors']}, 400)

api.add_resource(Hosts, '/hosts')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;GET: Retrieves host companies, filtered by convention ID if provided&lt;br&gt;
    -Process:&lt;br&gt;
        &amp;gt;Check if a convention_id is provided&lt;br&gt;
        &amp;gt;Query the database for host companies associated with the convention&lt;br&gt;
        &amp;gt;Return the list of host companies as JSON&lt;/p&gt;

&lt;p&gt;POST: Creates a new host company and associates it with a convention&lt;br&gt;
    -Process:&lt;br&gt;
        &amp;gt;Retrieve JSON data from the request&lt;br&gt;
        &amp;gt;Create a new HostCompany object using the data&lt;br&gt;
        &amp;gt;Add the new object to the database and commit the transaction&lt;br&gt;
        &amp;gt;Link the new host to a convention&lt;br&gt;
        &amp;gt;Return the new host company as JSON&lt;/p&gt;

&lt;p&gt;HostCompaniesById Resource:&lt;br&gt;
    -&amp;gt; This manages the individual host companies&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    def get(self, id):
        host = db.session.get(HostCompany, id)
        if host:
            return host.to_dict(), 200
        return {'error': 'HostCompany not found'}, 404

    def patch(self, id):
        host = HostCompany.query.filter_by(id=id).first()
        if host:
            try:
                data = request.get_json()
                for attr in data:
                    setattr(host, attr, data[attr])
                db.session.add(host)
                db.session.commit()
                return make_response(host.to_dict(), 202)
            except ValueError:
                return make_response({'errors': ['validation errors']}, 400)
        else:
            return make_response(jsonify({'error': 'HostCompany not found'}), 404)

    def delete(self, id):
        host = db.session.get(HostCompany, id)
        if host:
            db.session.delete(host)
            db.session.commit()
            return '', 204
        return {'error': 'HostCompany not found'}, 404

api.add_resource(HostCompaniesById, '/hosts/&amp;lt;int:id&amp;gt;')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;GET:Retrieves the specific host company by its ID&lt;br&gt;
    -Process:&lt;br&gt;
        &amp;gt;Query the database to get host company by ID&lt;br&gt;
        &amp;gt;Return the host company as JSON&lt;br&gt;
PATCH:Updates a specific host company&lt;br&gt;
    -Process:&lt;br&gt;
        &amp;gt;Retrieve JSON data from the request&lt;br&gt;
        &amp;gt;Update the host company with the new data&lt;br&gt;
        &amp;gt;Commit the changes to the database&lt;br&gt;
        &amp;gt;Return the updated host company as JSON&lt;br&gt;
DELETE:Deletes a specific host company by its ID&lt;br&gt;
    -Process:&lt;br&gt;
        &amp;gt;Query the database to get host company by ID.&lt;br&gt;
        &amp;gt;Delete the host company from the database&lt;br&gt;
        &amp;gt;Commit the changes.&lt;/p&gt;

&lt;p&gt;Convention Resource:&lt;br&gt;
    -&amp;gt; This resource allows us to manage conventions, including the assosciation with specific convention areas and hosts&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Conventions(Resource):
    def get(self):
        convention_area_id = request.args.get('convention_area_id', type=int)
        if convention_area_id:
            conventions = Convention.query.filter_by(convention_area_id=convention_area_id).all()
        else:
            conventions = Convention.query.all()
        return [convention.to_dict(only=('id', 'convention_name', 'days', 'convention_area_id', 'host_company_id')) for convention in conventions]

    def post(self):
        data = request.get_json()
        try:
            new_convention = Convention(
                convention_name=data['convention_name'],
                days=data['days'],
                convention_area_id=data['convention_area_id'],
                host_company_id=data.get('host_company_id')
            )
            db.session.add(new_convention)
            db.session.commit()
            return make_response(new_convention.to_dict(), 201)
        except ValueError as e:
            print('Error', e)
            return make_response({'errors': ['validation errors']}, 400)

api.add_resource(Conventions, '/conventions')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;GET: Retrieves all conventions with the option to be filtered by convention areas.&lt;br&gt;
    -Process:&lt;br&gt;
        &amp;gt;Check if a convention_area_id is provided&lt;br&gt;
        &amp;gt;Query the database for conventions associated with the convention area&lt;br&gt;
        &amp;gt;Return the list of convention as JSON&lt;/p&gt;

&lt;p&gt;POST: Creates a new convention and association it with a host company and convention area. &lt;br&gt;
    -Process:&lt;br&gt;
        &amp;gt;Retrieve JSON data from the request&lt;br&gt;
        &amp;gt;Create a new Convention object using the data&lt;br&gt;
        &amp;gt;Add the new object to the database and commit the transaction&lt;br&gt;
        &amp;gt;Return the new convention as JSON&lt;/p&gt;

&lt;p&gt;ConventionById Resource:&lt;br&gt;
    -&amp;gt; To manage individual conventions&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class ConventionsById(Resource):
    def get(self, id):
        convention = db.session.get(Convention, id)
        if convention:
            return convention.to_dict(), 200
        return {'error': 'Convention not found'}, 404

    def patch(self, id):
        convention = Convention.query.filter_by(id=id).first()
        if convention:
            try:
                data = request.get_json()
                for attr in data:
                    setattr(convention, attr, data[attr])
                db.session.add(convention)
                db.session.commit()
                return make_response(convention.to_dict(), 202)
            except ValueError:
                return make_response({'errors': ['validation errors']}, 400)
        else:
            return make_response(jsonify({'error': 'Convention not found'}), 404)

    def delete(self, id):
        convention = db.session.get(Convention, id)
        if convention:
            db.session.delete(convention)
            db.session.commit()
            return '', 204
        return {'error': 'Convention not found'}, 404

api.add_resource(ConventionsById, '/conventions/&amp;lt;int:id&amp;gt;')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;GET :Retrieves a specific convention by its ID&lt;br&gt;
    -Process:&lt;br&gt;
        &amp;gt;Query the database to get the convention by ID.&lt;br&gt;
        &amp;gt;Return the convention as JSON&lt;br&gt;
PATCH: Updates the specific convention&lt;br&gt;
    -Process:&lt;br&gt;
        &amp;gt;Retrieve the JSON data from the request&lt;br&gt;
        &amp;gt;Update the convention with the new data&lt;br&gt;
        &amp;gt;Commit the changes to the database&lt;br&gt;
        &amp;gt;Return the updated convention as JSON&lt;br&gt;
DELETE: Deletes a specific convention by its ID&lt;br&gt;
    -Process:&lt;br&gt;
        &amp;gt;Query the database to get the convention by ID.&lt;br&gt;
        &amp;gt;Delete the convention from the database&lt;br&gt;
        &amp;gt;Commit the changes&lt;/p&gt;

&lt;p&gt;Conclusion:&lt;/p&gt;

&lt;p&gt;Building a RESTful API can be great for managing resources within a system. To ensure your code is both flexible and maintainable, it's crucial to structure it thoughtfully. By defining clear models, implementing CRUD operations, and utilizing serialization, we can effectively handle complex relationships between elements in a many to many relation ship system. This structured approach simplifies the process and helps it to be scallable.&lt;/p&gt;

</description>
      <category>api</category>
      <category>flask</category>
      <category>devops</category>
    </item>
    <item>
      <title>React for Modern WebDevelopment: Trends and Best Practices</title>
      <dc:creator>AricayaJohn</dc:creator>
      <pubDate>Tue, 30 Jul 2024 10:29:12 +0000</pubDate>
      <link>https://forem.com/aricayajohn/react-for-modern-webdevelopment-trends-and-best-practices-352k</link>
      <guid>https://forem.com/aricayajohn/react-for-modern-webdevelopment-trends-and-best-practices-352k</guid>
      <description>&lt;p&gt;In today's fast-paced world, staying informed about industry trends and innovative tools can be beneficial to someone's success. With React's powerful features and growing capabilities, we will see a rise on usage of the React Library among future developers. Today, We will discuss the three Best Practices/Trends that React Developers are adopting, using examples from my Software Management Tracker Project. &lt;/p&gt;

&lt;p&gt;After reading this article, you will gain insights into Component-Based Architecture, State Management + Data Fetching, and lastly Routing and Navigation. If you want to check out more about my code, feel free to fork my repo at [(&lt;a href="https://github.com/AricayaJohn/ProjectManagement_ReactApplication)" rel="noopener noreferrer"&gt;https://github.com/AricayaJohn/ProjectManagement_ReactApplication)&lt;/a&gt;].&lt;/p&gt;

&lt;p&gt;We will start with &lt;strong&gt;Component-Based Architecture&lt;/strong&gt; :&lt;br&gt;
  Developers are moving towards component-based style of coding because of the benefits that it provide:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;It is designed to create reusable pieces for your app giving you the power to use that code again, saving you time and effort.&lt;/li&gt;
&lt;li&gt;Each component works on its own, which means that fixing or updating one part of the application does not disrupt the whole structure of your project.&lt;/li&gt;
&lt;li&gt;Easier Testing and Scalability. With pieces broken into different parts anyone can work on different parts of the project without having any conflicts with other team members work. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Example: The App component displays routes &lt;br&gt;
to different pages. It integrates multiple components in one page.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react";
import { Routes, Route } from "react-router-dom";
import Home from "./pages/Home";
import About from "./pages/About";
import Login from "./pages/Login";
import EmploeeTask from "./pages/EmployeeTask";

function App() {
    return (
        &amp;lt;Routes&amp;gt;
            &amp;lt;Route path="/" element={&amp;lt;Home /&amp;gt;} /&amp;gt;
            &amp;lt;Route path="/about" element={&amp;lt;About /&amp;gt;} /&amp;gt;
            &amp;lt;Route path="/login" element={&amp;lt;Login /&amp;gt;} /&amp;gt;
            &amp;lt;Route path="/employee-task/:id" element = {&amp;lt;EmploeeTask /&amp;gt;} /&amp;gt;
        &amp;lt;/Routes&amp;gt;
    );
}

export default App;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The next topic we are going to expore is &lt;strong&gt;State Management + Data Fetching&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This trend is crucial when we take our application to the next level. This needs React's &lt;code&gt;useState and&lt;/code&gt;useEffect` hooks that helps us simplify changes in our application and data. &lt;br&gt;
Here is the benefits of this proccess:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;useState&lt;/code&gt; helps you keep track of changes in your forms, buttons and other onChange features.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;useEffect&lt;/code&gt; lets you run and get data from your document file which is the API(application programming interface).&lt;/li&gt;
&lt;li&gt;By using state and effects in your components, React can help a smoother and better user experience for your users.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Here is an example from my project that uses &lt;code&gt;useState&lt;/code&gt; and &lt;code&gt;useEffect&lt;/code&gt;: &lt;br&gt;
In the function the &lt;code&gt;useState&lt;/code&gt; updates the state of the employees when needed. &lt;br&gt;
In the function the &lt;code&gt;useEffect&lt;/code&gt; fetches/gets the employees data from the server and gives a response.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fz6z6qc1i6gwio9oe7dvf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fz6z6qc1i6gwio9oe7dvf.png" alt="Image description" width="800" height="838"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the home Component, by using the &lt;code&gt;useState&lt;/code&gt; and &lt;code&gt;useEffect&lt;/code&gt; we are given the capability to display our data, change our data, and add more to our data. &lt;/p&gt;

&lt;p&gt;The last Trend and Best Practice that we will discuss is the &lt;strong&gt;Routing and Navigation.&lt;/strong&gt;&lt;br&gt;
 In my project I used a Single Page Application(SPAs) because of this benefits:&lt;br&gt;
1) This functionality makes the transition between different pages quick and easy, without reloading the page. &lt;br&gt;
2)Clear URLs helps create and manage userfriendly navigation for users &lt;br&gt;
3) I was able to organize the structure of the nested routes or multiple routes. This keeps related pages together and easier to understand.&lt;/p&gt;

&lt;p&gt;Here is an example of &lt;strong&gt;Routing and Navigation&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffcmae9mmc3sq48le63lb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffcmae9mmc3sq48le63lb.png" alt="Image description" width="800" height="748"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;These syntax imports the React Components that will be used as different pages in the application. Each object specifies the path to which component will be displayed when clicked or visited. This setup allows the application to handle navigation without reloading the entire page. This also organized the different parts on how it will be displayed on the URL.&lt;/p&gt;

&lt;p&gt;These practices: component-based architecture, effective state management + data fetching, and efficient routing + navigation, are key to building complex and user-friendly React application. &lt;/p&gt;

&lt;p&gt;For more details, check out my github :[(&lt;a href="https://github.com/AricayaJohn)" rel="noopener noreferrer"&gt;https://github.com/AricayaJohn)&lt;/a&gt;]&lt;br&gt;
and Linkedin [(&lt;a href="https://www.linkedin.com/in/john-aricaya/)" rel="noopener noreferrer"&gt;https://www.linkedin.com/in/john-aricaya/)&lt;/a&gt;]&lt;/p&gt;

</description>
      <category>react</category>
      <category>webdev</category>
      <category>beginners</category>
      <category>javascript</category>
    </item>
    <item>
      <title>React Components Basic 101</title>
      <dc:creator>AricayaJohn</dc:creator>
      <pubDate>Mon, 03 Jun 2024 04:13:41 +0000</pubDate>
      <link>https://forem.com/aricayajohn/react-components-basic-101-5fe7</link>
      <guid>https://forem.com/aricayajohn/react-components-basic-101-5fe7</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;The Building Blocks Of Modern Web Application&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;What is a React Component:&lt;/strong&gt;&lt;br&gt;
-Components are part of React, which is a JavaScript Library used to build web interface.&lt;br&gt;
-They are written in JSX, a syntax extension that combines JS and HTML making it more readable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Analogy&lt;/strong&gt;&lt;br&gt;
Imagine codes inside LEGO blocks that, when pieced together, forms a web page application. Each webpage is broken up into pieces of smaller User Interface. By combining these blocks, you build complex and dynamic web pages.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why is it important:&lt;/strong&gt;&lt;br&gt;
Reusability: &lt;br&gt;
     -You can create a component and use that same application through out different parts of your code.&lt;br&gt;
     -This means you write less code and reduce the potential bugs and errors&lt;br&gt;
Maintainability:&lt;br&gt;
     -You can organize each component for a clear purpose and simplify the furture updates or modification.&lt;/p&gt;
&lt;h2&gt;
  
  
  But how does Component Work and Pieced together:
&lt;/h2&gt;

&lt;p&gt;We have a main component that combines all the other components. &lt;br&gt;
It is usually in the default component which is the App.js.&lt;br&gt;
and in here we would see:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Import React from 'react';

function App() {
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;Header /&amp;gt;
      &amp;lt;Content /&amp;gt;
      &amp;lt;Footer /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

export default App
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This App component is linked to index.js, which renders it to the index.html file using:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ReactDOM.render(&amp;lt;App /&amp;gt;, document.getElementById("root"));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Each component is linked by the Import and Export&lt;/strong&gt; &lt;br&gt;
Import syntax: &lt;br&gt;
import ComponentName from "./componentfolder/ComponentName";&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;To use a component, you import it at the beginning of the file &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Export syntax:&lt;br&gt;
export default ComponentName;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;To make a component available for use in other parts of your application, you export it at the end of the file&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;What do we put in the middle?&lt;/strong&gt;&lt;br&gt;
-Component syntax:&lt;br&gt;
 We start with a component function and adds a return property that will contain an JSX style of code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function ComponentName () {
  return (....)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Conclusion:&lt;br&gt;
This simple introduction opens up a more complex structure and component lifecycle that we can explore. We can pass properties (props) to components and use that data to make our UI more interactive. We can nest components inside other components to create more sophisticated layouts.&lt;/p&gt;

&lt;p&gt;For those up to the challenge, exploring class-based components can provide a deeper understanding of React. Class components are the original structure for writing React components and offer additional features like lifecycle methods.&lt;/p&gt;

&lt;p&gt;React components are powerful tools that allow developers to build modular, maintainable, and reusable code. By mastering components, you can create efficient and dynamic web applications. Happy coding! &lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>tutorial</category>
      <category>react</category>
    </item>
    <item>
      <title>EV Test Drive Project</title>
      <dc:creator>AricayaJohn</dc:creator>
      <pubDate>Sat, 27 Apr 2024 18:22:50 +0000</pubDate>
      <link>https://forem.com/aricayajohn/ev-test-drive-project-27o9</link>
      <guid>https://forem.com/aricayajohn/ev-test-drive-project-27o9</guid>
      <description>&lt;h1&gt;
  
  
  Electric Car Website Project
&lt;/h1&gt;

&lt;h3&gt;
  
  
  Step 1 : Coming up with an idea
&lt;/h3&gt;

&lt;p&gt;Purpose: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;As someone interested in new technology and cars, I want to have the users to get information about the Electric vehicles and their qualities that they need&lt;/li&gt;
&lt;li&gt;I want this site to give accessibility to get them book a test drive when the customer's see the car that they want. &lt;/li&gt;
&lt;li&gt;Since in today's world there is a pletora of option to choose from. I want to give users the option to randomly get a car that they can test drive.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Requirements
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;    Have a webrowser installed.&lt;/li&gt;
&lt;li&gt;    Have a code editor installed.&lt;/li&gt;
&lt;li&gt;    Have json-server installed in the code editor.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Installation Instructions
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;   Fork and clone.&lt;a href="https://dev.tourl"&gt;https://github.com/AricayaJohn/EVTestDrive-Project&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;   Run &lt;code&gt;json-server --watch db.json&lt;/code&gt; in code Editor.&lt;/li&gt;
&lt;li&gt;   Open &lt;code&gt;index.html&lt;/code&gt; in the browser.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Step 2: Features
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;-      I want to have a title in the header.&lt;/strong&gt;&lt;br&gt;
  To do this, in the HTML add h1 tag in the body of the file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;h1 id = "header"&amp;gt;Electric Car Test Drive&amp;lt;/h1&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;-      I want to have a random button generator.&lt;/strong&gt;&lt;br&gt;
 To do this, we add a button tag with an id attribute in html.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; &amp;lt;button id = "randomBtn"&amp;gt;Random EV&amp;lt;/button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;-I want a list of cars with its information inside a card structure that can also take a user information so that they can book the test drive. (DOMContentLoaded)&lt;/strong&gt;&lt;br&gt;
  To do this we will create a div element with id attribute and a class attribute that will allow us to edit, style and manipulate the data in html.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  &amp;lt;div id ="ev-collection" class = "card-containter"&amp;gt;&amp;lt;/div&amp;gt;
    &amp;lt;!--This where we will fetch data from db.json then create a card in js--&amp;gt;
        &amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Step 3 : Come up with an &lt;strong&gt;&lt;em&gt;MVP&lt;/em&gt;&lt;/strong&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;  I want a list of cars inside a card structure. (DOMContentLoaded)
To do this, we are going to fetch the data using DOMCOntentLoaded event listener and use a function to call and create the cards from our the data in our json file.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;document.addEventListener("DOMContentLoaded", () =&amp;gt; {
    fetchGetEVData();
    createRandomBtn(); // call the function for random button 
})
//This is to get data from db.json
function fetchGetEVData() {
    fetch("http://localhost:3000/EV")
    .then(resp =&amp;gt; resp.json())
    .then(data =&amp;gt; {
      console.log("Data fetched successfully:", data); // Log fetched data json objects to console
            data.forEach(EV =&amp;gt; showCars(EV));
        })
        //if promise failed to load data from json file
        //then it will show error 
        .catch(error =&amp;gt; {
          console.error('Error fetching the json data', error)
        })
    }
  //Create a card
function showCars(EV) {
  //Fetch data for ev-collection HTML and create structure to cards
    const evCollection = document.getElementById("ev-collection");
        const div = document.createElement("div")
        div.classList.add("card");
  //Create images variable to add to div 
    const img = document.createElement("img")
        img.src = EV.ImageLink
        img.classList.add("car-img")

 //Create h2 variable to give title for card
    const h2 = document.createElement("h2")
    h2.textContent = EV.Company

 //Create p document for model, price, and range
    const p = document.createElement("p")
        p.textContent = EV.Model

 //Create p for price 
    const price = document.createElement("p")
        price.textContent = EV.Price  

 //create p for range
    const range = document.createElement("p")
        range.textContent = EV.Range
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;  I want to take user information into a form so that they can book the test drive 
In our index.js, below of our previous syntax we will create a form variable that will contain alabel and input for name, email, and date of testdrive and a submit button for the form
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; //Create a form for user's info name, email, the day to test drive, and submit button
    const form = document.createElement("form")
        form.classList.add("comment-form")
 //Create a label for name
        const userName = document.createElement("Label")
            userName.textContent = "Name: ";
            const userInput = document.createElement("input")
            userName.type = "text"
            userInput.name = "name";
  //Create a label for email          
        const userEmail = document.createElement("label")
            userEmail.textContent = "Email: ";
            const inputEmail = document.createElement("input")
            inputEmail.type = "email";
            userEmail.name = "email";
 //Create a email label and input
        const dateLabel = document.createElement("label")
        dateLabel.textContent = "Schedule Test Drive: "
        const dateInput = document.createElement("input")
        dateInput.type = "date";
        dateInput.name = "date";
 //Create a submit button to submit form 
        const submitBtn = document.createElement("input")
        submitBtn.type = "submit"
        submitBtn.value = "submit"
 //Handling submit function eventListener
            function handleSubmit(event) {
                event.preventDefault();
                const name = userInput.value;
                const email = inputEmail.value;
                const date = dateInput.value;
                if (!name || !email || !date) {
                    alert("Please complete all fields before submitting the form.");
                    return;
                  }

                alert("Your Test Drive reservaton has been completed");
                form.reset();  
            };
    //callback
    form.addEventListener("submit", handleSubmit)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Then we will append this functions, attributes and elements to the Dom so that we could see it on our website.&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Going to append the form to the card DOM
    form.appendChild(userName);
    form.append(userInput);
//Create a break to have another input bellow
    form.appendChild(document.createElement("br"))
//Going to append the email form to the card DOM    
    form.appendChild(userEmail);
    form.append(inputEmail);
//Going to create a break to put date label and input bellow
    form.appendChild(document.createElement("br"))
//Going to append date label and input to the DOM
    form.appendChild(dateLabel)
    form.append(dateInput);
//Adding a break to put submit button bellow 
    form.appendChild(document.createElement("br"))
//Appending submit button to form 
    form.appendChild(submitBtn)

//Connect the data to html div to be able to send to the DOM       
div.append (img, h2, p, price, range, form)
    evCollection.append(div)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;*&lt;em&gt;-   I want to have a random button generator that would pick a random car for the user. *&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;To do this, we are getting the randomBtn tag in our HTML and adding a function to it so that it would display a random EV card.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function createRandomBtn() {
    const randomBtn = document.getElementById("randomBtn");
    randomBtn.classList.add("random-btn");

    randomBtn.addEventListener("click", () =&amp;gt; {
      const cards = document.querySelectorAll(".card");
      const randomIndex = Math.floor(Math.random() * cards.length);

      cards.forEach((card, index) =&amp;gt; {
        if (index === randomIndex) {
          card.style.display = "block"; // Show the selected card
        } else {
          card.style.display = "none"; // Hide the other cards
        }
      });
    });
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;**-   I want an alert to show up when form is submitted or is incomplete. *&lt;/em&gt;*&lt;br&gt;
 To do this, we add a function and event listener bellow our submit button that we created.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; //handling submit
            function handleSubmit(event) {
                event.preventDefault();
                const name = userInput.value;
                const email = inputEmail.value;
                const date = dateInput.value;
                if (!name || !email || !date) {
                    alert("Please complete all fields before submitting the form.");
                    return;
                  }

                alert("Your Test Drive reservaton has been completed");
                form.reset();  
            };
    form.addEventListener("submit", handleSubmit)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Step 4 : Stretch goals
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt; I want to have a drop down button that filters down to the car model &lt;/li&gt;
&lt;li&gt;    I want user can like/favorite the vehicle (click)&lt;/li&gt;
&lt;li&gt;    Add form for user to submit a test drive request to their email at certain date&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>javascript</category>
      <category>html</category>
      <category>css</category>
      <category>beginners</category>
    </item>
  </channel>
</rss>
