我正在使用Django ..
以下是观点
class SettingsValues(generics.ListAPIView):
serializer_class = SettingsSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def get_queryset(self):
queryset = Settings.objects.all()
queryset = queryset.filter(user=self.request.user.id)
return queryset
class SettingsValuesUpdate(generics.UpdateAPIView):
queryset = Settings.objects.all()
serializer_class = SettingsSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def perform_update(self, serializer):
serializer.save(user=self.request.user.id)
这是我的模型
class Settings(models.Model):
user = models.OneToOneField('auth.User', related_name='settings', on_delete=models.CASCADE)
boolean1 = models.BooleanField(default=False)
boolean2 = models.BooleanField(default=False)
boolean3 = models.BooleanField(default=False)
string1 = models.CharField(max_length=100, default='No description')
我的序列化程序
class SettingsSerializer(serializers.ModelSerializer):
class Meta:
model = Settings
fields = ('id', 'boolean1', 'boolean2', 'boolean3', 'string1')
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email', 'password' ,'settings', 'image')
extra_kwargs = {'password': {'write_only': True}}
我的网址
url(r'^settings/?$', views.SettingsValues.as_view()),
url(r'^updsettings/?$', views.SettingsValuesUpdate.as_view()),
我正在使用Angular 2或邮差应用程序并不重要..当我返回设置时它工作正常。但是当我尝试更新用户设置(PUT)时,它显示错误
使用名为" pk"的URL关键字参数调用预期视图SettingsValuesUpdate。修复您的网址,或在视图上正确设置.lookup_field
属性
有什么想法吗?
修改
回答vinay kumar的回答,我的观点是
class SettingsValuesUpdate(viewsets.ModelViewSet):
queryset = Settings.objects.all()
serializer_class = SettingsSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
@detail_route(methods='PUT')
def perform_update(self, serializer):
serializer.save(user=self.request.user.id)
但仍然存在错误{" detail":" Method \" PUT \"不允许。"}
答案 0 :(得分:1)
请尝试这种方式。
from django.conf.urls import include, urls
from rest_framework import routers
from .views import SettingsValues, SettingsValuesUpdate
router = routers.SimpleRouter()
router.register(r'settings', SettingsValues, base_name='setting_values')
router.register(r'updsettings', SettingsValuesUpdate, base_name='setting_value_update')
urlpatterns = [
url(r'^', include(router.urls)),
]
答案 1 :(得分:0)
在我的情况下,我从get_queryset(self)
返回了一个对象,然后将其更改为get_object(self)
解决了我的问题