【问题标题】:Django getting Type error in post image create function viewDjango在发布图像创建功能视图中出现类型错误
【发布时间】:2021-05-12 08:45:29
【问题描述】:

下面的代码出现错误TypeError: post_image_create() missing 1 required positional argument: 'post' 我想在提交表单之前将多个图像异步添加到 django 表单。我有用于在客户端上传图像的 Javascript 代码并将其异步添加到我的服务器。我需要做的就是给它一个端点

如果有任何帮助,我将不胜感激。

模型

class FileModel(models.Model):
    post = models.ForeignKey(Article, on_delete=models.CASCADE)
    file = models.FileField(upload_to='stories', blank=True, null=True)

观看次数

def post_image_create(request, post):
    if(request.method == "POST"):
        for f in request.FILES.getlist('file'):
            FileModel.objects.create(file=f)


class NewsCreateView(CreateView):
    form_class = FileForm
    template_name = 'news/news_create.html'
    success_url = '/'

    def form_valid(self, form):
        post = form.save(commit=False)
        post.author = self.request.user
        post_image_create(request=self.request, post=post)  # This function is defined above
        post.save()
        return super().form_valid(form)

【问题讨论】:

  • 查看此文档以了解如何为 ajax 请求获取 csrf-token Django docs

标签: javascript python django django-models django-views


【解决方案1】:

这表示您的请求函数缺少参数。 TypeError: post_image_create() missing 1 required positional argument: 'post'.

在您的视图函数中,您定义def post_image_create(request, post):,但在您的 urls.py 中您将其设置为:path('new_image/', views.post_image_create, name='new_image') 如果您想传递一个参数,您需要在您的 urls.py url 路由器中进行设置.

但不用于传递帖子数据。您可以使用请求对象访问发布数据。将您的视图函数更改为:

def post_image_create(request):
  if(request.method == "POST"):
    files = request.FILES 
     ...then do stuff

在文档中:https://docs.djangoproject.com/en/3.1/ref/request-response/#django.http.HttpRequest.method

以及更多关于将 urls.py 中的参数传递给视图函数的信息:https://docs.djangoproject.com/en/3.1/topics/http/urls/#example

【讨论】:

  • @afi 之前的更新有什么更新吗?我认为这不是解决此问题的最佳方法,因为更新我的答案和来回更新您的问题会掩盖您遇到的原始问题和建议的原始修复。也许你应该提出一个新问题。
  • 是的,亲爱的,我正在尝试找到问题的解决方案。你的答案对我来说是正确的......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 2020-07-15
  • 1970-01-01
  • 1970-01-01
  • 2019-09-07
  • 2016-08-01
相关资源
最近更新 更多