[英]How to call a function from models.py with class based views in Django?
I would like to convert a user uploaded .docx file to .html using a function/method I have in models.py.我想使用models.py 中的函数/方法将用户上传的.docx 文件转换为.html。 I can do it with function based view with this kind of approach:
我可以使用这种方法使用基于函数的视图来做到这一点:
models.py:模型.py:
class Article(models.Model):
main_file = models.FileField(upload_to="files")
slug = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
@classmethod
def convert_word(self, slug):
import pypandoc
pypandoc.convert_file('media/files/%s.docx' %slug, 'html', outputfile="media/files/%s.html" %slug)
And then I call the convert_word function like this in views.py:然后我在views.py中像这样调用convert_word函数:
def submission_conf_view(request, slug):
Article.convert_word(slug)
return redirect('submission:article_list')
What I would like to do is to call the same function/method but using Django's Class-based views, but I am having trouble figuring that out.我想做的是调用相同的函数/方法,但使用 Django 的基于类的视图,但我无法弄清楚。
You could use the base View
and override the get
method.您可以使用基本
View
并覆盖get
方法。
from django.views import View
class MyView(view):
def get(self, request, *args, **kwargs):
Article.convert_word(self.kwargs['slug'])
return redirect('submission:article_list')
Or since your view always redirects, you could use RedirectView
.或者由于您的视图总是重定向,您可以使用
RedirectView
。
class MyView(RedirectView):
permanent = False
pattern_name = 'submission:article_list' # the pattern to redirect to
def get_redirect_url(self, *args, **kwargs):
# call the model method
Article.convert_word(self.kwargs['slug'])
# call super() to return a redirect
return super().get_redirect_url(*args, **kwargs)
However there's not real advantage to using either of these.但是,使用其中任何一个都没有真正的优势。 I think your current three line method is more readable.
我认为您当前的三行方法更具可读性。
See the docs about an introduction to class based views or RedirectView
for more info.有关更多信息,请参阅有关基于类的视图或
RedirectView
的介绍的文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.