【发布时间】:2015-12-14 19:07:51
【问题描述】:
我是 Django Rest Framework 和 Django 的新手。我有以下模型类:
class NotificationType(LogModel):
name = models.CharField(max_length=300, verbose_name="Name")
frequency = models.PositiveSmallIntegerField(
choices=NotificationFrequency.CHOICES,
verbose_name="notification_frequency")
active = models.BooleanField(default=1)
class Meta:
db_table = 'notificaiton_type'
verbose_name = 'NotificationType'
verbose_name_plural = 'NotificationTypes'
ordering = ('-id',)
def __str__(self):
return "{}{}".format(self.name, self.frequency)
@python_2_unicode_compatible
class Notification(LogModel):
notification_type = models.ForeignKey(NotificationType)
property_info = models.ForeignKey(PropertyInfo)
description = models.TextField(verbose_name="Notification Description")
action = models.TextField(blank=True, null=True)
class Meta:
db_table = 'notification'
verbose_name = 'Notification'
verbose_name_plural = 'Notifications'
ordering = ('-id',)
def __str__(self):
return "{}".format(self.description)
我的序列化器和视图集如下:
class NotificationTypeSerializer(serializers.ModelSerializer):
class Meta:
model = NotificationType
fields = ('name', 'frequency', 'active')
class NotificationSerializer(serializers.ModelSerializer):
property_info = PropertyInfoSerializer(read_only=True)
notification_type = NotificationTypeSerializer(read_only=True)
class Meta:
model = Notification
views.py:
class NotificationCRUDView(generics.ListCreateAPIView):
model = Notification
serializer_class = serializers.Notification
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)
def post(self, request, pk, property_id): #
serializer = serializers.NotificationSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
我的 urls.py 文件包含以下 url 模式:
url(r'^notification/(?P<pk>[0-9]+)/(?P<property_id>[0-9]+)/$', NotificationCRUDView.as_view(), name="notification-crud-view")
现在每当我尝试使用 url 路径进行 POST 调用时 /api/v1/notification/pk/property_id {其中 pk 和 property_id} 作为 url 参数传递。我收到上述错误。 任何人都可以帮我解决这个问题。 TIA。 :)
【问题讨论】:
-
我认为你需要修复源代码的缩进,如果不是很可读的话。
-
并包含网址详细信息。
-
你没有使用
pk和property_id传递给查看函数,DRF 不会为你处理。 -
哎哟!我的错。感谢@Saurabh 的帮助
标签: django django-rest-framework