【问题标题】:Django Rest Framework: Unable to see view or individual filesDjango Rest Framework:无法查看视图或单个文件
【发布时间】:2020-11-03 13:22:46
【问题描述】:

我正在尝试上传文件,然后尝试在列表视图中查看文件。例如,我希望在/files/upload/ 上显示我上传的文件,并且我希望在files/upload/1 或files/upload/file-name 上查看每个单独的项目。

我已经创建了一个模型和视图,但我似乎找不到访问它的 url。例如,Django 给出的模式是

api/v1/files ^upload/$ [name='lessonpdfmodel-list']
api/v1/files ^upload/(?P<pk>[^/.]+)/$ [name='lessonpdfmodel-detail'

我唯一保存的是一个名为pokemon.pdf的文件

那个网址是什么?是localhost:8000/files/upload/pokemon.pdf吗?

我的模特是:

class LessonPDFModel(models.Model):
    title = models.CharField(max_length=80)
    description = models.CharField(max_length=225)
    upload_date = models.DateTimeField(auto_now_add=True)
    pdf = models.FileField(blank=False, null=False, upload_to='pdfs/')
    icon = models.ImageField(blank=False, null=False, upload_to='images/')

    class Meta:
        ordering = ['upload_date']

    def __str__(self):
        return f"{self.title}"

我的观点是:

class LessonPDFViewSet(ModelViewSet):
    queryset = LessonPDFModel.objects.all()
    serializer_class = LessonPDFModelSerializer

我的序列化器是:

class LessonPDFModelSerializer(serializers.ModelSerializer):
    # file_uploaded = FileField()

    class Meta:
        model = LessonPDFModel
        fields = ('pdf', 'description', 'upload_date')
            
    def create(self, validated_data):
        return LessonPDFModel.object, create(**validated_data)

我的网址是:

router = routers.SimpleRouter()
router.register('upload', LessonPDFViewSet)

urlpatterns = [
    path('', include(router.urls)),
]

【问题讨论】:

    标签: django django-models django-rest-framework django-views


    【解决方案1】:

    我认为您的网址应该是localhost:8000/pdfs/pokemon.pdf。

    因为 Django 将模型数据保存到媒体文件夹中。

    别忘了在 settings.py 和 urls.py 中设置媒体路径

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      • 2019-02-23
      • 2017-07-20
      • 1970-01-01
      • 1970-01-01
      • 2016-09-30
      • 2020-02-06
      相关资源
      最近更新 更多