我正在使用django restapi框架并尝试做crud,我完成了insert,update,select操作,但是无法删除记录。如果有人能告诉我应该朝哪个方向去解决这个问题,我对此一无所知,我真的很高兴。
urls.py 我尝试使用url版本和路径版本
path('user/profile/add', views.AddProfile.as_view(), name='user_profile_add'),
# path('user/profile/delete/<int:id>', views.DeleteProfile.as_view(), name='user_profile_delete'),
url(r'^user/profile/(?P<pk>\d+)/delete/$', views.DeleteProfile.as_view(), name='user_profile_add'),
views.py
class DeleteProfile(APIView):
permission_classes = (IsAuthenticated,)
def get_object(self, pk):
try:
return UserProfile.objects.get(pk=pk)
except UserProfile.DoesNotExist:
raise Http404
def delete(self, request, pk):
userprofile = self.get_object_or_404(id=pk)
userprofile.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
serializers.py
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ('id', 'userid', 'accounttype')
models.py
from django.shortcuts import render, redirect, get_object_or_404, render_to_response
from .models import UserProfile
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import serializers
from rest_framework import status
class UserProfile(models.Model):
id = models.AutoField(primary_key=True, verbose_name='PID')
userid = models.BigIntegerField(verbose_name='UID')
accounttype = models.CharField(max_length=20, verbose_name='AccType')
list_display = ('id', 'accounttype', 'userid')
我将views.py更改为
class DeleteProfile(APIView):
permission_classes = (IsAuthenticated,)
def get_object(self, pk):
try:
return UserProfile.objects.get(pk=pk)
except ObjectDoesNotExist:
raise Http404
def delete(self, request, pk, format=None):
userprofile = self.get_object(pk)
userprofile.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
并从终端获取此错误:
response = handler(request, *args, **kwargs)
File "D:\Only One Will Live - 3\dysapp\views.py", line 329, in delete
userprofile = self.get_object(pk)
File "D:\Only One Will Live - 3\dysapp\views.py", line 324, in get_object
return UserPorfile.objects.get(pk=pk)
NameError: name 'UserPorfile' is not defined
[27/Jun/2019 11:28:06] "DELETE /user/profile/37/delete/ HTTP/1.1" 500 18477
当前错误:
response = handler(request, *args, **kwargs)
File "D:\Only One Will Live - 3\dysapp\views.py", line 329, in delete
userprofile = self.get_object(pk)
File "D:\Only One Will Live - 3\dysapp\views.py", line 324, in get_object
return UserProfile.objects.get(pk=pk)
AttributeError: type object 'UserProfile' has no attribute 'objects'
[27/Jun/2019 11:42:16] "DELETE /user/profile/37/delete/ HTTP/1.1" 500 18525
答案 0 :(得分:0)
from django.core.exceptions import ObjectDoesNotExist
from django.shortcuts import get_object_or_404
......
try:
# try something
except ObjectDoesNotExist:
# do something
#### Or use the following
get_object_or_404(UserProfile, pk=pk)
答案 1 :(得分:0)
”“我认为您已经在视图文件中定义了一个类, 名为UserProfile,因此将覆盖您导入的模型。 将该视图称为其他视图。 “丹尼尔·罗斯曼
解决了。