Django

⌘K
  1. Home
  2. Django
  3. Django তে কিভাবে কাজ করতে...
  4. Django-এর ডিফল্ট User মডে...
  5. User এবং Profile মডেলকে একত্রে দেখা ও এডিট করা

User এবং Profile মডেলকে একত্রে দেখা ও এডিট করা

আগের টিউটোরিয়াল দেখে কনফিগার করি এবং আমাদের মডেল টি নিচের মতো ছিল

1. Models:

আমাদের প্রাথমিক মডেলগুলি User এবং Profile থাকবে, যেখানে Profile মডেলটি User মডেলের সাথে এক OneToOne সম্পর্কিত।

from django.contrib.auth.models import User
from django.db import models

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(null=True, blank=True)
    location = models.CharField(max_length=255, null=True, blank=True)
    birth_date = models.DateField(null=True, blank=True)

    def __str__(self):
        return self.user.username

2. Serializers:

এখন, আপনি একটি serializer তৈরি করবেন, যা User এবং Profile মডেলকে একত্রে একটি ফর্ম্যাটে রেন্ডার করবে।

serializers.py:

from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Profile

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = ['bio', 'location', 'birth_date']

class UserProfileSerializer(serializers.ModelSerializer):
    profile = ProfileSerializer()

    class Meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'email', 'profile']

    # Save user data along with profile
    def update(self, instance, validated_data):
        profile_data = validated_data.pop('profile')
        instance.first_name = validated_data.get('first_name', instance.first_name)
        instance.last_name = validated_data.get('last_name', instance.last_name)
        instance.email = validated_data.get('email', instance.email)
        instance.save()

        # Handle Profile Data
        profile = instance.profile
        profile.bio = profile_data.get('bio', profile.bio)
        profile.location = profile_data.get('location', profile.location)
        profile.birth_date = profile_data.get('birth_date', profile.birth_date)
        profile.save()

        return instance

3. Views:

এখন, আপনি views তৈরি করবেন যাতে User এবং Profile ডেটা একসাথে GET, POST, PUT এবং PATCH করা যায়।

views.py:

from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from django.contrib.auth.models import User
from .serializers import UserProfileSerializer

class UserProfileView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, *args, **kwargs):
        try:
            user = request.user
        except User.DoesNotExist:
            return Response({'error': 'User not found'}, status=status.HTTP_404_NOT_FOUND)

        # GET request will return user and profile data
        serializer = UserProfileSerializer(user)
        return Response(serializer.data)

    def put(self, request, *args, **kwargs):
        try:
            user = request.user
        except User.DoesNotExist:
            return Response({'error': 'User not found'}, status=status.HTTP_404_NOT_FOUND)

        # PUT request will update both user and profile data
        serializer = UserProfileSerializer(user, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

4. URLs:

এখন, আপনাকে urls.py ফাইলে এই API endpoint টিকে রেজিস্টার করতে হবে।

urls.py:

from django.urls import path
from .views import UserProfileView

urlpatterns = [
    path('api/user/profile/', UserProfileView.as_view(), name='user_profile'),
]

5. টেস্ট করার জন্য:

এখন আপনি GET এবং PUT রিকোয়েস্ট পাঠাতে পারবেন /api/user/profile/ এ:

GET রিকোয়েস্ট:

আপনি ব্যবহারকারীর first_name, last_name, email, এবং profile ডেটা দেখতে পাবেন।

Response (GET):

{
    "username": "johndoe",
    "first_name": "John",
    "last_name": "Doe",
    "email": "johndoe@example.com",
    "profile": {
        "bio": "Software developer",
        "location": "New York, USA",
        "birth_date": "1990-01-01"
    }
}

PUT রিকোয়েস্ট:

আপনি ব্যবহারকারীর first_name, last_name, email এবং profile (যেমন bio, location, birth_date) আপডেট করতে পারবেন।

Request (PUT):

{
    "first_name": "Jane",
    "last_name": "Doe",
    "email": "janedoe@example.com",
    "profile": {
        "bio": "Full-stack developer",
        "location": "San Francisco, USA",
        "birth_date": "1992-02-02"
    }
}

Response (PUT):

{
    "username": "johndoe",
    "first_name": "Jane",
    "last_name": "Doe",
    "email": "janedoe@example.com",
    "profile": {
        "bio": "Full-stack developer",
        "location": "San Francisco, USA",
        "birth_date": "1992-02-02"
    }
}

5. Security (Permissions):

আপনি চাইলে নিরাপত্তার জন্য IsAuthenticated পারমিশন ক্লাস ব্যবহার করতে পারেন, যা নিশ্চিত করবে যে শুধু লগ ইন করা ব্যবহারকারীরা API-তে অ্যাক্সেস করতে পারবেন।

from rest_framework.permissions import IsAuthenticated

class UserProfileView(APIView):
    permission_classes = [IsAuthenticated]
    # Your existing methods

How can we help?