Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django staff users manage their own users that they have created only
In my Django app a user can register to the site and receive staff_user privileges from the admin. After that the staff user can create and manage some other users (normal users) using default django admin site. Now, I would like to let the staff user see and manage only the users he created from the admin site, I don't want him to see other users created by another staff user. how can I do that? I imagine I need to modify admin.py right? I am using django version 1.11 -
Django template loader unable to load template
I am getting a TemplateDoesNotExistError I am new to Django development and have already spent hours trying to fix this issue without success. Can anyone guide me? My project is basilweb and my app within this project is basilapp. I need to show a screen that gets the user for a "gocker_setting" if its not already present in the session. The form to ask the user for this gocker_setting displays correctly and I am able to retrieve the value properly in my view. But when I next try to render the screen after the value is retrieved, I get a TemplateDoesNotExistError at /genie/gocker. Here are the details of my setup #settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'basilapp', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] # my directory structure basilweb basilapp templates genie getgockersetting.html gocker.html # basilweb/url.py urlpatterns = [ path('genie/', include('basilapp.genie.urls')), path('saras/', include('basilapp.saras.urls')), path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), ] # bailapp/genie/urls.py urlpatterns = [ path('index', views.index, name='genie_index'), path('gocker', views.gocker, name='genie_gocker'), ] # basilapp/genie/views.py @login_required(login_url='/accounts/login/') def gocker(request): gocker_setting = None if "gocker_setting" in request.session: gocker_setting = request.session["gocker_setting"] else: # if this is … -
How to set a session variable in a HTML template in Django?
I'm trying to set value to Django session within the template and then posible used in the view. I'm doing something like this {% block body %} <html> {% request.session.fav_color="red" %} <div> Is your favorite color {{ request.session.fav_color}} ?</div> </html> {% endblock %} -
Moving django project to Github removes its dependency packages
So I'm working on a blog right now with Django and Python. I created a virtual environment and created my project there. I activated my virtual environment every time, so that whenever I do pip install Django or whatever it installs those packages to my virtual environment. However, When I uploaded my project with virtual env to GitHub and downloaded it on my laptop, and do "pip list" only 4 Django packages(pip, pytz, setuptools, virtualenv) are there. They are all different versions from the original too. My original virtual env has these packages below: certifi 2018.11.29 chardet 3.0.4 Django 2.1.5 django-embed-video 1.2.0 idna 2.8 pip 18.1 pytz 2018.7 requests 2.21.0 setuptools 40.6.3 urllib3 1.24.1 wheel 0.32.3 Can anyone explain to me what is going on? -
cookiecutter not running django server
Traceback (most recent call last): File ".\manage.py", line 15, in import django # noqa ModuleNotFoundError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File ".\manage.py", line 18, in "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? So, I'm getting that error after installing cookiecutter on my virtualenv, any ideas? -
Django function based views return form object instead of actual form
I have this view of creating Post Model instance. def post_create(request): if request.method == 'GET': form = PostCreate() context = { 'form': form } return render(request, 'posts/create.html', context) else: form = PostCreate(request.POST) if form.is_valid(): title = form.cleaned_data.get('title') blog_type = form.cleaned_data.get('blog_type') text = form.cleaned_data.get('text') status = form.cleaned_data.get('status') Post.objects.create( title=title, blog_type=blog_type, text=text, status=status ) return redirect('post-show') else: return render(request, 'posts/create.html', context) I have a form class PostCreate which is a ModelForm for my Post Model class PostCreate(forms.ModelForm): class Meta: model = Post fields = [ 'title', 'blog_type', 'text', 'status' ] And create.html have a form <form action="" method='post'> {% csrf_token %} {{form.as_p}} <input type="submit"> </form> With path path('posts/create', post_create, name='post-create'), Server is running fine with all this. Now when I goto this path, it does not show the form. As I checked using print(form) in view or {{form}} in template gives <posts.views.PostCreate object at 0x10b1b8a90>. Due to this {{form.as_p}} is not returning anything. This was working fine yesterday but today, everything is fine even then not working now. -
Custom Interactive data Visualization Dashboard Built in Django
I want to try to build an interactive dashboard like Tableau or Power BI in Django. Have you any suggestions? -
Django: How to bind two fields in two models, i.e. make them exactly the same?
Here I have a User model: class User(AbstractUser): plate_number = models.CharField(max_length=10, blank=True, null=True) and a Vehicle model: class Vehicle(models.Model): plate_number = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) I do not think my design is correct, because plate_number in Vehicle model is not CharField but User in this way. How to make two plate_number exactly the same in two models? The logic is, a User MAY NOT have a plate_number but a vehicle MUST HAVE a same plate_number existing in User model, and I would like either field change, then the counterpart field makes the same change automatically. Is this possible? Thanks very much!! -
Regex-based custom template filter doesn't find the first targeted word in a string (Django 2.1)
I have a regex-based custom template filter that finds and highlights the keyword put into the search engine, like Google. For example, if the user searches "cake", my filter will highlight "cake" in "I just ate a cake." Here is the code for the filter: @register.filter(needs_autoescape=True) @stringfilter def highlight(value, search_term, autoescape=True): # first compile the regex pattern using the search_term pattern = re.compile(re.escape(search_term), re.IGNORECASE) # now replace new_value = pattern.sub('<span class="highlight">\g<0></span>', value) return mark_safe(new_value) Code for search engine in views.py: def query_search(request): articles = cross_currents.objects.all() search_term = '' if 'keyword' in request.GET: search_term = request.GET['keyword'] articles = articles.annotate(similarity=Greatest(TrigramSimilarity('Title', search_term), TrigramSimilarity('Content', search_term))).filter(similarity__gte=0.03).order_by('-similarity') context = {'articles': articles, 'search_term': search_term} return render(request, 'query_search.html', context) HTML template: <ul> {% for article in articles %} <li><a href="{% url 'search:article_detail' article.ArticleID %}">{{ article|highlight:search_term }}</a></li> <p> {{ article.Content|highlight:search_term|show_excerpt:search_term }} </p> {% endfor %} </ul> The problem is that the filter doesn't highlight the first keyword that occurs but does it to all other keywords. For example, if the keyword is "cake" and a sentence is "my cake is a cake from a cake shop", it would only highlight the second and third "cake" but not the first one. Any idea why this is the case? -
Problem in displaying django formset errors
I'm using formset to get multiple user inputs where users can set the Delete form checkbox if needed. But there should be at least 1 form as provided in min_num argument to the formset. However, when the user check all forms to be deleted formset is_valid() method fails without showing any errors. It just show [{}, {}] when printed formset.errors attribute. if formset.is_valid(): ... else: print(formset.errors) # this prints [{}, {}] return self.render_to_response(context_data) -
Django - How to determine time periods when a resource is greater than a max_value on a ForeignKey
I have two models relevant to this question. Each PowerSource has a maximum current (number of amps) that can flow through it before it becomes dangerous. I want to allow people to utilize these power sources by scheduling Usage instances. class PowerSource(models.Model): title = models.CharField(max_length=20, unique=True) max_amps = models.SmallIntegerField(default=0, help_text='Maximum capacity for this Power Source in amps') class Usage(models.Model): user = ForeignKey(User, on_delete=models.CASCADE) start_dt = models.DateTimeField() end_dt = models.DateTimeField() amps = models.SmallIntegerField(help_text='How much current, in amps, does this usage need?') It's easy enough to check whether a newly placed Usage instance will put the PowerSource over the max_amps value (just get the sum of amps for each order that overlaps with the new Usage instance), but I need something a bit more complex: Assuming there are multiple Usage instances with overlapping start/stop periods for a particular PowerSource, how can I efficiently identify all time periods when overall usage is at or above the 'max_amps' value for the PowerSource? I'm pretty experienced with Django, but I don't even know where to start with something like this. Can this be done in the ORM? -
Find Django Database in the PC
I am trying to create a django project and I created a simple model and ran the django server, entered the fields. I can see all the data on the django server. I was wondering if there is any other way to see the data entered. enter image description here This is the data I entered. Can I view it anywhere else in tabular form or database form? Thanks in advance. -
How to resize and crop an image into a square in Django?
I wanted to crop my profile images into squares and reduce their size. So I googled "image resize matrix." None of the results matched my need, so I wrote my own code. It's in python/django. I decided most images of a head have more space on the bottom because of the neck and shoulders. So I cropped heights from the top, instead of from the middle. All of the widths are cropped to the middle. It uses 300 pixels as a maximum. I suppose this might help someone who has a similar task. I need more points so I can vote on stuff. I use the site all day and get lots of answers, but I can't vote. Which makes me feel guilty. from PIL import Image class CustomUser(AbstractBaseUser, PermissionsMixin): # User model fields, etc image = models.ImageField(default='default.jpg',upload_to='profile_pics') def save(self, *args, **kwargs): super().save() img = Image.open(self.image.path) width, height = img.size # Get dimensions if width > 300 and height > 300: # keep ratio but shrink down img.thumbnail((width, height)) width, height = img.size # check which one is smaller if height < width: # make square by cutting off equal amounts left and right left = (width - height) / … -
Python Contact Form
i created a contact form using django. Everything goes through to my email account except im not able to see the emailFrom on my email account. how can i edit my code so the from email appears on my account?? views def contact(request): mapbox_access_token = 'pk.my_mapbox_access_token' if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): sender_name = form.cleaned_data['name'] emailFrom = form.cleaned_data['email'] message = "{0} has sent you a new message:\n\n{1}".format(sender_name, form.cleaned_data['message']) form.save() try: send_mail('New Enquiry', message, emailFrom, ['va.glazing@gmail.com']) except BadHeaderError: return HttpResponse('Invalid header found') return redirect('success') return render(request, "contact.html",{'form': form}) -
Install BruteBuster, setup is correct wont block me
I installed BruteBuster into my django project, everything seems to be loaded properly in my database but it doesn't seem to be doing anything. I'm still able to spam attempt different passwords without a lockout timer or anything. https://github.com/mtrdesign/django-brutebuster The installation section even states that the default lockout is set at 5 attempts but here I'll show you that I've gone past 5 minutes. Is this happening because I'm using a loopack ip? or did I miss something? Please any recommendations would be greatly appreciated. -
Link Django models together
Hi have two background functions that fetch data from an api and update models every few seconds calling .save() The models updated like that are MBEvent and MBOrders I would like to map the data between the models using foreign key. event_id temp_id runner_id are the primary key for the three models. I would like to map runner_1_back_odds runner_2_back_odds runner_1_lay_odds runner_2_lay_odds from MBEvent as current_back_odds and current_lay_odds to MBBet I haven't been able to get foreign keys to work in django. Is what I'm requesting possible with foreign keys? class MBEvent(models.Model): event_id = models.BigIntegerField(primary_key=True) event_name = models.CharField(max_length=100,null=True) start_time = models.DateTimeField(null=True) is_ip = models.CharField(max_length=100,null=True) runner_1_name = models.CharField(max_length=100,null=True) runner_2_name = models.CharField(max_length=100,null=True) runner_1_id = models.BigIntegerField(null=True) runner_2_id = models.BigIntegerField(null=True) runner_1_back_odds = models.FloatField(null=True) runner_2_back_odds = models.FloatField(null=True) runner_1_lay_odds = models.FloatField(null=True) runner_2_lay_odds = models.FloatField(null=True) class MBOrders(models.Model): temp_id = models.FloatField(primary_key=True) event_id = models.BigIntegerField(null=True) event_name = models.CharField(null=True,max_length=300) runner_name = models.CharField(null=True, max_length=100) runner_id = models.BigIntegerField(null=True) odds = models.FloatField(null=True) remaining = models.IntegerField(null=True) pot_pro = models.IntegerField(null= True) rem_pot_pro = models.IntegerField(null=True) pot_lib = models.IntegerField(null=True) side = models.CharField(null=True, max_length=8) stake = models.IntegerField(null=True) status = models.CharField(null=True, max_length=10) time_stamp = models.DateTimeField(null=True) class MBBet(models.Model): runner_id = models.BigIntegerField(primary_key=True) runner_name = models.BigIntegerField(null=True) event_name = models.CharField(null=True,max_length=300) current_back_odds = models.FloatField() current_lay_odds = models.FloatField() bet_odds = models.FloatField(null=True) side = models.CharField(null=True, max_length=8) stake … -
Customizing JWT response from django-rest-framework-simplejwt
I'm setting up Django to send a JWT Response as opposed to a view. I tried using django-rest-framework-simplejwt. Provided in this framework, there is a function TokenObtainPairView.as_view() that returns a pair of jwt. I need to return the access token with another Json response as opposed to the two tokens provided. Ideally I would like one JsonResponse that contains an access token that is the same as this one: TokenObtainPairView.as_view(). I tried creating my own view which is provided below. Login URL Path urlpatterns = [ path('auth/', views.LoginView.as_view()), ] LoginView I created class LoginView(APIView): permission_classes = (AllowAny,) def post(self, request, *args, **kwargs): username = request.data['username'] password = request.data['password'] user = authenticate(username=username, password=password) if user is not None: payload = { 'user_id': user.id, 'exp': datetime.now(), 'token_type': 'access' } user = { 'user': username, 'email': user.email, 'time': datetime.now().time(), 'userType': 10 } token = jwt.encode(payload, SECRET_KEY).decode('utf-8') return JsonResponse({'success': 'true', 'token': token, 'user': user}) else: return JsonResponse({'success': 'false', 'msg': 'The credentials provided are invalid.'}) Pattern provided by framework. urlpatterns = [ ... path('token/', TokenObtainPairView.as_view()), ... ] It returns this token eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTQ5NDk3NDQ2LCJqdGkiOiI3YmU4YzkzODE4MWI0MmJlYTFjNDUyNDhkNDZmMzUxYSIsInVzZXJfaWQiOiIwIn0.xvfdrWf26g4FZL2zx3nJPi7tjU6QxPyBjq-vh1fT0Xs eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTU0OTQ5NzQ0NiwianRpIjoiOTNhYzkxMjU5NmZkNDYzYjg2OGQ0ZTM2ZjZkMmJhODciLCJ1c2VyX2lkIjoiMCJ9.dOuyuFuMjkVIRI2_UcXT8_alCjlXNaiRJx8ehQDIBCg If you go to https://jwt.io/ you will see what's returned -
Django OperationalError(2013, "Lost connection to MySQL server during query")
I've been getting the above error when using two servers to connect to the same Aurora DB. We're running a simple Django REST Framework on Elastic Beanstalk which connects to an Aurora DB cluster. Whenever we start up the DB and test the API from the EBS server connections go through fine. However, if I then start up my local development server connecting to the same DB, I get the operational error when going to the same route on the local server. I've tried increasing 'connect_time', 'interactive_timeout', 'max_execution_time', 'wait_timeout', 'max_allowed_packet', and 'max_user_connections' in increments up to the max. No change. The query shouldn't be big as there's only about 20 items in the table, and most of the time we're querying one item. We aren't managing the connection manually anywhere so it's not that we accidentally closed the connection prematurely. I've dug through the MySQL logs and only found the following message: Aborted connection ## to db: 'db_name' user: 'username' host: 'host_ip' (Got an error reading communication packets). Which seems to be pretty generic, and implies something on the dev server is closing the connection. The only way to get the development server to stop throwing this exception is to … -
Significant performance issue with Django Admin - foreign key labels
I’m experience significant performance issue with Django Admin. I have a mapping model where I map primary keys of 2 other modes In my FundManagerMappingAdmin I try to represent the foreign key of the 2 tables with a label from the foreign key models. The underlying models are about 4000 lines I’m experiencing slow performance when retrieving the list in admin and then also when editing and updating Could someone please point out the inefficiencies in this code? Is there a better way please? Admin.py @admin.register(ChampDwDimFundManagerMapping) class FundManagerMappingAdmin(admin.ModelAdmin): list_display = ['get_champ_fund_manager_id', 'get_evestment_name', 'get_sharepoint_name', ] def get_champ_fund_manager_id(self, obj): return obj.fund_manager_id get_champ_fund_manager_id.short_description = 'CHAMP Manager ID' def get_evestment_name(self, obj): return obj.evestment_fund_manager_id.manager_name get_evestment_name.short_description = 'Evestment Manager Name' def get_sharepoint_name(self, obj): return obj.sharepoint_fund_manager_id.manager_name get_sharepoint_name.short_description = 'Sharepoint Manager Name' def get_form(self, request, obj=None, **kwargs): form = super(ChampFundManagerMappingAdmin, self).get_form(request, obj, **kwargs) form.base_fields['sharepoint_fund_manager_id'].label_from_instance = lambda obj: "{} {}".format(obj.final_publications_fund_manager_id, obj.manager_name) form.base_fields['evestment_fund_manager_id'].label_from_instance = lambda obj: "{} {}".format(obj.evestment_fundmanager_id_bk, obj.manager_name) return form Models.py class FundManagerMapping(models.Model): fund_manager_id = models.AutoField(db_column='FundManagerId', primary_key=True) sharepoint_fund_manager_id = models.ForeignKey(SharePointFundManager, models.DO_NOTHING, db_column='SharePointFundManagerId') evestment_fund_manager_id = models.ForeignKey(EvestmentFundManager, models.DO_NOTHING, db_column='eVestmentFundManagerId') class EvestmentFundManager(models.Model): evestment_fund_manager_id = models.AutoField(db_column='eVestmentFundManagerId', primary_key=True) package_execution_id = models.IntegerField(db_column='PackageExecutionId') evestment_fund_manager_id_bk = models.CharField(db_column='eVestmentFundManagerId_BK', max_length=50) manager_name = models.CharField(db_column='ManagerName', max_length=255) class SharePointFundManager(models.Model): sharepoint_fund_manager_id = models.AutoField(db_column='SharePointFundManagerId', primary_key=True) package_execution_id = models.IntegerField(db_column='PackageExecutionId') research_fund_manager_id = models.CharField(db_column='ResearchFundManagerId', max_length=50, blank=True, null=True) … -
How to customize oscar address form fields?
after customizing django oscar app (address) and adding a new field named 'area' when I run migrate it gave me Unknown field(s) (area) specified for UserAddress I used the command ./manage.py oscar_fork_app address myappsfolder/ after creating the folder and __init__.py file in it then I started to customize the app like this: #myappsfolder/address/models.py from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from oscar.apps.address.abstract_models import AbstractAddress class Address(AbstractAddress): area = models.CharField(_("Area"), max_length=120, choices=settings.AREA_CHOICES, blank=True) from oscar.apps.address.models import * #myappsfolder/address/forms.py from oscar.apps.address import forms as base_forms class UserAddressForm(base_forms.UserAddressForm): class Meta(base_forms.UserAddressForm.Meta): fields = ['area'] I did't touch the admin.py , config.py and __init__.py that have been created by the command ./manage.py oscar_fork_app address myappsfolder/ also the __init__.py that I created in myappsfolder is empty, should I add something to these files ? What should I do to customize this app ? or any other app ? If I edited the models in oscar/apps/address/abstract_models.py it only apply in local host and the error in forms disappear , which means that django still reading the models from oscar/apps not from myappsfolder Hope someone help me with this Thanks. -
using pymongo with django and uwsgi
I have a djagno project which is deployed using uwsgi. in this project I used mongodb by mongoengine(pymongo) as orm. where I should place the mongoengine.connect() in the project. and which arguments ? I heared that pymongo is threadsafe. what is uwsgi settings for this case? -
Django apache localhost permissions problem
I guess that I should set a noob question alert on top. I am trying to deploy two Django projects locally with Apache and SQLite using mod_wsgi. Everything works fine, but I cannot figure out how to properly configure the permissions to my folders locally. Most of the relevant tutorials or posts treat the issue insufficiently or are quite difficult for me to understand. I have to say that I am using ubuntu 18.04. My current permissions are set by chmod -R 755 /var/www/env1 which is the parent directory of the project and also contains my virtual environment (using VirtualEnv). However, I understand that this is not the way to go, because I can directly download my .py files from the browser. This is the result of 'ls -la' inside the env1 folder. drwxr-sr-x+ 10 www-data www-data 4096 Φεβ 5 21:10 . drwxrwsr-x+ 3 www-data www-data 4096 Φεβ 1 12:39 .. drwxr-sr-x+ 9 www-data www-data 4096 Ιαν 26 00:05 astronomy drwxr-sr-x+ 3 www-data www-data 4096 Φεβ 1 13:43 bin drwxr-sr-x+ 9 www-data www-data 4096 Ιαν 26 00:05 gastronomy drwxr-sr-x+ 2 www-data www-data 4096 Ιαν 25 16:46 include drwxr-sr-x+ 3 www-data www-data 4096 Ιαν 25 16:46 lib drwxr-sr-x+ 2 www-data www-data … -
What is the reason for a noticable difference between postgis distance function and google maps distance calculator results?
I'm building a python/django based application in which it is important to measure the distance between two given geo-points with accuracy around at least 10 meters. The problem is that the results of postgis distance function and google maps distance calculator (between two pins) differentiate a lot. I placed two pins on Google Maps with the coordinates (52.162919 20.999998) and (52.163557 20.997626) and measured the distance via right-click -> measure distance and I also used postgis distance function to calculate the result in my code. from django.contrib.gis.db.models.functions import Distance from django.contrib.gis.geos import GEOSGeometry qs = queryset.annotate(distance=Distance( GEOSGeometry(f'SRID=4326;POINT(52.162919 20.999998)'), GEOSGeometry(f'SRID=4326;POINT(52.163557 20.997626)'), spheroid=True)) \ .values_list('id', 'distance', named=True) return qs class XXXSerializer(serializers.ModelSerializer): class Meta: model = XXX fields = ('id', 'distance') distance = serializers.SerializerMethodField() def get_distance(self, obj): return obj.distance.m The result of Database-base calculation is 270.868624085953 meters whereas the Google Maps-base result is 175,13 meters! The difference between those result is huge. Do you have any ideas what may be the cause, which result is the correct one and how to adjust my code so that it matches with the Google Maps distance result? -
Using Django for communicating with a Chrome Extension without creating a website
Can I use Django just for creating a server without using it to create a website? I want to use Django to be able to communicate with a Chrome extension. Basically, I want it to access a database linked to it, compute values, and then send the computed values back to the extension. I don't know how to use Django and plan on learning it for this project, but I wanted to know if it is possible to do so in the first place, and if not, what else can I use. All the tutorials I found online use Django to create a website; however, in my case, I don't want a website, I just want it to compute stuff on a server and send it back to a chrome extension. Also, in that case, would I be using Django REST? Hope this question makes sense! Thanks! -
How to add superscript to Draftail in Wagtail 2.0
I have added superscript to the Draftail editor in Wagtail following these instructions Adding superscript to Draftail in Wagtail 2.0 It works and renders with the "sup" tag on front end, but does not display as superscript on backend. I've tried adding 'style': 'vertical-align: super' in the feature config, but this does not help. Any suggestions? @hooks.register('register_rich_text_features') def register_superscript_feature(features): feature_name = 'superscript' type_ = 'SUPERSCRIPT' tag = 'sup' # Configure how Draftail handles the feature in its toolbar. control = { 'type': type_, 'label': 'x²', 'description': 'Superscript', 'style': 'vertical-align: super', } # Call register_editor_plugin to register the configuration for Draftail. features.register_editor_plugin( 'draftail', feature_name, draftail_features.InlineStyleFeature(control) ) # Configure the content transform from the DB to the editor and back. db_conversion = { 'from_database_format': {tag: InlineStyleElementHandler(type_)}, 'to_database_format': {'style_map': {type_: tag}}, } # Call register_converter_rule to register the content transformation conversion. features.register_converter_rule('contentstate', feature_name, db_conversion) I would like for it to display as superscript in the editor as well.