django文件上传 - 隐藏编辑模板中当前显示的图像链接

时间:2015-02-18 08:40:18

标签: python django image file-upload

我有一个测试模板,允许用户将上传的文件图像以及图像标题作为字段添加到用户帐户。这工作正常。

我现在正尝试允许用户编辑已上传的文件图像和图像标题详细信息。

是否可以隐藏图像链接,而是将图像显示在其位置?

我已阅读django docs,已搜索SO&谷歌和工作2天半,但我仍然无法解决这个问题。

似乎有很多关于如何上传新文件图片的信息,但没有关于如何编辑已经上传的文件图像的信息。

这是我的models.py代码:

def _get_document_upload_location(instance, filename):
"""
Using a function instead of a lambda to make migrations happy. DO NOT remove or rename this function in the future, as it will break migrations.
@param instance: model instance that owns the FileField we're generating the upload filename for.
@param filename: Original file name assigned by django.
"""
return 'attachments/%d/%s' % (instance.user.id, uuid.uuid4())

class AttachmentDetails(models.Model, FillableModelWithLanguageVersion):
    user = models.ForeignKey(User)
    language_version = models.ForeignKey('LanguageVersion')
    attachment_document = models.FileField(upload_to=_get_document_upload_location)
    attachment_title = models.CharField(null=False, blank=False, max_length=250)
    attachment_timestamp_added = models.DateTimeField(auto_now_add=True, auto_now=False)
    attachment_timestamp_updated = models.DateTimeField(auto_now=True, auto_now_add=False)

这是我的views.py文件代码:

def attachment_details_edit(request, attachment_details_id):
    try:
        attachment_details = AttachmentDetails.objects.get(pk=attachment_details_id, user=request.user)
    except AttachmentDetails.DoesNotExist:
        return redirect(settings.MENU_DETAIL_LINK_ATTACHMENT_DETAILS)
    language_versions = LanguageVersion.objects.filter(user=request.user).select_related('language_version')
    available_languages = get_available_language_details(language_versions, request.user.userprofile.language_preference)
    attachment_details_num = request.user.attachmentdetails_set.count()
    language_code = attachment_details.language_version.language_code
    language_code_disabled = attachment_details.language_version.language_code_disabled
    language_preference = request.user.userprofile.language_preference
    if language_code_disabled:
        return redirect(settings.MENU_DETAIL_LINK_ATTACHMENT_DETAILS)
    if request.method == 'GET':
        language_code = attachment_details.language_version.language_code
        form = AttachmentDetailsForm(
                available_languages,
                language_preference=request.user.userprofile.language_preference,
                file_required=False,
                initial=dict(
                    model_to_dict(attachment_details),
                    language_code=language_code
                )
        )
    elif request.method == 'POST':
        form = AttachmentDetailsForm(
            available_languages,
            language_preference,
            False,  # file_required
            request.POST,
            request.FILES
        )
        if form.is_valid():
            cd = form.cleaned_data
            if cd['attachment_document'] is not None:
                print 'removing previously uploaded file'
                attachment_details.attachment_document.delete(save=False)
            attachment_details.fill(cd)
            attachment_details.save()
            messages.success(request, _('successfully updated.'))
            return redirect(settings.MENU_DETAIL_LINK_ATTACHMENT_DETAILS)

修改

以下是我试图向用户隐藏的示例 - 代替链接,显示实际上传的文件图像。 下面的图片是django admin,但我想隐藏链接并在编辑模板中显示上传的图片:

Supress the Currently prompt and uploaded file link

我有一篇相关的帖子here

3 个答案:

答案 0 :(得分:1)

要隐藏当前显示的图像链接,您可以简单地覆盖 get_context(以下是 ClearableFileInput 的示例,它类似于 FileInput)。

在寻找此类解决方案时检查源代码非常有用。

Django 是一个开源模块,因此您可以在 GitHub 上查找源代码: https://github.com/django/django/blob/main/django/forms/widgets.py

class ClearableFileInputCustom(forms.ClearableFileInput):
    def get_context(self, name, value, attrs):
        context = super().get_context(name, value, attrs)
        context['widget']['is_initial'] = False
        return context

答案 1 :(得分:0)

我在一个旧项目中使用了this snippet。它不是很好,因为你必须刷新页面/保存模型,但它做了我认为你想要的。

窗口小部件:

class AdminImageWidget(forms.FileInput):                                    
    """A ImageField Widget for admin that shows a thumbnail."""             

    def __init__(self, attrs={}):   # pylint: disable=E1002,W0102           
        super(AdminImageWidget, self).__init__(attrs)                       

    def render(self, name, value, attrs=None):  # pylint: disable=E1002     
        output = []                                                         
        css = {'style': 'clear:left;float:left;margin:1em 1em 0 0;'}        
        output.append(super(AdminImageWidget, self).render(name, value,     
                                                           attrs=css))      
        if value and hasattr(value, "url"):                                 
            output.append(('<a target="_blank" href="%s">'                  
                           '<img src="%s" alt="" '                          
                           'style="float:left;border:1px solid black;" /></a> '
                           % (value.url, value.url)))                       
        return mark_safe(u''.join(output)) 

在管理员中使用它:

class SomeAdminForm(forms.ModelForm):
    class Meta:
        model = MyModel
        widgets = {
            'my_image_field_name': AdminImageWidget(),
        }

class SomeAdmin(admin.ModelAdmin):
    form = SomeAdminForm

答案 2 :(得分:0)

您必须在模板中设置 img 标记的 src 属性才能成功显示图像。

<img src="{{attachment_details.file_url}}"/>

{{attachment_details.file_url}}当然必须替换为您正在检索文件网址。