2

I would like to convert a user uploaded .docx file to .html using a function/method I have in models.py. I can do it with function based view with this kind of approach:

models.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:

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.

1 Answer 1

1

You could use the base View and override the get method.

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.

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.