В настоящее время я настраиваю бэкэнд (используя MongoDB, djongo и pymongo) сайта, на котором вы должны зарегистрироваться, а затем ввести личную информацию, прежде чем получить доступ к панели инструментов, короче.
Дело в том, чтосистема регистрации работает безупречно благодаря Djoser, и я также добавил сигнал для создания своего собственного пользовательского экземпляра с новым пользовательским экземпляром.Таким образом, именно моя собственная модель MyUser создала патч с другим маршрутом, и это тоже, кажется, работает идеально.
Проблема в том, что на моем административном сайте, когда я пытаюсь удалить модель пользователя, яполучаю такую ошибку:
Traceback (most recent call last):
File "/Users/quentinmoinat/PycharmProjects/dimtech_backend/venv/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 763, in parse
return handler(self, statement)
File "/Users/quentinmoinat/PycharmProjects/dimtech_backend/venv/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 881, in _update
self._query = UpdateQuery(self.db, self.connection_properties, sm, self._params)
File "/Users/quentinmoinat/PycharmProjects/dimtech_backend/venv/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 312, in __init__
super().__init__(*args)
File "/Users/quentinmoinat/PycharmProjects/dimtech_backend/venv/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 74, in __init__
self.parse()
File "/Users/quentinmoinat/PycharmProjects/dimtech_backend/venv/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 343, in parse
self.result = db[self.left_table].update_many(**kwargs)
File "/Users/quentinmoinat/PycharmProjects/dimtech_backend/venv/lib/python3.6/site-packages/pymongo/collection.py", line 1065, in update_many
session=session),
File "/Users/quentinmoinat/PycharmProjects/dimtech_backend/venv/lib/python3.6/site-packages/pymongo/collection.py", line 851, in _update_retryable
_update, session)
File "/Users/quentinmoinat/PycharmProjects/dimtech_backend/venv/lib/python3.6/site-packages/pymongo/mongo_client.py", line 1248, in _retryable_write
return self._retry_with_session(retryable, func, s, None)
File "/Users/quentinmoinat/PycharmProjects/dimtech_backend/venv/lib/python3.6/site-packages/pymongo/mongo_client.py", line 1201, in _retry_with_session
return func(session, sock_info, retryable)
File "/Users/quentinmoinat/PycharmProjects/dimtech_backend/venv/lib/python3.6/site-packages/pymongo/collection.py", line 847, in _update
retryable_write=retryable_write)
File "/Users/quentinmoinat/PycharmProjects/dimtech_backend/venv/lib/python3.6/site-packages/pymongo/collection.py", line 818, in _update
_check_write_command_response(result)
File "/Users/quentinmoinat/PycharmProjects/dimtech_backend/venv/lib/python3.6/site-packages/pymongo/helpers.py", line 217, in _check_write_command_response
_raise_last_write_error(write_errors)
File "/Users/quentinmoinat/PycharmProjects/dimtech_backend/venv/lib/python3.6/site-packages/pymongo/helpers.py", line 198, in _raise_last_write_error
raise DuplicateKeyError(error.get("errmsg"), 11000, error)
pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection: dimtech.API_myuser index: user_id_1 dup key: { : null }
Вот мой код:
from jsonfield import JSONField
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from rest_framework import serializers
from rest_framework import viewsets
from rest_framework.generics import RetrieveUpdateAPIView
class MyUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
myuser_phone_number = models.CharField(max_length=15, null=True)
myuser_job = models.CharField(max_length=64, null=True)
myuser_nationality = models.CharField(max_length=64, null=True)
myuser_avatar = models.ImageField(upload_to="photos/users/Clients", null=True)
myuser_birthdate = models.DateField(null=True)
myuser_first_sign_in = models.BooleanField(default=True)
myuser_data = JSONField(null=True)
myuser_markets = models.ManyToManyField('Market', related_name='market_followers')
class MyUserSerializer(serializers.ModelSerializer):
username = serializers.CharField(read_only=True, source="user.username")
first_name = serializers.CharField(read_only=True, source="user.first_name")
last_name = serializers.CharField(read_only=True, source="user.last_name")
email = serializers.CharField(read_only=True, source="user.email")
is_active = serializers.BooleanField(read_only=True, source="user.is_active")
class Meta:
model = MyUser
fields = ('id', 'username', 'first_name', 'last_name', 'email', 'is_active', 'myuser_phone_number',
'myuser_birthdate', 'myuser_avatar', 'myuser_nationality', 'myuser_job', 'myuser_first_sign_in',
'myuser_data')
class MyUserViewSet(viewsets.ModelViewSet):
queryset = MyUser.objects.all()
serializer_class = MyUserSerializer
class CurrentMyUser(RetrieveUpdateAPIView):
serializer_class = MyUserSerializer
def get_object(self):
queryset = MyUser.objects.get(user=self.request.user)
return queryset
def perform_update(self, serializer):
myuser = serializer.save()
# add data on meta class User
user = myuser.user
if 'username' in self.request.data:
user.username = self.request.data['username']
if 'email' in self.request.data:
user.email = self.request.data['email']
if 'first_name' in self.request.data:
user.first_name = self.request.data['first_name']
if 'last_name' in self.request.data:
user.last_name = self.request.data['last_name']
user.save()
# myuser first sign in
if myuser.myuser_first_sign_in:
if self.request.data.get('last_name', False) is not False and \
self.request.data.get('first_name', False) is not False and \
self.request.data.get('myuser_nationality', False) is not False and \
self.request.data.get('myuser_birthdate', False) is not False and \
self.request.data.get('email', False) is not False:
myuser.myuser_first_sign_in = False
myuser.save()
@receiver(post_save, sender=User)
def registration(sender, instance, created, **kwargs):
if created:
MyUser.objects.create(user=instance)
Заранее благодарю за помощь и совет,
Тинтин