【问题标题】:Django image is not uploading from the template, but uploads from adminDjango 图像不是从模板上传,而是从管理员上传
【发布时间】:2019-09-25 17:40:28
【问题描述】:

我正在尝试创建一个页面,用户可以在其中上传带有帖子的图片。 图像上传在另一个应用程序中工作,但在这个应用程序中,每当我提交表单时,除了图像之外的所有信息都会插入到数据库中。 如果我打开管理面板并上传图片,则图片上传成功,只是通过模板无法上传。

这是我的模型:

def validate_image(image):
    file_size = image.file.size
    limit_mb = 3
    if file_size > limit_mb * 1048576:
        raise ValidationError("Max size of file is %s MB" % limit_mb)

class Posting (models.Model):
    poster = models.ForeignKey(User, related_name='poster_posting', verbose_name='poster')
    description = models.TextField(max_length=200, verbose_name=_('description'))
    pictures = models.ImageField(
        upload_to='postings/',
        verbose_name=_('Posting_picture'),
        blank=True, null=True,
        validators=[validate_image],
    )

    def __str__(self):
        return "Posting #{}".format(self.pk)

    def filename(self):
        if self.pictures:  
            return os.path.basename(self.pictures.name)
        return ''

这里是视图:

def posting(request):
        if request.method == "POST":
        form = Publish(request.POST)


        if form.is_valid():
            post = form.save(commit=False)
            post.poster = request.user
            post.save()
            messages.success(request, _("your request was posted successfully"))


            return redirect("posting:posting_detail", pk=post.id)
    else:
        form = Publish()

    return render (request, 'list_posting.html',{'form': form})

形式:

class Publish(forms.ModelForm):
    """publishing of listing"""
    description = forms.CharField(
        widget=forms.Textarea(
            attrs={'rows': 6, }
        )
    )

    class Meta:
        model = Posting
        fields = (
        'description',
        'pictures')

最后是模板:

[...]
<form  method="POST" enctype="multipart/form-data" style="margin-bottom: 60px;font-family: Muli, sans-serif;" >
 {% csrf_token %}
<div class="form-row" id="Notes" style="padding-right: 20px;padding-left: 20px;">
                <div class="col"><input name="description" id="listing_description" required class="form-control" placeholder=" {% trans 'Items to send - Example: I want to send 3 shirts, one children book and one science book (maximum of 150 characters)' %}" maxlength="150" style="margin-top: 36px;"></div>

{% if form.description.errors %}<small class="form-text text-muted" style="color: red">{{ form.description.errors }}</small> {% endif %}


                      </div>

<div class="form-row" id="Pictures" style="padding-right: 20px;padding-left: 20px;" >
    <div class="col">

    <input accept="image/" type="file" class="filestyle" name="pictures" data-size="sm" style="padding-top: 33px;" >
<small class="form-text text-muted" >{% trans 'You can only upload one picture. The size cannot exceed 3Mb.' %}</small> </div>
</div>
<div class="form-row text-right" id="Buttons" style="padding-right: 20px;padding-left: 20px;padding-top: 29px;">
                <div class="col">
                    <div class="btn-group" role="group"><a class="btn btn-light" role="button" href="{% url '...' %}" style="margin-right: 20px;">{%trans 'cancel'%}</a><button class="btn btn-dark" type="submit">{% trans 'submit' %}</button></div>
                </div>
            </div>

当我提交表单时,在调试中,图片字段是空白的,所以我不确定问题是否在我的 html 代码中。

【问题讨论】:

    标签: html django upload image-uploading


    【解决方案1】:

    您是否更改了 settings.py 配置? 您还需要在 views.py 中包含 form = Publish(request.POST, request.FILES or none) 以在您的 forms.py 中呈现文件或图像

    【讨论】:

      【解决方案2】:

      真正的问题是您没有将pictures 附加到您的表单中。将构建表单的方式更改为:

      views.py:

      form = Publish(request.POST, request.FILES)
      

      如果您关注django docs on forms rendering,您也可以稍微改进您的模板。

      你是如何创建没有on_delete 属性的ForeignKey 的?

      在您的模型中,您将用户称为发件人,而不是发件人,因此也要更改它:

      views.py:

      post.poster = request.user
      

      【讨论】:

      • 谢谢@Gasanov,你能给我解释一下带有on_delete属性的东西吗?在我的情况下,键不会从数据库中删除,所以我没有考虑on_delete,但是当有外键时我应该总是添加它吗?
      • @RiadC on_deletepositional argument,据我所知,django 甚至不应该在没有指定的情况下启动(除非你使用 django
      猜你喜欢
      • 2014-09-25
      • 2018-02-13
      • 1970-01-01
      • 2015-10-25
      • 2021-09-27
      • 2017-01-12
      • 1970-01-01
      • 2014-04-16
      • 2013-09-07
      相关资源
      最近更新 更多