Расширенные поля в пользовательской модели Django User не отображаются

Я пытаюсь расширить стандартную модель пользователя Django, чтобы включить другие поля и позволить пользователям обновлять эту информацию.

Вот что у меня есть в models.py:

from django.db import models from django.contrib.auth.models import User из django.db.models.signals import post_save из django.dispatch import receiver

#extending user model to allow users to add more profile information
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True)
    city = models.CharField(max_length=50, blank=True)
    country = models.CharField(max_length=50, blank=True)
    @receiver(post_save, sender=User)
    def create_user_profile(sender, instance, created, **kwargs):
        if created:
            Profile.objects.create(user=instance)

    @receiver(post_save, sender=User)
    def save_user_profile(sender, instance, **kwargs):
        instance.profile.save()

api.py:

from rest_framework import generics, permissions, mixins
from rest_framework.authentication import TokenAuthentication
from rest_framework.response import Response
from .serializers import RegisterSerializer, UserSerializer
from django.contrib.auth.models import User
from rest_framework.permissions import AllowAny

#Register API
class RegisterApi(generics.GenericAPIView):
    serializer_class = RegisterSerializer
    #remove this if it doesn't work
    authentication_classes = (TokenAuthentication,)
    permission_classes = (AllowAny,)
    def post(self, request, *args,  **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        return Response({
            "user": UserSerializer(user, context=self.get_serializer_context()).data,
            "message": "User Created Successfully.  Now perform Login to get your token",
        })

и serializers.py:

from django.contrib.auth.models import User
from accounts.models import Profile
from rest_framework import serializers
#added more imports based on simpleJWT tutorial
from rest_framework.permissions import IsAuthenticated
from django.db import models
from django.contrib.auth import authenticate
from django.contrib.auth.hashers import make_password
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer;
from rest_framework_simplejwt.views import TokenObtainPairView;


#changed from serializers.HyperLinked to ModelSerializer
class RegisterSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        #removed url from fields
        fields = ['username', 'email', 'password', 'bio', 'first_name', 'last_name', 'city', 'country']
        extra_kwargs = {
            'password': {'write_only': True},
        }
        def create(self,validated_data):
            user = Profile.objects.create_user(
                                            username=validated_data['username'],
                                            # password=validated_data['password'],
                                            email=validated_data['email'])
            user.set_password(validated_data['password'])
            user.save()
            return user

#customizing the payload we get from our access tokens
class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)
        token['username'] = user.username
        return token

class CustomTokenObtainPairView(TokenObtainPairView):
    serializer_class = CustomTokenObtainPairSerializer


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = '__all__'

class UserSerializerWithToken(serializers.ModelSerializer):
    token = serializers.SerializerMethodField()
    password = serializers.CharField(write_only=True)


class PasswordSerializer(serializers.Serializer):
    old_password = serializers.CharField(required=True)
    new_password = serializers.CharField(required=True)

Проблема в том, что я не получаю новые поля, которые я создал на портале администратора. Я запустил python manage.py makemigrations

And in admin.py:

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import Profile

admin.site.register(Profile, UserAdmin)

Вот моя трассировка:

    ERRORS:
    <class 'django.contrib.auth.admin.UserAdmin'>: (admin.E019) The value of 'f
    ilter_horizontal[0]' refers to 'groups', which is not a field of 'accounts.Profile'.
    <class 'django.contrib.auth.admin.UserAdmin'>: (admin.E019) The value of 'f
    ilter_horizontal[1]' refers to 'user_permissions', which is not a field of 'accounts.Profile'.
...

Вам нужно создать класс ProfileAdmin и зарегистрировать его:

admin.site.register(Profile, ProfileAdmin)

или просто зарегистрировать Профиль:

admin.site.register(Profile)
Вернуться на верх