BBCode to Markdown

I’ve been working on a Python/Django project that involved importing the database from a MyBB forum to a forum that uses Markdown instead of BBCode.

There aren’t really any Python libraries available that do a direct conversion of BBCode to Markdown. So I wrote my own using the bbcode library to convert the bbcode to html which is then converted to Markdown using the html2text library.

The source, along with a demo project of BBtoMD is available on github.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from django.views.generic import TemplateView
from django.shortcuts import render
from django import forms
from . import models
import bbcode
import html2text


class ConverterForm(forms.ModelForm):
    class Meta:
        model = models.ConversionModel
        fields = '__all__'


class ConverterView(TemplateView):
    form_class = ConverterForm
    initial = {'key': 'value'}
    template_name = 'pages/index.html'

    def get(self, request, *args, **kwargs):
        form = self.form_class
        return render(request, self.template_name, {'converter_form': form})

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        if form.is_valid():
            mybbcodes = request.POST['bbcodes']
            html = bbcode.render_html(mybbcodes)
            h = html2text.HTML2Text()
            h.body_width = 0
            mymdcodes = h.handle(html)

        return render(request, self.template_name, {'converter_form': form, 'mdcodestring': mymdcodes })

You May Also Like

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *