Django:在编辑模块时自定义FileField值

2024-10-01 22:42:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个模型,有FileField。当我在视图中编辑这个模型时,我想更改在视图窗体中显示的FileField的“当前”值。让我解释一下。在

模型.py:

class DemoVar_model(models.Model):
    ...
    Welcome_sound=models.FileField(upload_to='files/%Y/%m/%d')

表单.py:

^{pr2}$

视图.py:

soundform = DemoVar_addform(instance=ivrobj)
....
return render_to_response(template,{'soundform':soundform}, ....)

现在我想在我的视图中编辑这个模型。当我在浏览器中查看时,我看到表单显示为

Welcome sound: Currently: welcome_files/2011/04/27/15_35_58_ojCompany.wav.mp3 
Change : <Choose File button>

我想更改这个“当前”值,它描述了文件在服务器上退出时的整个路径。我想把这个字符串裁剪成不带路径的文件名。我该怎么做呢?在


Tags: topy模型路径视图编辑表单models
3条回答

Django 1.10.x或更早版本


最简单的方法是重写默认的template_substitution_valuesdjango小部件,该小部件将在以后呈现表单时使用。这是一种更干净的方法,不会导致任何不必要的代码重复。在

from os import path
from django.forms.widgets import ClearableFileInput
from django.utils.html import conditional_escape

class CustomClearableFileInput(ClearableFileInput):
    def get_template_substitution_values(self, value):
        """
        Return value-related substitutions.
        """
        return {
            'initial': conditional_escape(path.basename(value.name)),
            'initial_url': conditional_escape(value.url),
        }

然后使用表单.py如下:

^{pr2}$

Django 1.11.x或更高版本


选中ImageField / FileField Django form Currently unable to trim the path to filename。在

如果您想要一种更简单的方法,并且避免重写小部件的呈现逻辑,那么您可以进行一些修改。在

from os import path
from django import forms


class FormatString(str):

    def format(self, *args, **kwargs):
        arguments = list(args)
        arguments[1] = path.basename(arguments[1])
        return super(FormatString, self).format(*arguments, **kwargs)


 class ClearableFileInput(forms.ClearableFileInput):

     url_markup_template = FormatString('<a href="{0}">{1}</a>')

然后手动设置字段的小部件。在

^{pr2}$

您需要覆盖当前使用的ClearableFileInput,以更改它的显示方式。在

下面是新的ShortNameFileInput的代码,它继承了默认的ClearableFileInput,只在第19行做了一个更改,只显示了文件名:

from django.forms.widgets import ClearableFileInput
import os
# missing imports
from django.utils.safestring import mark_safe
from cgi import escape
from django.utils.encoding import force_unicode

class ShortNameClarableFileInput(ClearableFileInput):
    def render(self, name, value, attrs=None):
        substitutions = {
            'initial_text': self.initial_text,
            'input_text': self.input_text,
            'clear_template': '',
            'clear_checkbox_label': self.clear_checkbox_label,
        }
        template = u'%(input)s'
        substitutions['input'] = super(ClearableFileInput, self).render(name, value, attrs)

        if value and hasattr(value, "url"):
            template = self.template_with_initial
            substitutions['initial'] = (u'<a href="%s">%s</a>'
                                        % (escape(value.url),
                                           escape(force_unicode(os.path.basename(value.url))))) # I just changed this line
            if not self.is_required:
                checkbox_name = self.clear_checkbox_name(name)
                checkbox_id = self.clear_checkbox_id(checkbox_name)
                substitutions['clear_checkbox_name'] = conditional_escape(checkbox_name)
                substitutions['clear_checkbox_id'] = conditional_escape(checkbox_id)
                substitutions['clear'] = CheckboxInput().render(checkbox_name, False, attrs={'id': checkbox_id})
                substitutions['clear_template'] = self.template_with_clear % substitutions

        return mark_safe(template % substitutions)

要在表单中使用它,您必须手动设置要使用的小部件:

^{pr2}$

这应该能解决问题。在

相关问题 更多 >

    热门问题