Не могу разобраться с конечной точкой DRF.
Я работаю над этой конечной точкой для хранения электронной почты. Я отправляю POST на /emails с { "email": "user101c@email.com" }
и получаю ошибку IntegrityError at /emails (1048, "Column 'user_id' cannot be null")
. Очевидно, что это ошибка на уровне базы данных. Поле user_id не должно задаваться пользователем. Я не уверен, как действовать дальше.
models.py
class EmailAddress(ExportModelOperationsMixin('email_address'), models.Model):
user = models.ForeignKey(User, related_name='emails', on_delete=models.CASCADE)
email = models.EmailField(max_length=255)
verify_key = models.CharField(max_length=255, null=True, blank=True)
verified = models.BooleanField(default=False)
created = models.DateTimeField(auto_now=True)
verification_sent = models.DateTimeField(null=True, blank=True)
reset_key = models.CharField(default=None, null=True, max_length=255, blank=True)
reset_sent = models.DateTimeField(null=True, blank=True)
class Meta:
verbose_name = _("email")
verbose_name_plural = _("emails")
unique_together = [("user", "email")]
ordering = ['-created']
def __str__(self):
return self.email
def save(self, *args, **kwargs):
self.verify_key = get_random_string(length=32)
if not self.id: # if new
verify_email_signal.send(sender=self.__class__, email=self.email, key=self.verify_key)
self.verification_sent = timezone.now()
super(EmailAddress, self).save(*args, **kwargs)
serializers.py
class EmailAddressSerializer(serializers.ModelSerializer):
class Meta:
model = account_models.EmailAddress
fields = ['user', 'email', 'verified', 'created', 'verification_sent', 'reset_sent']
read_only_fields = ['id', 'user']
views.py
class EmailAddressViewSet(ModelViewSet):
permission_classes = (permissions.IsAuthenticated,)
serializer_class = serializers.EmailAddressSerializer
def get_queryset(self):
return account_models.EmailAddress.objects.filter(user=self.request.user)
urls.py
email_list = views.EmailAddressViewSet.as_view({
'get': 'list',
'post': 'create'
})
email_detail = views.EmailAddressViewSet.as_view({
'get': 'retrieve',
'put': 'update',
'patch': 'partial_update',
'delete': 'destroy'
})
urlpatterns = [
path('emails/', email_list, name='email_list'),
path('emails/<int:pk>/', email_detail, name='email_detail'),
]
Исправляется включением аутентифицированного пользователя в набор представлений
class EmailAddressViewSet(ModelViewSet):
permission_classes = (permissions.IsAuthenticated,)
serializer_class = serializers.EmailAddressSerializer
def get_queryset(self):
return account_models.EmailAddress.objects.filter(user=self.request.user)
def perform_create(self, serializer):
serializer.save(user=self.request.user)