【问题标题】:Image field gets cleared off in django when i submit it当我提交时,图像字段在 django 中被清除
【发布时间】:2020-11-05 03:15:06
【问题描述】:

我正在尝试创建一个类似于 Instagram 的社交媒体应用程序,但是由于某种原因,当我将图片加载到图像字段并提交时,图像被清除,并说该字段是必需的。

Before submission

After submission

在 Django 中,代码为 视图.py

@login_required
def new_post(request):
    if request.method == 'POST':
        form = CreateNewPost(request.POST)
        if form.is_valid():
            messages.success(request, "Post has been created")
            form.save()
            return redirect('home')
    else:
        form = CreateNewPost()
    return render (request, "posts/post_form.html", {"form":form})

我暂时将默认用户保留为无,因为它在我最初创建模型时坚持让我选择一个。这是这个问题的原因吗?如果是这样,我该如何摆脱它。

HTML 代码...

    <form method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        <fieldset class="form-group">
            <legend class="border-bottom mb-4">Add a Post!</legend>
            {{ form | crispy }}
        </fieldset>
        <div class="form-group">
            <button class="btn btn-outline-info" type="submit">Post</button>                
        </div>
    </form>

models.py

class Post(models.Model):
    image = models.ImageField(upload_to='post_images')
    caption = models.CharField(blank=True, max_length=254)
    date_posted = models.DateTimeField(auto_now_add=timezone.now)
    author = models.ForeignKey(User, on_delete = models.CASCADE)

    def save(self):
        super().save()
        img = Image.open(self.image.path)
        width, height = img.size
        ratio = width/height
        if img.height > 500:
            outputsize = (500, (height/ratio))
            img.thumbnail(outputsize)
            img.save(self.image.path)

forms.py

class CreateNewPost(forms.ModelForm):
    class Meta:
        model = Post
        fields = ["image","caption"]

以防万一,urls.py

urlpatterns = [
    path('', views.home, name='home'),
    path('new_post/', views.new_post, name="new_post"),
]

我也尝试过使用基于类的视图,这给了我同样的错误

【问题讨论】:

标签: python django social-media


【解决方案1】:

您需要将request.FILES [Django-doc] 传递给表单,这是一个类似于字典的对象,其中包含上传文件的UploadedFile 对象:

@login_required
def new_post(request):
    if request.method == 'POST':
        form = CreateNewPost(request.POST, request.FILES)
        if form.is_valid():
            form.instance.author = request.user
            form.save()
            messages.success(request, 'Post has been created')
            return redirect('home')
    else:
        form = CreateNewPost()
    return render (request, 'posts/post_form.html', {'form':form})

注意:通常使用settings.AUTH_USER_MODEL [Django-doc] 引用用户模型比直接使用User model [Django-doc] 更好。更多信息可以查看referencing the User model section of the documentation

【讨论】:

  • 天哪,完美!非常感谢你的帮助。意义重大!
猜你喜欢
  • 1970-01-01
  • 2014-10-17
  • 2011-08-12
  • 1970-01-01
  • 2010-10-11
  • 1970-01-01
  • 2021-09-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多