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

Neo*_*Neo 9 python django file-upload django-forms django-file-upload

我有一个模特,有FileField.当我在视图中编辑此模型时,我想要更改其"视图"中FileField显示的"当前"值.让我解释.

models.py:

class DemoVar_model(models.Model):
    ...
    Welcome_sound=models.FileField(upload_to='files/%Y/%m/%d')
Run Code Online (Sandbox Code Playgroud)

forms.py:

class DemoVar_addform(ModelForm):
    ...
    class Meta:
        model = DemoVar_model        
Run Code Online (Sandbox Code Playgroud)

views.py:

soundform = DemoVar_addform(instance=ivrobj)
....
return render_to_response(template,{'soundform':soundform}, ....)
Run Code Online (Sandbox Code Playgroud)

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

Welcome sound: Currently: welcome_files/2011/04/27/15_35_58_ojCompany.wav.mp3 
Change : <Choose File button>
Run Code Online (Sandbox Code Playgroud)

我想更改此"当前"值,该值描述文件在我的服务器上退出时的整个路径.我想将此字符串修剪为没有路径的文件名.我该如何做到这一点?

Gui*_*vin 11

您需要覆盖当前使用的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)
Run Code Online (Sandbox Code Playgroud)

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

class DemoVar_addform(ModelForm):
    ...
    class Meta:
        model = DemoVar_model
        widgets = {
            'Welcome_sound': ShortNameClarableFileInput,
        }                    
Run Code Online (Sandbox Code Playgroud)

这应该够了吧.


Dra*_*s C 9

如果你想要一种更简单的方法并避免重写小部件的渲染逻辑,你可以做一点点破解.

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>')
Run Code Online (Sandbox Code Playgroud)

然后手动设置该字段的小部件.

class DemoVar_addform(ModelForm):

    class Meta:
        model = DemoVar_model
        widgets = {
            'Welcome_sound': ClearableFileInput,
        }   
Run Code Online (Sandbox Code Playgroud)