Django 图片不是从模板上传的,而是从管理员上传的

Django image is not uploading from the template, but uploads from admin

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

这是我的模型:

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

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

views.py:

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

如果您遵循 django docs on forms rendering.

,您还可以稍微改进您的模板

你是如何在没有 on_delete 属性的情况下创建 ForeignKey 的?

在您的模型中,您将用户称为发帖人,而不是发件人,所以也更改它:

views.py:

post.poster = request.user

您是否更改了 settings.py 配置? 您还需要在 views.py 中包含 form = Publish(request.POST, request.FILES or none),以便在 forms.py

中呈现文件或图像