I'm trying to use auth_method field from MethoID model in AgentDetails Model.But when I enter the value of primary key id in serializer for authen_method it is not being validated.
Models:
class AuthMethodID(models.Model):
auth_method = models.CharField(max_length=50, default="Google")
def __str__(self):
return self.auth_method
class AgentDetail(models.Model):
authen_method = models.ForeignKey(AuthMethodID, on_delete=models.CASCADE)
Serializer:
class AgentSerializer(serializers.ModelSerializer):
class Meta:
model = AgentDetail
fields = [
"authen_method",
]
and in views I use POST request.
Views:
@api_view(["POST"])
def create_agent(request):
if request.method == "POST":
serializer = AgentSerializer(data=request.data, many=False)
if serializer.is_valid():
serializer.save()
return Response(status=status.HTTP_200_OK)
error = Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
return error
I send this as request body, cause I added just one value in AuthMethodID model auth_method field(Google),so it could use its primarykey value as input in request body. There are other fields in AgentDetail model which I use them in request body but I have only one field in AuthMethodID model which I intend to use in requestbody as primarykey value.
{
"authen_method": 1,
}
Error:
When you send the following response as request body you must make sure the foreign model instance ( here, auth_method with id 1 ) already exists. Create a instance of AuthMethodID model first. Then again try to post the child model AgentDetail instance.
{
"authen_method": 1
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.