用models.ImageField保存图像,并用CreateView保存图像

时间:2019-06-17 17:23:27

标签: django

我正在使用CreateView CBV,当我尝试使用CreateView而不将图像保存到DB时,其余字段只能正常工作。

它确实可以通过管理员界面保存

models.py:



class Movie(models.Model):

    name = models.CharField(max_length = 250,unique = True)
    director = models.CharField(max_length = 250)
    image = models.ImageField(upload_to='movies_pictures', blank =True, null=True)
    length = models.IntegerField()
    price = models.IntegerField()
    copies = models.IntegerField()
    trailer = models.URLField()

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        ''' this will reverse you back to movie detail page '''
        return reverse("movie_detail",kwargs={"pk":self.pk})

    class Meta:
        ordering = ['name']



forms.py:

class MovieForm(forms.ModelForm):
    class Meta:
        model = models.Movie
        fields = '__all__'


views.py:


class MovieCreateView(CreateView):
    model = models.Movie
    fields='__all__'

模板:

{% extends "Store/base.html" %}
{% block content %}

  <h1>hello this is movie_form </h1>

  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Save">
  </form>

{% endblock %}

1 个答案:

答案 0 :(得分:0)

将enctype =“ multipart / form-data”添加到表单标签

这对我来说很完美!