Login

Upload multi images

Author:
hieunv495
Posted:
January 17, 2018
Language:
Python
Version:
1.8
Score:
4 (after 4 ratings)

Upload multi images

 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
/* models.py */

class Post(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField()

    slug = models.SlugField(max_length=5, unique=True, blank=True, editable=False)

    slug2 = models.SlugField(max_length=10, blank=True, editable=False)

    def __str__(self):
        return self.slug

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = get_unique_slug(self.__class__,'slug',self.name)
        if not self.slug2:
            self.slug2 = get_unique_slug(self.__class__,'slug2',self.name)
        super().save(*args, **kwargs)


class Image(models.Model):
    post = models.ForeignKey(Post, related_name='images')
    file = models.ImageField(upload_to='upload')
    position = models.PositiveSmallIntegerField(default=0)

    class Meta:
        ordering = ['position']

    def __str__(self):
        return '%s - %s ' % (self.post, self.file)

/* admin.py */
class ImageInline(admin.StackedInline):
    model = Image
    extra = 0

class PostAdmin(admin.ModelAdmin):
    form = PostForm
    inlines = [ImageInline]

    def save_model(self, request, obj, form, change):
        super(PostAdmin,self).save_model(request, obj, form, change)
        # obj.save()

        for afile in request.FILES.getlist('photos_multiple'):
            obj.images.create(file=afile)

/*
project 
----app_name
--------templates
------------admin
----------------app_name
--------------------model_name
------------------------change_form.html
*/
{% extends "admin/change_form.html" %}
{% block inline_field_sets %}
{% for inline_admin_formset in inline_admin_formsets %}
    {% include inline_admin_formset.opts.template %}
{% endfor %}
<fieldset class="module">
  <h2>Upload Photos</h2>
  <input name="photos_multiple" type="file" multiple />
</fieldset>
{% endblock %}

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.