【问题标题】:Django: How to Use upload_to=function with ModelFormDjango:如何在 ModelForm 中使用 upload_to=function
【发布时间】:2010-03-07 18:36:14
【问题描述】:

目标是动态更新upload_to,以便用户上传的文件存储在取决于用户的目录位置。网上有几个这样的例子,但没有一个使用 ModelForm。查看代码 sn-ps 的两个问题,一个是我得到了 instance.user 值的空字符串,当我尝试修复它时,表单无效。

# models.py

def get_file_path( instance, filename ):
    # make the filepath include the signed in username
    print "inst: %s" % instance.__dict__.keys()
    print "inst:user:%s" % instance.user   # <-- This is empty string!!
    print "file: %s" % filename
    return "%s/myapp/%s/%s" % ( settings.MEDIA_ROOT, instance.user, filename )

class trimrcUpload(models.Model):
    user = models.CharField( max_length = 20 )
    inputFile = models.FileField( upload_to = get_file_path )


# forms. py

class trimrcUploadForm(ModelForm):

    class Meta:
        model = trimrcUpload
        exclude = ( 'resultFile', 'numTimesProcessed' )

# views.py

def myapp_upload( request, username, template_name="myapp/myapptemplate.html" ):

    dummy = trimrcUpload( user=username )
    if request.POST:
        form = trimrcUploadForm( request.POST, request.FILES, instance=dummy )
        if form.is_valid():
            success = form.save()
            success.save()

    # form is not valid, user is field is "required"
    # the user field is not displayed in the template by design,
    # it is to be populated by the view (above).

# http://docs.djangoproject.com/en/1.0/topics/forms/modelforms/
# about halfway down there is a "Note" section describing the use of dummy.

【问题讨论】:

    标签: django modelform


    【解决方案1】:

    我想您的问题来自尝试使用用户名填充模型的用户属性。如果上传表单将始终由登录用户使用,您可以使用它来代替:

    dummy = trimrcUpload( user=request.user )
    

    否则,如果你仍然想像现在这样传递用户名,你可以尝试类似:

    try:
        user = User.objects.get(username=username)
        dummy = trimrcUpload( user=user )
    except User.DoesNotExist:
        # Probably have to set some kind of form error
    

    我建议使用第一个选项,这样您就不必将用户名传递给视图。

    【讨论】:

    • 但是用户名是一个有效的字符串。我的天啊。我不知道为什么,但它现在完全可以工作了。我最好将此标记为已回答。
    【解决方案2】:

    问题中的原始代码确实有效。

    【讨论】:

      猜你喜欢
      • 2011-06-27
      • 2020-07-19
      • 2012-02-09
      • 2015-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-16
      • 2012-08-01
      相关资源
      最近更新 更多