Step by step guide to build an app using :1.next.js 2.django.

liz_nzisa_ac2b0175672cd1c

liz nzisa

Posted on September 16, 2024

Step by step guide to build an app using :1.next.js 2.django.

project Documentation: Next.js Finance App & Django Polling App

1. Next.js Finance App

Project Overview

This project is a finance application built using Next.js. It allows users to log in, view invoices, collected amounts, add or edit customers, and view customer and invoice pages. It also provides a recent revenue summary for financial tracking.

The app uses PostgreSQL as the primary database, enhanced with MySQL logic for optimized queries. The app is successfully deployed on Vercel.
**
Features
Authentication: Secure login system to access personal accounts.
Invoice Management: View, edit, and manage invoices and track the total amount collected.
Customer Management: Add, view, and edit customer information.
Revenue Summary: View the most recent revenue generated from customer invoices.
Database: PostgreSQL integrated with MySQL logic.
Deployment: Deployed on Vercel.

Installation
Step 1: Install Node.js and Next.js

Install Node.js
sudo apt update
sudo apt install nodejs

Install Next.js and create a new project
npx create-next-app@latest finance-app
cd finance-app
npm install
`

Step 2: Install PostgreSQL

Install PostgreSQL
sudo apt update
sudo apt install postgresql postgresql-contrib

Start PostgreSQL
sudo service postgresql start

Step 3: Setup MySQL (Optional for Logic)

Install MySQL
sudo apt install mysql-server

Start MySQL
sudo service mysql start

Step 4: Run Development Server

Start the Next.js development server
npm run dev

Key Concepts

  1. Routing

Next.js provides a file-based routing system. The app has routes for invoices, customers, and revenue pages:

js

// Example: Invoice route in pages/invoices/[id].js
import { useRouter } from 'next/router';

export default function InvoicePage() {
const router = useRouter();
const { id } = router.query;

return <div>Invoice ID: {id}</div>;
Enter fullscreen mode Exit fullscreen mode

}

  1. Data Fetching

Server-side rendering (SSR) with getServerSideProps ensures real-time data updates for viewing recent revenue and invoice details:

js

export async function getServerSideProps() {
const invoices = await fetchInvoicesFromDB();
return { props: { invoices } };
}

  1. Form Validation

Using react-hook-form and yup for form validation when adding/editing customer information:

js

`import { useForm } from 'react-hook-form';
import * as yup from 'yup';

const schema = yup.object().shape({
customerName: yup.string().required(),
});

export default function AddCustomer() {
const { register, handleSubmit } = useForm({
validationSchema: schema,
});

const onSubmit = data => console.log(data);

return (



Submit

);
}`
  1. Error Handling

Handled via custom error pages (404.js, 500.js) to enhance the user experience:

js

export default function Custom404() {
return <h1>404 - Page Not Found</h1>;
}

  1. Authentication

Implemented using NextAuth.js to secure login functionality:

js

`import { signIn, useSession } from 'next-auth/react';

export default function Login() {
const { data: session } = useSession();

if (session) {
return

Welcome {session.user.email}

;
}

return signIn()}>Sign In;
}
``

  1. Styling

Styled using Tailwind CSS for responsive and modern UI design:

html

<div className="bg-gray-200 p-4">
<h1 className="text-2xl font-bold">Recent Revenue</h1>
<p>Total Revenue: $5000</p>
</div>

  1. Meta Data & SEO

Handled through the Next.js

component for SEO:

js

<Head>
<title>Finance App - Recent Revenue</title>
<meta name="description" content="View your recent revenue and manage invoices" />
</Head>

  1. Django Polling App Project Overview

This project is a polling application created using Django. It allows users to vote on polls and view poll results. The admin interface enables the creation, modification, and deletion of polls.

The project features two models: Question and Choice. Each Question has associated Choices for users to vote on, and each Choice tracks the number of votes.
Features

Public Polling: Allows users to view and vote on polls.
Admin Interface: Manage polls, add questions, and track votes.
Models:
    Question model with the question text and publication date.
    Choice model with the choice text and vote count, linked to Question.
Enter fullscreen mode Exit fullscreen mode

Installation
Step 1: Install Python and Django

bash

Install Python
sudo apt update
sudo apt install python3

Install Django
pip install django

Step 2: Create a Django Project

django-admin startproject polls_project
cd polls_project

Start Django development server

python manage.py runserver

Step 3: Setup Database (SQLite by default)

Migrate to initialize database
python manage.py migrate

Step 4: Create Polling Models

python

models.py
from django.db import models

class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')

class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)`

Key Concepts

  1. Routing

Django's URL routing mechanism is used for linking views with URLs:

python
` urls.py
from django.urls import path
from . import views

urlpatterns = [
path('', views.index, name='index'),
path('int:question_id/', views.detail, name='detail'),
path('int:question_id/vote/', views.vote, name='vote'),
]
`

  1. Form Validation

Form validation is used when submitting votes, ensuring that valid data is submitted:

python

`forms.py
from django import forms

class VoteForm(forms.Form):
choice = forms.ChoiceField(choices=[(choice.id, choice.choice_text) for choice in choices])`

  1. Admin Interface

The Django admin panel is used to manage questions and choices:

python
`
from django.contrib import admin
from .models import Question, Choice

admin.site.register(Question)
admin.site.register(Choice)`

  1. Error Handling

Custom error messages are displayed if an invalid poll or vote is submitted:

python

def vote(request, question_id):
try:
question = get_object_or_404(Question, pk=question_id)
except KeyError:
return render(request, 'polls/detail.html', {'error_message': "You didn't select a choice."})

  1. Styling

The app uses Bootstrap for a clean, responsive interface:

html

<div class="container">
<h1>Poll Results</h1>
<p>{{ question.question_text }}</p>
</div>

  1. Meta Data

Meta tags are used to improve SEO:

html

<meta name="description" content="Vote on the latest polls and view poll results.">

💖 💪 🙅 🚩
liz_nzisa_ac2b0175672cd1c
liz nzisa

Posted on September 16, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related