my journey with next,js and django for the past two weeks.
Elvis Munene
Posted on September 16, 2024
My Journey with Next.js and Django: Building a Finance App and Polling App
Introduction
In this article, I'll walk you through two projects I’ve built using Next.js and Django. The first is a simple finance app built with Next.js, PostgreSQL, and deployed on Vercel. The second is a polling app developed using Django, with models for questions and choices.
Table of Contents
Next.js Finance App
Introduction
Project Setup
Styling
Routing
Data Fetching
Error Handling
Form Validation
Authentication
Optimization
Deployment on Vercel
Django Polling App
Introduction
Models: Question and Choice
Admin Site
Views and Templates
URL Routing
Voting and Tallying
Error Handling
Deployment
Next.js Finance App
- Introduction The finance app allows users to log in, create invoices, manage customers, and perform CRUD operations (Create, Read, Update, Delete). We use PostgreSQL as the database, and I followed MySQL logic for data management.
This project was deployed on Vercel, leveraging its seamless integration with Next.js.
- Project Setup To set up a Next.js app, I initialized the project using the following command:
bash
Copy code
npx create-next-app@latest finance-app
cd finance-app
npm install
Key Dependencies:
PostgreSQL (pg)
Authentication (next-auth)
Database Setup:
bash
Copy code
npm install pg
I connected to PostgreSQL by creating a db.js file:
javascript
Copy code
import { Pool } from 'pg';
const pool = new Pool({
user: 'yourUser',
host: 'localhost',
database: 'finance_db',
password: 'yourPassword',
port: 5432,
});
export default pool;
- Styling For styling, I used CSS Modules and styled-components:
javascript
Copy code
import styles from './Home.module.css';
function HomePage() {
return (
Welcome to Finance App
);
}
- Routing Next.js uses a file-based routing system. For each page, a corresponding .js file is created inside the pages/ directory.
Example:
bash
Copy code
/pages/invoice.js
The routing looks like:
javascript
Copy code
import Link from 'next/link';
function Invoice() {
return (
Invoices
View Customers
);
}
export default Invoice;
- Data Fetching Next.js supports Server-Side Rendering (SSR) and Static Generation. For my app, I used getServerSideProps to fetch invoice data:
javascript
Copy code
export async function getServerSideProps() {
const res = await fetch('http://api.yourapp.com/invoices');
const invoices = await res.json();
return {
props: {
invoices,
},
};
}
- Error Handling Error handling was implemented using a combination of try-catch blocks and a custom error page (pages/_error.js):
javascript
Copy code
try {
const res = await fetch(...);
if (!res.ok) throw new Error('Failed to fetch data');
} catch (error) {
console.error(error);
return { props: { error: 'Failed to load data' } };
}
- Form Validation For form validation, I used Formik and Yup:
bash
Copy code
npm install formik yup
Sample code:
javascript
Copy code
import { useFormik } from 'formik';
import * as Yup from 'yup';
const formik = useFormik({
initialValues: { name: '' },
validationSchema: Yup.object({
name: Yup.string().required('Name is required'),
}),
onSubmit: (values) => {
console.log(values);
},
});
- Authentication NextAuth.js was used for authentication, supporting multiple providers:
bash
Copy code
npm install next-auth
Set up authentication in pages/api/auth/[...nextauth].js:
javascript
Copy code
import NextAuth from 'next-auth';
import Providers from 'next-auth/providers';
export default NextAuth({
providers: [
Providers.Google({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
}),
],
});
- Optimization For performance optimization, I used lazy loading for images and components:
javascript
Copy code
const LazyComponent = dynamic(() => import('../components/LazyComponent'));
- Deployment on Vercel Deployment on Vercel was seamless:
bash
Copy code
vercel deploy
You can view the app live at: Finance App Link.
Django Polling App
Introduction
The polling app is a simple web application where users can vote on polls. There are two models: Question and Choice.Models: Question and Choice
I defined two models in models.py:
python
Copy code
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)
- Admin Site To manage the polls, I registered the models in the Django admin:
python
Copy code
from django.contrib import admin
from .models import Question, Choice
admin.site.register(Question)
admin.site.register(Choice)
- Views and Templates I created views for listing polls and voting. For example, the view for poll detail:
python
Copy code
from django.shortcuts import render, get_object_or_404
from .models import Question
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/detail.html', {'question': question})
- URL Routing The URL configuration for the polls:
python
Copy code
from django.urls import path
from . import views
urlpatterns = [
path('int:question_id/', views.detail, name='detail'),
]
- Voting and Tallying The voting view updates the vote tally:
python
Copy code
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
selected_choice = question.choice_set.get(pk=request.POST['choice'])
selected_choice.votes += 1
selected_choice.save()
return redirect('polls:results', question_id=question.id)
- Error Handling Django handles errors gracefully with its built-in middleware. I used custom 404 and 500 error pages for better user experience.
python
Copy code
def custom_404_view(request, exception):
return render(request, '404.html', status=404)
- Deployment I deployed the Django polling app using Heroku. It integrates easily with PostgreSQL and Django’s settings.
bash
Copy code
heroku create
git push heroku master
The app is live at: Polling App Link.
Conclusion
Posted on September 16, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.