summaryrefslogtreecommitdiff
path: root/app/utils/widgets.py
blob: 8e390d51d6711ef801e34c1a89e3939b72ad337e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import os
from django import forms
from django.contrib import admin
from django.contrib.admin.widgets import AdminFileWidget
from django.contrib.gis.admin import OSMGeoAdmin
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
import markdown


def markdown_to_html(txt):
    md = markdown.Markdown(
        extensions=[
            'markdown.extensions.fenced_code',
            'markdown.extensions.codehilite(css_class=highlight,linenums=False)',
            'markdown.extensions.attr_list',
            'footnotes',
            'extra'
        ],
        output_format='html5',
        safe_mode=False
    )
    return md.convert(txt)


class TagListFilter(admin.SimpleListFilter):
    # Human-readable title which will be displayed in the
    # right admin sidebar just above the filter options.
    title = _('tag')

    # Parameter for the filter that will be used in the URL query.
    parameter_name = 'tag'

    def lookups(self, request, model_admin):
        """
        Returns a list of tuples. The first element in each
        tuple is the coded value for the option that will
        appear in the URL query. The second element is the
        human-readable name for the option that will appear
        in the right sidebar.
        """
        tl = []
        self.model_to_use = model_admin.model
        for t in self.model_to_use.tags.all().order_by('name'):
            tl += (t.name, t.name),
        return tl

    def queryset(self, request, queryset):
        """
        Returns the filtered queryset based on the value
        provided in the query string and retrievable via
        `self.value()`.
        """
        qs = self.model_to_use.objects.all()
        try:
            request.GET['tag']
            return qs.filter(tags__name=self.value())
        except:
            return qs


def thumbnail(image_path):
    absolute_url = os.path.join(settings.IMAGES_URL, image_path[7:])
    print(absolute_url)
    return '<img style="max-width: 400px" src="%s" alt="%s" />' % (absolute_url, image_path)


class AdminImageWidget(AdminFileWidget):
    """
    A FileField Widget that displays an image instead of a file path
    if the current file is an image.
    """
    def render(self, name, value, attrs=None):
        output = []
        file_name = str(value)
        help_text = ''
        if file_name:
            file_path = '%s' % (file_name)
            if attrs['id'] == 'id_thumbnail':
                help_text = '160 wide'
            if attrs['id'] == 'id_image':
                help_text = '205px high'
            output.append('<span>%s</span><a target="_blank" href="%s">%s</a>' % (help_text, file_path, thumbnail(file_name)))

        output.append(super(AdminFileWidget, self).render(name, value, attrs))
        return mark_safe(''.join(output))


class LGEntryForm(forms.ModelForm):
    class Meta:
        widgets = {
            'body_markdown': forms.Textarea(attrs={'rows': 40, 'cols': 100}),
        }


class LGEntryFormSmall(forms.ModelForm):
    class Meta:
        widgets = {
            'body_markdown': forms.Textarea(attrs={'rows': 12, 'cols': 100}),
        }
class OLAdminBase(OSMGeoAdmin):
    default_lon = -9285175
    default_lat = 4025046
    default_zoom = 15
    units = True
    scrollable = False
    map_width = 700
    map_height = 425
    map_template = 'gis/admin/osm.html'
    openlayers_url = '/static/admin/js/OpenLayers.js'


from bs4 import BeautifulSoup
from photos.models import LuxImage
from django.template.loader import render_to_string
from django.template import Context


def parse_image(s):
    soup = BeautifulSoup(s.group(), "lxml")
    for img in soup.find_all('img'):
        cl = img['class']
        if cl[0] == 'postpic' or cl[0] == 'postpicright':
            s = str(img).replace('[[base_url]]', settings.IMAGES_URL)
            return s
        else:
            image_id = img['id'].split("image-")[1]
            i = LuxImage.objects.get(pk=image_id)
            caption = False
            exif = False
            cluster_class = None
            extra = None
            if cl[0] == 'cluster':
                css_class = cl[0]
                cluster_class = cl[1]
                try:
                    if cl[2] == 'caption':
                        caption = True
                    elif cl[2] == 'exif':
                        exif = True
                    else:
                        extra = cl[2]

                    if len(cl) > 3:
                        if cl[3] == 'exif':
                            exif = True
                except:
                    pass
            elif cl[0] != 'cluster' and len(cl) > 1:
                css_class = cl[0]
                if cl[1] == 'caption':
                    caption = True
                if cl[1] == 'exif':
                    exif = True
            elif cl[0] != 'cluster' and len(cl) > 2:
                css_class = cl[0]
                if cl[1] == 'caption':
                    caption = True
                if cl[2] == 'exif':
                    exif = True
                print('caption'+str(caption))
            else:
                css_class = cl[0]
            return render_to_string("lib/img_%s.html" % css_class, {'image': i, 'caption': caption, 'exif': exif, 'cluster_class': cluster_class, 'extra':extra})


def parse_video(s):
    soup = BeautifulSoup(s, "lxml")
    if soup.find('video'):
        return True
    return False