English 中文(简体)
如何定制Django的一个植被的html产出?
原标题:How can i customize the html output of a widget in Django?

I couldn t find this in the docs, but think it must be possible. I m talking specifically of the ClearableFileInput widget. From a project in django 1.2.6 i have this form:

# the profile picture upload form
class ProfileImageUploadForm(forms.ModelForm):
    """
    simple form for uploading an image. only a filefield is provided
    """
    delete = forms.BooleanField(required=False,widget=forms.CheckboxInput())

    def save(self):
        # some stuff here to check if "delete" is checked
        # and then delete the file
        # 8 lines

    def is_valid(self):
        # some more stuff here to make the form valid
        # allthough the file input field is empty
        # another 8 lines

    class Meta:
        model = SocialUserProfile
        fields = ( image ,)

i 然后使用该模板代码:

<form action="/profile/edit/" method="post" enctype="multipart/form-data">
    Delete your image:
<label> {{ upload_form.delete }} Ok, delete </label>
<button name="delete_image" type="submit" value="Save">Delete Image</button>
    Or upload a new image:
    {{ upload_form.image }}
    <button name="upload_image" type="submit" value="Save">Start Upload</button>
{% csrf_token %}
</form>

由于Django 1.3.1现在将可清除的液体投入用作缺损植被,即表面上可以绕过我形式的16条线。 除此以外,也只是缩短了类似形式代码:

# the profile picture upload form
class ProfileImageUploadForm(forms.ModelForm):
    """
    simple form for uploading an image. only a filefield is provided
    """

    class Meta:
        model = SocialUserProfile
        fields = ( image ,)

这将给我带来一种良好感觉,即,我不太定制的形式编码,而且可以依靠Django的建筑。

I would, of course, like to keep the html-output the same as before. When just use the existing template code, such things like "Currently: somefilename.png" pop up at places where i do not want them.

象<条码>{上载_form.image.file>/code”等进一步铺设表格似乎不可行。 我所想的下一个事情是写出一种习俗。 这将完全违背我为尽可能取消尽可能多的定制守则所作的努力。

在这种情况下,什么是最简单的事?

最佳回答

首先,在一份电文中建立一个<代码>widgets.py文档。 举例来说,我把你打成<条码>。 AdminImageWidget category thatlif AdminFileWidget/code>。 基本上,我想有一个图像上上载现场,显示目前在<代码><img src=”/> tag,而不是仅仅输出文档路径。

http://www.ohchr.org。

from django.contrib.admin.widgets import AdminFileWidget
from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe
import os
import Image

class AdminImageWidget(AdminFileWidget):
    def render(self, name, value, attrs=None):
        output = []
        if value and getattr(value, "url", None):

            image_url = value.url
            file_name=str(value)

            # defining the size
            size= 100x100 
            x, y = [int(x) for x in size.split( x )]
            try :
                # defining the filename and the miniature filename
                filehead, filetail  = os.path.split(value.path)
                basename, format        = os.path.splitext(filetail)
                miniature                   = basename +  _  + size + format
                filename                        = value.path
                miniature_filename  = os.path.join(filehead, miniature)
                filehead, filetail  = os.path.split(value.url)
                miniature_url           = filehead +  /  + miniature

                # make sure that the thumbnail is a version of the current original sized image
                if os.path.exists(miniature_filename) and os.path.getmtime(filename) > os.path.getmtime(miniature_filename):
                    os.unlink(miniature_filename)

                # if the image wasn t already resized, resize it
                if not os.path.exists(miniature_filename):
                    image = Image.open(filename)
                    image.thumbnail([x, y], Image.ANTIALIAS)
                    try:
                        image.save(miniature_filename, image.format, quality=100, optimize=1)
                    except:
                        image.save(miniature_filename, image.format, quality=100)

                output.append(u  <div><a href="%s" target="_blank"><img src="%s" alt="%s" /></a></div> %s   % 
                (miniature_url, miniature_url, miniature_filename, _( Change: )))
            except:
                pass
        output.append(super(AdminFileWidget, self).render(name, value, attrs))
        return mark_safe(u  .join(output))

因此,这里发生的事情是什么?

  1. I import an existing widget (you may be starting from scratch, but should probably be able to extend ClearableFileInput if that s what you are starting with)
  2. I only want to change the output/presentation of the widget, not the underlying logic. So, I override the widget s render function.
  3. in the render function I build the output I want as an array output = [] you don t have to do this, but it saves some concatenation. 3 key lines:
    • output.append(u <div><a href="%s" target="_blank"><img src="%s" alt="%s" /></a></div> %s % (miniature_url, miniature_url, miniature_filename, _( Change: ))) Adds an img tag to the output
    • output.append(super(AdminFileWidget, self).render(name, value, attrs)) adds the parent s output to my widget
    • return mark_safe(u .join(output)) joins my output array with empty strings AND exempts it from escaping before display

我如何利用这一点?

class SomeModelForm(forms.ModelForm):
    """Author Form"""
    photo = forms.ImageField(
        widget = AdminImageWidget()
    )

    class Meta:
        model = SomeModel

页: 1

class SomeModelForm(forms.ModelForm):
    """Author Form"""
    class Meta:
        model = SomeModel
        widgets = { photo  : AdminImageWidget(),}

让我们:

“admin

问题回答

暂无回答




相关问题
How to get two random records with Django

How do I get two distinct random records using Django? I ve seen questions about how to get one but I need to get two random records and they must differ.

Moving (very old) Zope/Plone Site to Django

I am ask to move data from a (now offline) site driven by Plone to a new Django site. These are the version informations I have: Zope Version (unreleased version, python 2.1.3 ) Python Version 2.1....

Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

Flexible pagination in Django

I d like to implement pagination such that I can allow the user to choose the number of records per page such as 10, 25, 50 etc. How should I go about this? Is there an app I can add onto my project ...

is it convenient to urlencode all next parameters? - django

While writing code, it is pretty common to request a page with an appended "next" query string argument. For instance, in the following template code next points back to the page the user is on: &...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

热门标签