Django在发布图像创建函数视图中出现类型错误 [英] Django getting Type error in post image create function view
问题描述
下面的代码出错了 TypeError:post_image_create()缺少1个必需的位置参数:'post'
我想在表单提交之前异步将多个图像添加到Django表单中.我有Javascript代码用于在客户端上载图像并将其异步添加到我的服务器.我要做的就是给它一个端点
The code below is getting error TypeError: post_image_create() missing 1 required positional argument: 'post'
I want to add multiple images to a django form asynchronously before form submit.I have the Javascript code for uploading of the images on the client side and asynchronously adds it to my server. All I need to do is give it a endpoint
我将不胜感激.
模型
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)
推荐答案
这是说您的请求函数缺少参数. TypeError:post_image_create()缺少1个必需的位置参数:"post"
.
This is saying that your request function is missing an argument. 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,名称="new_image")
如果要传递参数,则需要在urls.py url路由器中进行设置.
In your view function, you define def post_image_create(request, post):
but in your urls.py you have it set up as :path('new_image/', views.post_image_create, name='new_image')
If you want to pass a parameter you need to set set that up in your urls.py url router.
但不用于传递帖子数据.您可以使用请求对象访问帖子数据.将视图功能更改为:
BUT that isn't used for passing post data. You can access post data using the request object. Change your view function to be:
def post_image_create(request):
if(request.method == "POST"):
files = request.FILES
...then do stuff
它在文档中: https://docs.djangoproject.com/zh-CN/3.1/ref/request-response/#django.http.HttpRequest.method
and more about passing parameter in urls.py to a view function: https://docs.djangoproject.com/en/3.1/topics/http/urls/#example
这篇关于Django在发布图像创建函数视图中出现类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!