首页 \ 问答 \ Django Rest框架文件上传(Django Rest Framework File Upload)

Django Rest框架文件上传(Django Rest Framework File Upload)

我使用Django Rest Framework和AngularJs来上传文件。 我的视图文件看起来像这样。

class ProductList(APIView):
    authentication_classes = (authentication.TokenAuthentication,)
    def get(self,request):
        if request.user.is_authenticated(): 
            userCompanyId = request.user.get_profile().companyId
            products = Product.objects.filter(company = userCompanyId)
            serializer = ProductSerializer(products,many=True)
            return Response(serializer.data)

    def post(self,request):
        serializer = ProductSerializer(data=request.DATA, files=request.FILES)
        if serializer.is_valid():
            serializer.save()
            return Response(data=request.DATA)

作为最后一行的post方法应该返回所有的数据,应该在那里写什么,或者如何检查那里是否有任何请求.FILES,以及如何序列化文件或怎样使用Parser? 请帮忙..


I am using Django Rest Framework and AngularJs to upload a file. My view file looks like this:

class ProductList(APIView):
    authentication_classes = (authentication.TokenAuthentication,)
    def get(self,request):
        if request.user.is_authenticated(): 
            userCompanyId = request.user.get_profile().companyId
            products = Product.objects.filter(company = userCompanyId)
            serializer = ProductSerializer(products,many=True)
            return Response(serializer.data)

    def post(self,request):
        serializer = ProductSerializer(data=request.DATA, files=request.FILES)
        if serializer.is_valid():
            serializer.save()
            return Response(data=request.DATA)

As the last line of post method should return all the data, I have several questions:

  • how to check if there is anything in request.FILES?
  • how to serialize file field?
  • how should I use parser?

原文:https://stackoverflow.com/questions/20473572
更新时间:2022-04-10 19:04

最满意答案

Facebook有一个Swift SDK,你可能会发现它比Objective-C(他们刚刚称之为iOS)更容易使用。 试着查看这里的文档:

https://developers.facebook.com/docs/swift

另外,请按照(其他)iOS SDK中描述的步骤开始:

https://developers.facebook.com/docs/ios/getting-started/

这是我可以开始工作的最小应用程序委托(请注意,Swift SDK缺少iOS SDK中存在的FB前缀):

import UIKit
import FacebookCore

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
        SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
        return true
    }

    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
        return SDKApplicationDelegate.shared.application(app, open: url, options: options)
    }

}

并确保在Info.plist添加所有必需的密钥,否则您将无法获得身份验证。


Facebook has a Swift SDK you might find easier to use than the Objective-C one (which they just call iOS). Try looking around the documentation here:

https://developers.facebook.com/docs/swift

Also, follow the steps described in the (other) iOS SDK to get started:

https://developers.facebook.com/docs/ios/getting-started/

This is the minimal app delegate I could get to work (notice the Swift SDK is missing the FB prefixes that exist in the iOS SDK):

import UIKit
import FacebookCore

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
        SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
        return true
    }

    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
        return SDKApplicationDelegate.shared.application(app, open: url, options: options)
    }

}

And be sure to add all the required keys in your Info.plist or else you won't get authentication to work at all.

相关问答

更多
  • Facebook有一个Swift SDK,你可能会发现它比Objective-C(他们刚刚称之为iOS)更容易使用。 试着查看这里的文档: https://developers.facebook.com/docs/swift 另外,请按照(其他)iOS SDK中描述的步骤开始: https://developers.facebook.com/docs/ios/getting-started/ 这是我可以开始工作的最小应用程序委托(请注意,Swift SDK缺少iOS SDK中存在的FB前缀): import ...
  • 如果您将其作为框架引入,则无需将其添加到桥接标头中。 而是将“import FBSDKLoginKit”添加到swift文件的顶部,它将识别这些类。 If you brought it in as a framework then you don't need to add it into your bridging header. Instead add "import FBSDKLoginKit" to the top of your swift file and it will recognize t ...
  • 您必须将Bolt框架添加到Xcode项目中。 出于某种原因,iOS的Facebook快速入门指南不再说了。 只需将Bolt从您下载的facebook SDK拖放到XCode中,如FBSDKCoreKit等。 You have to add the Bolt framework to your Xcode project. For some reason the Facebook quick start guide for iOS doesn't say that anymore. Just drag & d ...
  • 您可以使用Facebook提供的FBSDKProfilePictureView ,而不是自己获取所有图像。 您只需设置用户配置文件ID,它就会为您加载图片。 这应该可以改进,因为它不必等待所有图像在显示之前加载,并且在滚动tableview时也会异步加载它们。 Instead of fetching all the images by yourself, you could use Facebook provided FBSDKProfilePictureView. You only have to set ...
  • FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email, gender"]) .startWithCompletionHandler({ (connection, result, error) -> Void in }) FBSDKGraphRequest(graphPath: "me", param ...
  • 那可能吗? 是。 Facebook应用程序是唯一的解决方案吗? 如果你想与Facebook联系,那么是的。 Facebook集团墙怎么样? 不确定你是什么意思。 Is that possible? Yes. And is the Facebook application only solution? If you are trying to connect with Facebook, then yes. What about Facebook group wall? Not sure what you m ...
  • Koala是一个与Facebook的Graph API交互的宝石,也可以处理Facebook OAuth。 Koala在Github上有一些很好的例子,但如果你喜欢Ryan Bates在Railscasts Pro #361和#363中介绍Koala和Facebook的Graph API。 两者都是付费剧集。 Omniauth是处理许多不同OAuth提供商(包括Facebook)的绝佳宝石。 Ryan Bates在几集中介绍了它。 Koala is a gem that interacts with Fac ...
  • func loginButton(_ loginButton:FBSDKLoginButton!,didCompleteWith result:FBSDKLoginManagerLoginResult!,error:Error!){print(“Login buttoon clicked”) let graphRequest:FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"first_name, ge ...
  • 您可能需要考虑在GWT后端代码中使用socialauth 。 我目前将此用于G +和Facebook集成服务器端。 You might want to consider using socialauth in your GWT backend code. I currently use this for G+ and Facebook integration server side.
  • facebookUser.facebook未定义你需要声明它,示例: facebookUser.facebook = {} Actually I found what was wrong I was using the wrong model. Changed from facebookModel to userModel. Fixed the problem.

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)