Django映像不是从模板上传,而是从管理员上传

时间:2019-05-08 03:26:21

标签: html django upload image-uploading

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

这是我的模特:

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代码内。

2 个答案:

答案 0 :(得分:0)

真正的问题是您没有将pictures附加到表单上。将表单的生成方式更改为:

views.py:

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

如果您遵循django docs on forms rendering,也可以稍微改善模板。

您甚至如何创建没有ForeignKey属性的on_delete

在模型中,您将用户称为发布者,而不是发件人,因此也请对其进行更改:

views.py:

post.poster = request.user

答案 1 :(得分:0)

您是否更改了settings.py配置? 另外,您还需要在views.py中包含minlat = input.readFloat(); minlon = input.readFloat(); maxlat = input.readFloat(); maxlon = input.readFloat(); kdtreeCoastline = (KDTree) input.readObject(); kdtreeBicycle = (KDTree) input.readObject(); ---- output.writeFloat(minlat); output.writeFloat(minlon); output.writeFloat(maxlat); output.writeFloat(maxlon); output.writeObject(kdtreeCoastline); output.writeObject(kdtreeBicycle); ,以便在您的form.py中渲染文件或图像

相关问题