【Next.js×Django】ユーザ情報を更新する処理

# やりたいこと
ユーザIDをキーにしてデータベースからレコードを抽出して画像カラム`generalUserImage`を更新する処理を備忘録として記載します。

# ディレクトリ構成


```
└── Project/
    ├── frontend/
    │   └── app/
    │       ├── api
    │       └── generalUsers/
    │           ├── dashboard/
    │           │   └── page.tsx
    │           └── registration/
    │               └── page.tsx
    └── backend/
        └── generalUsers/
            ├── urls.py
            ├── models.py
            └── views.py
```

# フロント側(Next.js)の実装

```frontend/generalUsers/dashboardpage.tsx
'use client'
import { useSearchParams } from "next/navigation";
import { useRouter } from "next/navigation";
import axios from "axios";
import { useEffect,useState } from "react";

export default function Dashboard(){
    const searchParam = useSearchParams();
    const router = useRouter();
    const userId = searchParam.get('userId');
    const userName = searchParam.get('userName');
    console.log('userId is',userId);
    console.log('userName is',userName);
    const thumbnailUrl = searchParam.get('url');
    const imageKey = searchParam.get('imageKey');

    const [generalUserId, setGeneralUserId] = useState<string | null>(null);
    const [generalUserName, setGeneralUserName] = useState<string | null>(null);
    const [generalUserEmail, setGeneralUserEmail] = useState<string | null>(null);
    /*
    // ✅ クライアントマウント後に sessionStorage を読み込む
    useEffect(() => {
        const id = sessionStorage.getItem('generalUserId');
        const name = sessionStorage.getItem('generalUserName');
        const email = sessionStorage.getItem('generalUserEmail');

        setGeneralUserId(id);
        setGeneralUserName(name);
        setGeneralUserEmail(email);

        console.log('id is:', id);
        console.log('name is:', name);
        console.log('email is:', email);
    }, []);
    */

    const clickBackToPage = ()=>{
        router.push('/components/thumbnailsUploadthing');
    }

    const clickUpdate = async()=>{
        try{
            const response  = await axios.put('http://127.0.0.1:8000/generalusers/updategeneralusers/',{
                generalUserId: userId,
                generalUserImage: thumbnailUrl
            });
            alert('Success to update.');
            console.log('Update data is,',response.data);
        }catch(error){
            alert('Failed to update');
            console.log(error);
        }

    }

    return (
        <div>
            <form>
                <div>
                    {generalUserId && (
                        <input type="hidden" value={generalUserId}/>
                    )}
                    {generalUserName && (
                        <input type="hidden" value={generalUserName}/>
                    )}
                    {generalUserEmail && (
                        <input type="hidden" value={generalUserEmail}/>
                    )}
                    
                </div>
                <div>
                    サムネイルURL:<img src={thumbnailUrl} width={200} height={200}/>
                    サムネイルURLKey:{imageKey}
                    <div>
                        この画像で登録しますか？
                    </div>
                    <div>
                        <button
                            type="button"
                            className="bg bg-blue-500 text-white rounded-md px-4 py-4"
                            onClick={clickUpdate}
                        >
                            Update
                        </button>
                        <button
                            type="button"
                            className="bg bg-blue-500 text-white rounded-md px-4 py-4"
                            onClick={()=>clickBackToPage()}
                        >
                            BackToPage
                        </button>
                    </div>
                </div>
            </form>
        </div>
    )
}
```

# サーバ側(Django)の実装

```backend/generalUsers/urls.py
from django.urls import path,include
from .views import GeneralUsersViewSet #Add
from rest_framework.routers import DefaultRouter
#from .views import GeneralUsersViewSet
from .views import update_general_user #Add

router = DefaultRouter()
router.register('registergeneralusers',GeneralUsersViewSet,basename='create_general_user')

urlpatterns =[
    path('updategeneralusers/', update_general_user),
    path('',include(router.urls))
]
```

```backend/generalUsers/views.py
#from django.shortcuts import render
from .models import GeneralUsers
from .serializers import GeneralUsersSerializer
from rest_framework import viewsets
from rest_framework.decorators import api_view #追加
from rest_framework.response import Response # 追加
from rest_framework import status #追加
from django.db import transaction # 追加
from django.contrib.auth.hashers import make_password #追加
from django.core.exceptions import ObjectDoesNotExist #Add
from django.contrib.auth.hashers import check_password #Add
from .serializers import GeneralUsersSerializer
# Create your views here.

class GeneralUsersViewSet(viewsets.ModelViewSet):
    queryset = GeneralUsers.objects.all()
    serializer_class = GeneralUsersSerializer

@api_view(['POST'])
def create_general_user(request):
    if request.method == 'POST':
        with transaction.atomic():
            serializer = GeneralUsersSerializer(data=request.data)
            if serializer.is_valid():
                password = serializer.validated_data['password']
                hashed_password = make_password(password)

                serializer.validated_data['generalUserPassword'] = hashed_password
                if serializer.is_valid():
                    serializer.save()
                    return Response(serializer.data,status=status.HTTP_201_CREATED)
                else:
                    return Response(serializer.errors,status=status.HTTP_500_INTERNAL_SERVER_ERROR)
                

@api_view(['PUT'])
def update_general_user(request):
    try:
        general_user_id = request.data.get('generalUserId')
        image_url = request.data.get('generalUserImage')

        user = GeneralUsers.objects.get(generalUserId=general_user_id)
        user.generalUserImage = image_url
        user.save()

        serializer = GeneralUsersSerializer(user)
        return Response(serializer.data,status=status.HTTP_200_OK)
    except GeneralUsers.DoesNotExist:
        return Response({'error': 'User not found'}, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
```

```backend/generalUsers/models.py
from django.db import models

# Create your models here.
class GeneralUsers(models.Model):
    generalUserId = models.CharField(blank=False,null=False)
    generalUserName = models.CharField(blank=False,null=False)
    generalUserImage = models.CharField(blank=True,null=True)
    generalUserEmail = models.CharField(blank=False,null=False)
    generalUserPassword = models.CharField(blank=False,null=False)
    generalUserDepartment = models.CharField(blank=False,null=False)
    generalUserDepartmentPhone = models.CharField(blank=False,null=False)

    def __str__(self):
        return self.generalUserId

```

以上です。