TypeError при вызове Profile.object.create в django / python - PullRequest
1 голос
/ 25 апреля 2019

При попытке создать новый профиль я получаю следующую ошибку.

Got a `TypeError` when calling `Profile.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Profile.objects.create()`. You may need to make the field read-only, or override the ProfileSerializer.create() method to handle this correctly.
Original exception was:

Я не уверен, почему я получаю эту ошибку.

У меня есть модель и сериализатор и представления и URL-адреса.Я даже не уверен, откуда происходит ошибка в процессе.

models.py

class Profile(models.Model):
    user = models.ForeignKey(
        User, on_delete=models.CASCADE
    )
    synapse = models.CharField(max_length=25, null=True)
    bio = models.TextField(null=True)
    profile_pic = models.ImageField(upload_to='./profile_pics/',
                                    height_field=500,
                                    width_field=500,
                                    max_length=150)
    facebook = models.URLField(max_length=150)
    twitter = models.URLField(max_length=150)
    updated = models.DateTimeField(auto_now_add=True)

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

profileViews.py

from users.models import Profile

from rest_framework.generics import ListAPIView, RetrieveAPIView, CreateAPIView
from rest_framework.generics import DestroyAPIView, UpdateAPIView

from users.api.serializers import ProfileSerializer


class ProfileListView(ListAPIView):
    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer


class ProfileRetrieveView(RetrieveAPIView):
    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer


class ProfileCreateView(CreateAPIView):
    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer


class ProfileDestroyView(DestroyAPIView):
    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer


class ProfileUpdateView(UpdateAPIView):
    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer

urls.py

from django.urls import path

from users.api.views.profileViews import ProfileListView, ProfileRetrieveView, ProfileCreateView
from users.api.views.profileViews import ProfileDestroyView, ProfileUpdateView

urlpatterns = [
    path('', ProfileListView.as_view()),
    path('create/', ProfileCreateView.as_view()),
    path('update/<pk>/', ProfileUpdateView.as_view()),
    path('delete/<pk>/', ProfileDestroyView.as_view()),
    path('<pk>/', ProfileRetrieveView.as_view())
]

Сериализатор для профиля

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = (
            'id',
            'user',
            'synapse',
            'bio',
            'profile_pic',
            'facebook',
            'twitter'
        )

означает ли это, что мне нужно указать тип изображения.Я хочу, чтобы изображения профиля были в главной папке пользователей.

enter image description here

Ответы [ 2 ]

0 голосов
/ 26 апреля 2019

Измените поле profile_pic в моделях, как показано ниже.( удалить height_field и width_field)

profile_pic = models.ImageField(upload_to='./profile_pics/', max_length=150)

Поскольку они не являются чем-то, что автоматически изменяет размер изображения.

Смотрите этоSO post 'getattr (): имя атрибута должно быть строкой' ошибка в панели администратора для модели с ImageField


Кроме этого, я быпредлагаем использовать ModelViewset с DRF-маршрутизаторами в вашем коде, поскольку вы обрабатываете CRUD заявка.

0 голосов
/ 26 апреля 2019

Обновите ваш ProfileSerializer до

class ProfileSerializer(serializers.ModelSerializer):

    user = UserSerializer(many=False, read_only=True)
    class Meta:
        model = Profile
        fields = (
            'id',
            'user',
            'synapse',
            'bio',
            'profile_pic',
            'facebook',
            'twitter'
        )

По вашему мнению, вместо этого я предлагаю пользователю ModelViewSet. Видел, что вы используете методы по умолчанию, так что просто нужно:

class ProfileViewSet(viewsets.ModelViewSet):
    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer

urls.py

from rest_framework import routers


router = routers.SimpleRouter()

router.register('profiles', ProfileViewSet, base_name='profile')
urlpatterns = [
    ...,
    url('/api', include(router.urls)),
]

Это относится к RESTful API, примеры:

  • Получить список: domain.com/api/profiles/ (метод GET)

  • Создать новый профиль: domain.com/api/profiles/ (метод POST)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...