Django:如何将 upload_to=function 与 ModelForm 一起使用

发布于 2024-08-24 08:39:48 字数 1438 浏览 7 评论 0原文

目标是动态更新 upload_to ,以便用户上传的文件存储在取决于用户的目录位置。网上有几个这样的例子,但没有一个使用 ModelForm。请参阅两个问题的代码片段,其中一个是我得到的 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.

The goal is to dynamically update upload_to such that user uploaded files are stored in a directory location that depends on the user. There are several examples of this online, but none using ModelForm. See the code snippets for the two problems, one is that I am getting an empty string for the instance.user value, and when I try and fix that, the form is not valid.

# 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

七七 2024-08-31 08:39:48

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

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

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

I would imagine your problem comes from trying to populate the user attribute of your model with a username. If the upload form will always be used by a logged in user, you can use this instead:

dummy = trimrcUpload( user=request.user )

Otherwise, if you still want to pass in the username like you do now, you can try something like:

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

I would recommend going with the first option which would allow you to not have to pass username to the view.

迷乱花海 2024-08-31 08:39:48

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

The original code in the question actually works.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文