当我尝试使用url http://localhost:8000/api/user/profile/2
通过user_id=2
为User
创建UserProfile
时,得到的结果是detail : not found
models.py:
class User(AbstractBaseUser, PermissionsMixin, Base):
user_id = models.AutoField(primary_key=True)
email = models.EmailField(db_index=True, max_length=100, unique=True)
is_advisor = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
UserProfile:
class UserProfile(Base):
profile_id = models.AutoField(primary_key=True)
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_profile')
first_name = models.CharField(null=True, blank=True, max_length=100)
last_name = models.CharField(null=True, blank=True, max_length=100)
UserProfileSerializer:
class UserProfileSerializer:
class Meta:
model = UserProfile
fields = "__all__"
views.py:
class UserProfileViewSet(viewsets.ModelViewSet):
queryset = UserProfile.objects.all()
parser_classes = (MultiPartParser, )
serializer_class = UserProfileSerializer
lookup_field = 'user'
urls.py:
router = SimpleRouter(trailing_slash=False)
router.register(r'user', UserViewSet)
router.register(r'user/profile', UserProfileViewSet)
urlpatterns = [
path(r'user/activate', ActivateUser.as_view(), name='activate_user'),
] + router.urls
发布于 2021-10-05 22:01:37
对于ModelViewSets
,api/user/profile/2
对应于一个详细视图。这意味着该对象应该已经存在。
由于用户2还没有配置文件(您希望创建一个),因此会出现404/not found错误。
有许多方法可以解决这个问题,但要支持为用户创建配置文件,而不需要在当前代码中进行更改,您只需在请求数据中使用用户id发布到/api/user/profile
即可:
帖子:http://localhost:8000/api/user/profile
{
"user": 2,
"first_name": "Tannisha",
"last_name": "Hill"
}
发布于 2021-10-12 03:01:39
……=路径(‘’,包含(router.urls)),…模式
发布于 2021-10-05 20:48:21
我看到相当多的初学者的小错误。我建议您采取较小的步骤,并确保每个部分在您前进的过程中都正常工作。
确保您的用户模型在设置中设置为AUTH_USER_MODEL,并检查您是否可以在shell中创建和查看至少一个用户,甚至在您担心DRF序列化等问题之前。
然后,由于您有一个自定义的用户模型,所以您不太可能需要或想要一个UserProfile对象-它的存在通常是为了扩展现有的用户模型,而当您有了自己的模型时,您可能只需要对其进行扩展,以使事情尽可能简单。
按照您想要的方式获取用户字段,并尝试在shell中创建用户。django shell是一个优秀的开发和学习工具。
一旦您可以在shell中创建用户并列出他们(例如使用User.objects.all()),您就可以考虑添加一个序列化程序。这将需要从合适的DRF默认序列化程序继承一些行为。将其添加到您的urls并使用DRF进行测试(您需要在您的设置中使用'rest_framework‘)。
您也可以在shell中测试序列化程序,但DRF api测试器在您开始使用时非常方便,因此您可能希望直接添加url并使用它。您将能够查看和发布您的更改。lookup_field不是必需的。
在为模型添加urls时,不要使用斜杠来分隔模型名称。斜杠表示不同的部分,型号名称是url的一个有意义的部分。如果您想拆分名称,可以使用下划线(例如"api/user_profile/")。
保留DRF尾部斜杠,除非您有很好的理由不需要它们。如果你忘记输入它们,Django会自动附加它们作为错误处理的一部分。
我希望这足以让你解脱。
https://stackoverflow.com/questions/69429861
复制相似问题