Skip to main content
 首页 » 编程设计

python之如何在 Django 中使用基于类的 View 从 models.py 调用函数

2025年01月19日27kerrycode

我想使用 models.py 中的函数/方法将用户上传的 .docx 文件转换为 .html。我可以通过这种方法使用基于函数的 View 来做到这一点:

模型.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) 

然后我在 views.py 中这样调用 convert_word 函数:

def submission_conf_view(request, slug): 
    Article.convert_word(slug) 
    return redirect('submission:article_list') 

我想做的是调用相同的函数/方法,但使用 Django 的基于类的 View ,但我无法弄清楚。

请您参考如下方法:

您可以使用基础 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') 

或者由于您的 View 总是重定向,您可以使用 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) 

但是,使用其中任何一个都没有真正的优势。我认为您当前的三行方法更具可读性。

请参阅有关 an introduction to class based views 的文档或 RedirectView了解更多信息。