How to customize django imagefield input in HTML

时间:2019-01-15 18:18:23

标签: django python-3.x django-forms django-templates bootstrap-4

I have a django-form with an ImageField that I'm rendering in the HTML template. Originally, using this code, I could successfully upload an image:

{% for field in form %}
  {% if field == form.image %}
    {{ field.label_tag }}
    {{ form.image }}

But I didn't like django's styling so I customized it using Bootstrap 4. This is the updated HTML:

{% for field in form %}
  {% if field == form.image %}
    <label class="btn btn-primary" for="my-file-selector">
      <input id="my-file-selector" type="file" style="display:none" 
              onchange="$('#upload-file-info').html(this.files[0].name)">
            Choose an image
    </label>
    <span class='label label-info' id="upload-file-info"></span>

Now the styling is correct, but the image won't upload successfully. Or rather, I can choose an image, but when I submit the playlist it won't be entered into the database and I therefore can't have it displayed. How can I use this styling but still successfully upload images?

This is my views.py code:

def new_playlist(request): 
"""Add a new playlist."""
    if request.method != 'POST':
        # No data submitted; create a blank form.
        form = AddPlaylistForm()
    else:
        form = AddPlaylistForm(request.POST)
        if form.is_valid:
            form.save()
            return redirect("/great_songs/playlists")

And my models.py:

class Playlist(models.Model):
    """Allow a user to create a customized list of songs."""
    name = models.CharField(max_length=100)
    image = models.ImageField(upload_to='playlists/%Y/%m/%d', blank=True, null=True)
    songs = models.ManyToManyField('Song')
    description = models.TextField(blank=True, null=True)
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        """String for representing the model object."""
        return self.name

    def get_absolute_url(self):
        """Returns the url to access a detail record for this song."""
        return reverse('playlist-detail', args=[str(self.id)])

0 个答案:

没有答案