Clash Royale CLAN TAG#URR8PPP
Django IntegryError Response does not work
i am writing a rest api where users are able to register, login and add keyword. But the keyword will only be added if they equals to one of the AllowedKeyword Model. I have done all so far, but i have to catch the IntegrityError if the combination of keyword and owner already exists.
But if i try a api call it response the keyword i wanted to add (but he does not save it, which is correct) instead of Response the error.
Here is the relevant code:
apy.py
class KeywordViewSet(viewsets.ModelViewSet):
permission_classes = [permissions.IsAuthenticated, ]
serializer_class = KeywordSerializer
def get_queryset(self):
return self.request.user.keywords.all()
def perform_create(self, serializer):
try:
serializer.save(owner=self.request.user)
except IntegrityError as e:
return Response({
"IntegrityError": "This combination already exists."
})
serializers.py
def allow_keyword(key):
if AllowedKeyword.objects.filter(allowed_keyword=key).exists():
return key
else:
raise serializers.ValidationError('This Keyword ist not allowed')
class KeywordSerializer(serializers.ModelSerializer):
#keyword = serializers.StringRelatedField()
keyword = serializers.CharField(max_length=255, validators=[allow_keyword])
class Meta:
model = Keyword
fields = ('id', 'keyword', )
models.py
class AllowedKeyword(models.Model):
allowed_keyword = models.CharField(max_length=255, null=True, default=None, blank=True)
def __str__(self):
return str(self.allowed_keyword)
class Keyword(models.Model):
keyword = models.CharField(max_length=255, null=True, blank=True)
owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='keywords')
def __str__(self):
return str(self.keyword)
class Meta:
unique_together = ('keyword', 'owner')
Output if keyword is not in AllowedKeyword
{
"keyword": [
"This Keyword ist not allowed"
]
}
Output if keyword is unique and in AllowedKeyword
{
"id": 11,
"keyword": "bitcoin"
}
Outout if keyword already exists in Keyword and is in AllowedKeyword
{
"keyword": "bitcoin"
}
=> But should be the Response after catching the IntegrityError
I hope you guys could help me
Cheers
EDIT
if i use raise ValidationError instead of Response it works, but i want this error in json
EDIT 2
For more information, if i dont catch the error i get this
IntegrityError at /api/keywords/
UNIQUE constraint failed: news_keyword.keyword, news_keyword.owner_id
I just want to catch this error and response a json response
1 Answer
1
I got a idea and now i tried another way. I implemented the validate method in the serializer and now it works fine
class KeywordViewSet(viewsets.ModelViewSet):
permission_classes = [permissions.IsAuthenticated, ]
serializer_class = KeywordSerializer
def get_queryset(self):
return self.request.user.keywords.all()
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
def allow_keyword(key):
if AllowedKeyword.objects.filter(allowed_keyword=key).exists():
return key
else:
raise serializers.ValidationError('This Keyword is not allowed')
.
class KeywordSerializer(serializers.ModelSerializer):
keyword = serializers.CharField(max_length=255, validators=[allow_keyword])
class Meta:
model = Keyword
fields = ('id', 'keyword', )
def validate(self, data):
if Keyword.objects.filter(keyword=data['keyword'], owner=self.context['request'].user).exists():
raise serializers.ValidationError("combination exists")
return data
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
two owner on keyword models?
– Hemanth SP
2 days ago