Next.js code with django backend api :-

Front end code in next-js :-
api-check/page.tsx :-

'use client';

import { useEffect, useState } from 'react';
import axios from 'axios';

const API_URL = 'http://localhost:8000/api/tasks/';

export default function HomePage() {
  const [tasks, setTasks] = useState<any[]>([]);
  const [title, setTitle] = useState('');
  const [editingId, setEditingId] = useState<number | null>(null);

  // Fetch tasks
  useEffect(() => {
    axios.get(API_URL)
      .then(res => setTasks(res.data))
      .catch(err => console.error('Fetch error:', err));
  }, []);

  // Create or update task
  const handleSubmit = async () => {
    if (!title.trim()) return;

    try {
      if (editingId) {
        const res = await axios.put(`${API_URL}${editingId}/`, {
          title,
          completed: tasks.find((t) => t.id === editingId)?.completed || false,
        });

        setTasks(tasks.map((t) => (t.id === editingId ? res.data : t)));
        setEditingId(null);
      } else {
        const res = await axios.post(API_URL, { title, completed: false });
        setTasks([...tasks, res.data]);
      }

      setTitle('');
    } catch (err) {
      console.error('Submit error:', err);
    }
  };

  // Toggle completed
  const toggleComplete = async (task: any) => {
    try {
      const res = await axios.put(`${API_URL}${task.id}/`, {
        ...task,
        completed: !task.completed,
      });
      setTasks(tasks.map((t) => (t.id === task.id ? res.data : t)));
    } catch (err) {
      console.error('Toggle error:', err);
    }
  };

  // Delete
  const handleDelete = async (id: number) => {
    try {
      await axios.delete(`${API_URL}${id}/`);
      setTasks(tasks.filter((t) => t.id !== id));
    } catch (err) {
      console.error('Delete error:', err);
    }
  };

  // Start editing
  const handleEdit = (task: any) => {
    setEditingId(task.id);
    setTitle(task.title);
  };

  return (
    <div style={{ padding: '2rem' }}>
      <h1>📝 Task Manager</h1>

      <div style={{ marginBottom: '1rem' }}>
        <input
          type="text"
          placeholder="Enter task"
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          style={{ padding: '0.5rem', marginRight: '0.5rem' }}
        />
        <button onClick={handleSubmit} style={{ padding: '0.5rem 1rem' }}>
          {editingId ? 'Update' : 'Add'} Task
        </button>
        {editingId && (
          <button
            onClick={() => {
              setEditingId(null);
              setTitle('');
            }}
            style={{ marginLeft: '1rem', color: 'gray' }}
          >
            Cancel
          </button>
        )}
      </div>

      <ul style={{ listStyle: 'none', padding: 0 }}>
        {tasks.map((task) => (
          <li key={task.id} style={{ marginBottom: '1rem' }}>
            <span
              onClick={() => toggleComplete(task)}
              style={{
                textDecoration: task.completed ? 'line-through' : 'none',
                cursor: 'pointer',
              }}
            >
              {task.title}
            </span>

            <button
              onClick={() => handleEdit(task)}
              style={{ marginLeft: '1rem' }}
            >
              ✏️ Edit
            </button>

            <button
              onClick={() => handleDelete(task.id)}
              style={{ marginLeft: '0.5rem', color: 'red' }}
            >
              ❌ Delete
            </button>
          </li>
        ))}
      </ul>
    </div>
  );
}

Back End Code of django :-

   Perfect! Let's build a full-stack CRUD app where:

The Django backend has a Task model.

The Next.js frontend interacts with it using axios.

✅ Django Backend (API)
You’ve defined the model:

# models.py
from django.db import models

class Task(models.Model):
    title = models.CharField(max_length=255)
    completed = models.BooleanField(default=False)

    def __str__(self):
        return self.title

🔸 1. Serializer

# serializers.py
from rest_framework import serializers
from .models import Task

class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = '__all__'
🔸 2. ViewSet

# views.py
from rest_framework import viewsets
from .models import Task
from .serializers import TaskSerializer

class TaskViewSet(viewsets.ModelViewSet):
    queryset = Task.objects.all()
    serializer_class = TaskSerializer
🔸 3. URL Routing

# urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import TaskViewSet

router = DefaultRouter()
router.register(r'tasks', TaskViewSet)

urlpatterns = [
    path('api/', include(router.urls)),
]
Now your API is available at:
🟢 http://localhost:8000/api/tasks/