我正在使用django基于通用类的视图CreateView
将图像上传到书中。这是代码:
# models.py
class Upload(models.Model):
image = models.ImageField(upload_to=get_upload_path, help_text='Image to process')
uploader = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE, related_name='uploader')
language = models.ForeignKey(Language, models.CASCADE)
book = models.ForeignKey(Book, models.CASCADE)
def __str__(self):
return str(os.path.split(self.image.name)[-1].split('_', 1)[-1])
@models.permalink
def get_absolute_url(self):
return ('book:upload_new', (self.book.id,)) # upload_new is linked to the view below
def save(self, *args, **kwargs):
super(Upload, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
self.image.delete(False)
super(Upload, self).delete(*args, **kwargs)
# views.py
@method_decorator(login_required, name='dispatch')
class PictureCreateView(CreateView):
model = Upload
fields = ("image",)
book_id = None
def dispatch(self, *args, **kwargs):
# book_id is passed as a URL parameter
self.book_id = self.kwargs['book_id']
return super().dispatch(*args, **kwargs)
def get_context_data(self, **kwargs):
context = super(PictureCreateView, self).get_context_data(**kwargs)
context['book_id'] = self.book_id
return context
def form_valid(self, form, **kwargs):
book = Book.objects.get(id=self.book_id)
form.instance.book = book
form.instance.language = book.language
form.instance.uploader = self.request.user
self.object = form.save()
# Running the command below prints
# <TemplateResponse status_code=200, "text/html; charset=utf-8">
# implying the upload was successful
#
# print(self.render_to_response(context=self.get_context_data()))
return super(PictureCreateView, self).form_valid(form)
def form_invalid(self, form):
print(form.errors)
data = json.dumps(form.errors)
return HttpResponse(content=data, status=400, content_type='application/json')
当我尝试上传图片时,我收到此请求的302 Found
错误(如我浏览器的开发工具中所示),表示该页面已暂时移动。除了标题之外,我无法看到此请求的预览或响应。上传成功虽然(我在管理页面中查看过)。
之前有人this issue,答案指出了网址中的错误。但是,该问题尚未完全解决,OP仍然获得302状态代码。
这可能是什么原因?
答案 0 :(得分:1)
默认情况下,form_valid
方法将302代码重定向到success_url
(可以通过覆盖get_success_url
动态生成)。所以这是正常的行为,我认为这是一种很好的做法。所以我不会改变它。
但如果您真的想要,可以返回任何其他响应代码,例如:内容与获取内容类似的200代码
# views.py
@method_decorator(login_required, name='dispatch')
class PictureCreateView(CreateView):
...
def form_valid(self, form, **kwargs):
book = Book.objects.get(id=self.book_id)
form.instance.book = book
form.instance.language = book.language
form.instance.uploader = self.request.user
self.object = form.save()
context = self.get_context_data()
# You may have check and modify your context for a correct page
# May be: add new things
context["success"] = True
return self.render_to_response(context))