Allow for adding covers from a disk
authorAleksander Łukasz <aleksander.lukasz@nowoczesnapolska.org.pl>
Wed, 9 Oct 2013 10:04:38 +0000 (12:04 +0200)
committerAleksander Łukasz <aleksander.lukasz@nowoczesnapolska.org.pl>
Wed, 9 Oct 2013 10:04:38 +0000 (12:04 +0200)
apps/cover/forms.py
apps/cover/migrations/0002_auto__chg_field_image_download_url.py [new file with mode: 0644]
apps/cover/models.py
apps/cover/templates/cover/add_image.html
apps/cover/views.py

index 0173134..67a0c53 100755 (executable)
@@ -13,6 +13,20 @@ class ImageAddForm(forms.ModelForm):
     class Meta:
         model = Image
 
+    def __init__(self, *args, **kwargs):
+        super(ImageAddForm, self).__init__(*args, **kwargs)
+        self.fields['file'].required = self.fields['download_url'].required = False
+
+    def clean_download_url(self):
+        return self.cleaned_data['download_url'] or None
+
+    def clean(self):
+        cleaned_data = super(ImageAddForm, self).clean()
+        if not cleaned_data.get('download_url', None) and not cleaned_data.get('file', None):
+            raise forms.ValidationError('No image specified')
+        return cleaned_data
+
+
 class ImageEditForm(forms.ModelForm):
     """Form used for editing a Book."""
     class Meta:
diff --git a/apps/cover/migrations/0002_auto__chg_field_image_download_url.py b/apps/cover/migrations/0002_auto__chg_field_image_download_url.py
new file mode 100644 (file)
index 0000000..8a64c39
--- /dev/null
@@ -0,0 +1,34 @@
+# -*- coding: utf-8 -*-
+import datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+
+class Migration(SchemaMigration):
+
+    def forwards(self, orm):
+
+        # Changing field 'Image.download_url'
+        db.alter_column(u'cover_image', 'download_url', self.gf('django.db.models.fields.URLField')(max_length=200, unique=True, null=True))
+
+    def backwards(self, orm):
+
+        # User chose to not deal with backwards NULL issues for 'Image.download_url'
+        raise RuntimeError("Cannot reverse this migration. 'Image.download_url' and its values cannot be restored.")
+
+    models = {
+        u'cover.image': {
+            'Meta': {'object_name': 'Image'},
+            'author': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
+            'download_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'unique': 'True', 'null': 'True'}),
+            'file': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}),
+            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'license_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
+            'license_url': ('django.db.models.fields.URLField', [], {'max_length': '255', 'blank': 'True'}),
+            'source_url': ('django.db.models.fields.URLField', [], {'max_length': '200'}),
+            'title': ('django.db.models.fields.CharField', [], {'max_length': '255'})
+        }
+    }
+
+    complete_apps = ['cover']
\ No newline at end of file
index 6900e78..5574f34 100644 (file)
@@ -21,8 +21,8 @@ class Image(models.Model):
     license_name = models.CharField(max_length=255, verbose_name=_('license name'))
     license_url = models.URLField(max_length=255, blank=True, verbose_name=_('license URL'))
     source_url = models.URLField(verbose_name=_('source URL'))
-    download_url = models.URLField(unique=True, verbose_name=_('image download URL'))
-    file = models.ImageField(upload_to='cover/image', editable=False, verbose_name=_('file'))
+    download_url = models.URLField(unique=True, verbose_name=_('image download URL'), null = True)
+    file = models.ImageField(upload_to='cover/image', editable=True, verbose_name=_('file'))
 
     class Meta:
         verbose_name = _('cover image')
index ed7adfb..1854555 100755 (executable)
@@ -1,6 +1,33 @@
 {% extends "catalogue/base.html" %}
 {% load i18n %}
 
+{% block add_js %}
+    {{block.super}}
+    <script>
+        $(function() {
+            var radio_buttons = $('input[type=radio][name=upload_type]'),
+                image_fields = $('.upload_type input[type=text],input[type=file]');
+
+            var enable_image_field = function(field) {
+                field.attr('disabled', false);
+            },
+            disable_image_fields = function() {
+                image_fields.attr('disabled', true);
+            }
+
+            radio_buttons.change(function() {
+                var radio_button = $(this),
+                    related_image_field = $('#'+radio_button.attr('data-for'));
+                disable_image_fields();
+                enable_image_field(related_image_field);
+            });
+
+            /* initial state */
+            disable_image_fields();
+            enable_image_field($('#id_download_url'));
+        });
+    </script>
+{% endblock %}
 
 {% block content %}
 <h1>{% trans "Add image" %}</h1>
 </tbody></table>
 </form>
 
-
-<form method="post">{% csrf_token %}
+<form method="post" enctype="multipart/form-data">{% csrf_token %}
+{{ form.non_field_errors }}
 <table class='editable'><tbody>
-    {{ form.as_table }}
+    {% for field in form %}
+        {% if field.name != 'download_url' and field.name != 'file' %}
+        <tr>
+            <th>{{field.errors}} {{field.label}}</th>
+            <td>{{field}}</td>
+        </tr>
+        {% endif %}
+    {% endfor %}
+    <tr class="upload_type">
+        <th>{{ form.download_url.errors }} <input style="width: auto;" checked data-for="id_download_url" type="radio" name="upload_type" value="url"/>{{form.download_url.label}}</th>
+        <td>{{form.download_url}}</td>
+        <th>{{ form.file.errors }} <input style="width: auto;" data-for="id_file" type="radio" name="upload_type" value="file"/> Lub {{form.file.label}}</th>
+        <td>{{form.file}}</td>
+
+    </td>
     <tr><td></td><td><button type="submit">{% trans "Add image" %}</button></td></tr>
 </tbody></table>
 </form>
index 2a21b5c..3d30a2a 100644 (file)
@@ -125,7 +125,7 @@ def add_image(request):
             if ff.is_valid():
                 form = forms.ImageAddForm(ff.cleaned_data)
         else:
-            form = forms.ImageAddForm(request.POST)
+            form = forms.ImageAddForm(request.POST, request.FILES)
             if form.is_valid():
                 obj = form.save()
                 return HttpResponseRedirect(obj.get_absolute_url())