Django Admin 中的图库预览

发布于 2024-11-27 04:37:40 字数 893 浏览 1 评论 0原文

我想在我的管理员中显示所选的图库。我不太有能力编写自定义字段,也找不到任何有关它的详细记录指南。

至于我的问题,我已经编写了基本类,例如:

class GalleryViewWidget(forms.TextInput):
    def render(self,name,value,attrs):
        rendered = super(GalleryViewWidget, self).render(name, value, attrs)
        return rendered + mark_safe(....)

class ProductModelForm(forms.ModelForm):
    information = forms.CharField(widget=forms.Textarea)
    gallery = GalleryViewWidget
    class Media:
        css = {
            'all': (settings.MEDIA_URL + 'css/preview.css',)
        }
        js=(
                "http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js",
                settings.MEDIA_URL + 'js/preview.js',
            )
    class Meta:
        model = Product

在我的preview.js文件中,我想发送一个ajax请求,问题是我不知道在哪里处理这个ajax调用。在我的 ProductModelForm 中?

我真的很感激,如果有人给我任何关于如何处理这个ajax事情或在我的管理员中显示所选画廊的其他方法的知识?

I want to display the selected gallery in my admin. I'm not very capable of writing custom fields and couldn't find any well documented guidelines about it.

As for my question, I've written basic classes such as:

class GalleryViewWidget(forms.TextInput):
    def render(self,name,value,attrs):
        rendered = super(GalleryViewWidget, self).render(name, value, attrs)
        return rendered + mark_safe(....)

class ProductModelForm(forms.ModelForm):
    information = forms.CharField(widget=forms.Textarea)
    gallery = GalleryViewWidget
    class Media:
        css = {
            'all': (settings.MEDIA_URL + 'css/preview.css',)
        }
        js=(
                "http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js",
                settings.MEDIA_URL + 'js/preview.js',
            )
    class Meta:
        model = Product

In my preview.js file, I want to send an ajax request, the problem is I don't know where to handle this ajax call. In my ProductModelForm ?

I'd really appreciate that if anyone gives me any knowledge about how to handle this ajax thing or another way to display selected gallery in my admin ?

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

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

发布评论

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

评论(3

ぃ双果 2024-12-04 04:37:40

在这里我看到了一个关于它的有点过时的教程......
它会创建您自己的缩略图。现在您需要使用“sorl-thumbnail”来生成缩略图,并且存储它更容易、更正确恕我直言...

尽管如此,这是一个有关如何在管理中构建照片预览的教程。您可以使用它或通过 AJAX 调用增强它。但恕我直言,这没有必要......

PS 最好从一开始就下载这个应用程序的完整源代码。

所以...文章:

Django 教程:照片管理器和共享应用程序第一部分:增强管理.

Here I saw a bit outdated tutorial about it...
It creates your own thumbnails. You need to use "sorl-thumbnail" now-days for thumbnails generation and storing it's a bit easier and more right way IMHO...

Nevertheless it's a tutorial of how to build a photo previews in admin. You could use it or enhance it with AJAX calls. But IMHO again it's not necessary...

P.S. It's better to download full sources of this app from the start.

so... article:

Django Tutorial: Photo Organizer and Sharing App Part I. Enhancing Admin.

享受孤独 2024-12-04 04:37:40

您的小部件(具有处理文件名中后缀的额外功能)可能如下所示:

class ImageThumbnailWidget(forms.FileInput):

    def __init__(self, postfix=None, attrs={}):
         self.postfix = postfix
         super(ImageThumbnailWidget, self).__init__(attrs)

    def render(self, name, value, attrs=None):
        output = []
        if value and hasattr(value, "url"):
            img_path = value.url.split('/')[:-1]
            img_path = "/".join(img_path)
            img_name = value.url.split('/')[-1]
            if self.postfix:
                name_parts = img_name.split(".")
                ext = name_parts.pop()
                img_name_start = "_".join(name_parts)
                img_name = "%s%s.%s" % (img_name_start, self.postfix, ext)
            output.append('%s<br/><img src="%s/%s" /> <br />%s ' % 
                (_('Currently:'), img_path, img_name, _('Change:')))
        output.append(super(ImageThumbnailWidget, self).render(name, value, attrs))
        return mark_safe(u''.join(output))

希望有帮助。如果它不符合您的需求,请写一些更多细节,我会尝试找出一些东西(我想知道您到底想在哪里显示图库的预览 - 是“changelist”还是“change_view”产品的,其中有带图像的内联表单集)。

Your widget (with extra feature of handling postfix in file name) might look like this:

class ImageThumbnailWidget(forms.FileInput):

    def __init__(self, postfix=None, attrs={}):
         self.postfix = postfix
         super(ImageThumbnailWidget, self).__init__(attrs)

    def render(self, name, value, attrs=None):
        output = []
        if value and hasattr(value, "url"):
            img_path = value.url.split('/')[:-1]
            img_path = "/".join(img_path)
            img_name = value.url.split('/')[-1]
            if self.postfix:
                name_parts = img_name.split(".")
                ext = name_parts.pop()
                img_name_start = "_".join(name_parts)
                img_name = "%s%s.%s" % (img_name_start, self.postfix, ext)
            output.append('%s<br/><img src="%s/%s" /> <br />%s ' % 
                (_('Currently:'), img_path, img_name, _('Change:')))
        output.append(super(ImageThumbnailWidget, self).render(name, value, attrs))
        return mark_safe(u''.join(output))

Hope it helps. If it doesn't fit your needs, write some more details and I'll try to figure out something (I'd like to know where exactly do you want to show the preview of gallery - is it "changelist" or "change_view" of product, where you have inline formset with images).

岛歌少女 2024-12-04 04:37:40

我将回答您的问题的在哪里放置我的 Admin/ModelForm Ajax 视图?部分,对于图库部分,您可以查看 照片记录

至于创建从管理表单调用的视图,我发现创建简单的自定义视图是最简单的。在您的 Javascript 代码中,您只需使用特定于您的应用的数据调用 {% url my_ajax_view %} 即可。

例如(ajax外键搜索的修改版本):

class ForeignKeySearchInput(forms.HiddenInput):
    """
    A Widget for displaying ForeignKeys in an autocomplete search input 
    instead in a ``select`` box.
    """
    [ ... stuff removed ... ]
    def render(self, name, value, attrs=None):
        [ ... snip ... ]
        context = Context({
            'search_url': reverse('tools_autocomplete_search'),
            'model_name': self.rel.to._meta.module_name,
            'app_label': self.rel.to._meta.app_label,
            [ ... snip ... ]
        })
        template = loader.get_template('admin/widgets/foreignkeysearchinput.html')
        return rendered + mark_safe(template.render(context))

这里的关键是将所需的数据交给widget模板,然后widget模板使用这些数据正确调用ajax回调。

实际的视图就像你的问题一样简单(或复杂)。

def ajax_search(request):
    """
    Searches in the fields of the given related model and returns the 
    result as a simple string to be used by the jQuery Autocomplete plugin
    """
    query = request.GET.get('q', None)
    app_label = request.GET.get('app_label', None)
    model_name = request.GET.get('model_name', None)
    search_fields = request.GET.get('search_fields', None)

    [ ... snip ... ]
    return HttpResponse(simplejson.dumps(data, indent=2))

或者,您可以将 ajax 视图嵌入到 ModelAdmin 子类(或 Mixin)中,但如果您不想搞乱 django.contrib.admin 路由的内部结构,那么上面的方法会更容易。

I'll answer the Where do I put my Admin/ModelForm Ajax views? part of your question, for the gallery part maybe have a look at photologue.

As for creating views which are called from the admin forms, I found creating simple custom views the easiest. In your Javascript code you just call {% url my_ajax_view %} with data specific to your app.

For example (a modified version of ajaxy foreignkey search):

class ForeignKeySearchInput(forms.HiddenInput):
    """
    A Widget for displaying ForeignKeys in an autocomplete search input 
    instead in a ``select`` box.
    """
    [ ... stuff removed ... ]
    def render(self, name, value, attrs=None):
        [ ... snip ... ]
        context = Context({
            'search_url': reverse('tools_autocomplete_search'),
            'model_name': self.rel.to._meta.module_name,
            'app_label': self.rel.to._meta.app_label,
            [ ... snip ... ]
        })
        template = loader.get_template('admin/widgets/foreignkeysearchinput.html')
        return rendered + mark_safe(template.render(context))

The key here is to hand the required data to the widget template, which then uses this data to call the ajax callback correctly.

The actual view then is as simple (or complicated) as your problem.

def ajax_search(request):
    """
    Searches in the fields of the given related model and returns the 
    result as a simple string to be used by the jQuery Autocomplete plugin
    """
    query = request.GET.get('q', None)
    app_label = request.GET.get('app_label', None)
    model_name = request.GET.get('model_name', None)
    search_fields = request.GET.get('search_fields', None)

    [ ... snip ... ]
    return HttpResponse(simplejson.dumps(data, indent=2))

Alternatively you can embedd ajax view into a ModelAdmin subclass (or a Mixin), but if you don't want to muck about with the internals of django.contrib.admin routing the above is way easier.

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