Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/chatgpt image url invalid
I am using the chatgpt API for some data analysis. So basically I am using django to have the user upload a file and then chatgpt analyses the photo. But when I feed it the encoded file I am getting the error 'Invalid Image URL' Here is my code This is the code that encodes the file: import base64 def download_file(file): file_encoded = base64.b64encode(file.read()).decode('utf-8') return file_encoded This is the view: def file_form(request): if request.method == 'POST': form = file_uploader(request.POST, request.FILES) if form.is_valid(): answer_analysed = chatgpt.analyse_answer(file_encoded=download_file(request.FILES['image']), question=None) return render(request, r'/Users/CormacCoffey/Desktop/AnswerAnalysisWeb/templates/home_page.html', {'answer_analysed' : answer_analysed}) else: form = file_uploader() return render(request, 'home_page.html', {'form': form}) The is the chatgpt call: client = OpenAI(api_key=api_key) print(file_encoded) headers = {"Content-Type":'application/json', 'Authorization' : f'Bearer {api_key}'} payload = { 'model' : "gpt-4o-mini", 'messages' : [{ "role": "user", "content": [ {"type":'If this image url is invalid can you tell me why', 'type': 'image_url', 'image_url':{'url' : f'data:image/jpeg;base64, {file_encoded}'} } ] }] } response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload).json() print(response) return response['choices'][0]['message']['content'] I tried to print out the image url and paste it into google but google says it was invalid -
Django app websocket connected client getting empty set even after active connection in connection handler
I am build a django app, it has following architecure. apps.py handlers.py signals.py views.py urls.py urls.py - It contains an endpoint there I have a view class from views.py. I capture POST request data there, this endpoint acts as a webhook. views.py - A view class with post method that handles incoming data to webhook endpoint. After getting data, I trigger a signal with data. signals.py - It has a Signal object created for custom signal. handlers.py - It has implementation of websockets package, have connected clients in self.clients property. apps.py - Inside this in ready method I am initializing WebSocketServer class from handlers.py, and on a given port in a separate thread. Handler.py code `import asyncio import websockets import json from django.dispatch import receiver from docapp.signals import gia_service_webhook_signal class WebSocketServer: instance = None # Class variable to hold the singleton instance clients = set() # Set of connected clients def __init__(self, host='localhost', port=8787): self.host = host # Store the host self.port = port # Store the port WebSocketServer.instance = self # Set the singleton instance # Connect the signal to the handler method gia_service_webhook_signal.connect(self.handle_gia_service_webhook) async def handle_connection(self, websocket, path): print(f"New connection attempt on path: {path}") # Debugging # Register … -
How to create a drop in serializer replacement for Django ReadOnlyViewSet that is very fast?
I've noticed that Django Serializers are extremely slow even after N+1 type problems (I think). I'm basing that off my own experience and questions such as these ModelSerializer is extremely slow in Django REST framework https://hakibenita.com/django-rest-framework-slow In my case I have a model for users from django.contrib.auth.models from rest_framework.viewsets import ReadOnlyModelViewSet class UserViewSet(ReadOnlyModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer filterset_fields = {'groups__name': ['exact', 'in'] If I have a function like: def serialize_user(user_instance): return {f: getattr(user_instance, f) for f in user_instance._meta.fields} how do I write a custom serializer class so I can use it as serializer_class = MyUserSerializer and it skips validation etc. I expect since it's readonly validation also doesn't make as much sense but maybe I'm missing something. -
Redirect to Django View after AJAX GET request with form prefilled data
I have a ListView to render page with table of objects. The first column are checkboxes to perform some actions on multiple objects (not a formset). Each checkbox contains an object id as value and utilizing AJAX requests to perform such actions. There is no issues with direct POST request as I send bunch of ids in array, validate them through the form and update(). However I'm experiencing some difficulties with GET request which suppose to be simplier: I have a view to edit object (FBV). The goal is to redirect to that view with field contains all those ids checked on ListView. But I just came to know that I can't call render() after AJAX call so I'm wondering what is the right way to handle such a redirect passing initial data to form presents in that view's context. Simplified code: class ProducutsListView(ListView): model = models.Product template_name = "production/products_list.html" paginate_by = 50 The view to redirect to: def product_update_view(request): if request.method == "POST": form = forms.ProductUpdateForm( request.POST, ) products = form.cleaned_data["products"] ------------------------------------- # some more validated data extracting ------------------------------------- products.update(**fields) return redirect("products_list") else: form = forms.ProductUpdateForm() if is_ajax(request): products_form = forms.ProductsMultipleForm(request.GET) # form contains only one field "poducts" represents … -
html email templates with django
How can I send HTML emails with embedded images in django application? How can I embed images like logos which will be displayed in the emails sent? I tried using {% load static %} in my html email template, but still no luck -
Django - get local listening IP address
In Django, how can I get Django's local IP 192.168.1.200 that it is presently listening on? I need to use the IP in Django logging format. settings.py ALLOWED_HOSTS = ['192.168.1.200', '127.0.0.1'] Run server python manage.py runserver 192.168.1.200:8000 -
Add Variable Django Form without Putting in Field
I am trying to add a variable to a Django form, without the variable being a field on the form. I want a set of checkboxes that are checked if the user is subscribed. When the form is loaded, the options are not loaded successfully. All subscriptions are checked when the form loads. The update function works appropriately and the database reflects the correct selections after submission. Please help me figure out why the appropriate usersubscriptions are not checked when the form loads. models.py class Subscription(models.Model): name = models.CharField(max_length=100, null=False, blank=False) description = models.TextField(null=False, blank=False) def __str__(self): return self.name class UserSubscription(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) subscription = models.ForeignKey(Subscription, on_delete=models.CASCADE) start_date = models.DateTimeField(auto_now_add=True) end_date = models.DateTimeField(null=True, blank=True) def __str__(self): return self.user.username + " " + self.subscription.name views.py @login_required(login_url='login') def managesubscription(request): userSubscriptions = UserSubscription.objects.filter(user=request.user) subscriptions = Subscription.objects.all() if request.method == 'POST': form = ManageSubscriptionForm(request.POST, userSubscriptions=userSubscriptions) if form.is_valid(): subscriptions = form.cleaned_data['subscriptions'] UserSubscription.objects.filter(user=request.user).delete() for subscription in subscriptions: print(subscription) UserSubscription.objects.create(user=request.user, subscription=subscription) messages.info(request, 'Subscriptions Updated') return redirect('dashboard') form = ManageSubscriptionForm(userSubscriptions=userSubscriptions, initial={'subscriptions': subscriptions, 'userSubscriptions': userSubscriptions}) return render(request, 'account/managesubscriptions.html', {'form': form}) forms.py class ManageSubscriptionForm(forms.ModelForm): subscriptions = forms.ModelMultipleChoiceField( queryset=Subscription.objects.all(), widget=forms.CheckboxSelectMultiple(attrs={'class': 'form-check-input'}), ) def __init__(self, *args, userSubscriptions, **kwargs): self.userSubscriptions = userSubscriptions print("here", userSubscriptions) super().__init__(*args, **kwargs) class Meta: model = Subscription … -
How to count the number of equities in a portfolio from credit/debit transactions in Django?
Apologies if this is a terrible writeup as this is my first question. I am trying to count the equities remaining in a user's Django portfolio after many equity transactions may have been made in that portfolio. The following is a summary of my models and my attempt. Currently I am filtering portfolios that have equity(ies) but am counting all the transactions within that portfolio. models Class Portfolio(models.Model): name = models.CharField(...) owner = models.ForeignKey(User, ...) equity = models.ManytoManyField(Equity...., through="PortfolioEquity") Class Equity(models.Model): symbol = models.CharField(...) name = models.CharField(...) Class PortfolioEquity(models.Model): BUY = "BUY" SELL = "SELL" TRANSACTION_CHOICES = { BUY: "Buy", SELL: "Sell", } portfolio = models.ForeignKey(Portfolio, ...) equity = models.ForeignKey(Equity, ...) transaction = models.CharField(max_length=4, choices=TRANSACTION_CHOICES) amount = models.DecimalField(max_digits=8, decimal_places=2) shares = models.DecimalField(max_digits=8, decimal_places=3) date = models.DateField() views def get(self, request): positive_equities = PortfolioEquity.objects.values('equity').annotate( tot_shares=Sum(Case( When(transaction="BUY", then=F('shares')), When(transaction="SELL", then=-F('shares')), default=Value(0), output_field=DecimalField() ))).filter(shares__gt=0) portfolios = Portfolio.objects.annotate(equity_count=Subquery( positive_equities.filter(portfolio=OuterRef('pk')) .values('portfolio') .annotate(count=Count('equity')) .values('count') )).filter(equity_count__gt=0) return self.render_to_response({'portfolios': portfolios}) html {% for portfolio in portfolios %} <p> Owner: {{ portfolio.owner.get_full_name }} Equit{{ portfolio.equity_count|pluralize:'y,ies' }}: {{ portfolio.equity_count }} </p> {% endfor %} Transactions: Buy; 5x AAPL; Jan. 1 2024; $300.00 Sell; 5x AAPL; Jan. 15 2024; $350.00 Buy; 1x AA; Jan. 20 2024; $200.00 Output should be 'Equity: … -
Video security in DRF
I was building a website for video lessons in DRF. I'm sending the video url directly to Front end. The person who receives the URL can download the video. What I can do is make sure I can't upload the video. Are there any ready-made examples How can I do that? I couldn't find information about this in the DRF class LessonVideoViewSet(viewsets.ReadOnlyModelViewSet): queryset = LessonVideo.objects.all().select_related('chapter') serializer_class = LessonVideoSerializer filter_backends = [filters.SearchFilter, DjangoFilterBackend] search_fields = ['chapter'] filterset_fields = ['chapter'] -
What is the process to ensure local Django database stucture updates get updated on production?
Currently I am running Django 5.1.1 and having it hosting on Google App Engine standard environment. When I make I am working on the site, I have the Cloud SQL Auth Proxy running. This means that any database changes that happen, happen on the cloud database. Going forward, I want to have two databases: a test database that is local, and the production one that is the one that I am using now in the cloud. I assume this would be accomplished by having settings.py check for environment variables, and setting the proper database to use. Then, when I deploy changes to Google, I will have use the Google cloud console to run the migrations to update the production database structure. Is this the correct way to handle having seperate test and production databases? Are there any gotchas or other things to worry about with this setup? -
File not being written to
I am working on a website with django and am currently trying to add a way for users to upload a file to the website and just to test have it write to my pc. But the problem is that nothing is being written to my desktop. I am not getting any errors just nothing is being written. The file I am testing with is a jpeg. The function: def download_file(filename): with open(r'C:\Users\kenco\OneDrive\Desktop\file.jpg', 'wb+') as destination: destination.write(filename) The django view: def file_form(request): if request.method == 'POST': form = file_uploader(request.POST,request.FILES) if form.is_valid(): download_file(filename=request.FILES['file']) return HttpResponseRedirect('/success') else: form = file_uploader() return render(request, 'home_page.html', {'form' : form}) The form: from django import forms class file_uploader(forms.Form): question = forms.CharField(max_length=100) image = forms.FileField() I tried to just write to desktop and it didnt work. I tried to do the string without a r string. And I tried to write it without the .jpg This code is also based around the django documentation: https://docs.djangoproject.com/en/5.1/topics/http/file-uploads/ -
Default location in wagtail-geo-widget
I have successfully added a GeoAddressPanel and LeafletPanel to a Wagtail admin page using Wagtail Geo Widget. I'd like to override the default location but can't figure out how, any ideas? This is what I have and that's working fine in the Wagtail admin: MultiFieldPanel( [ GeoAddressPanel("address", geocoder=geocoders.NOMINATIM), LeafletPanel( "location", address_field="address" ), ) Tried some suggestion by Claude.ai, but it did not have a clue. -
What will happen if the reported size of a streaming download is inaccurate?
I implemented a download view in my django project that builds a zip archive and streams it on the fly. The files included in the archive are 1 tsv file and any number of xml (from a set of search results) that are organized into a series of directories. The download works, but there is no progress. We have tested a small download (47Mb) and a large one (3Gb). I was thinking that it would be nice to have a progress bar to give the user some idea of how long the download will take, however, from what I've read, predicting the size of a zip file is tricky/prone-to-inaccuracy, so I'm wondering (since I'm very inexperienced with zip file generation [let alone streaming downloads])... What would happen with a download from a user perspective if I supply an estimated size? Specifically, would a download fail? What would happen if the estimated size is too big? What would happen if the estimated size is too small? Are there any alternate solutions for this problem space that I should consider? -
Images/files not shown after psycopg2 to psycopg3 upgrade
After upgrade from psycopg2 to psycopg3 in my Django project, my images (which I needed to store as bytea in the database) no longer render. Consider person = Person.objects.get(pk=1). I then do FileResponse(person.picture, as_attachment=True) to get the picture and serve it to the response. With psycopg2, type(person.picture) yielded memoryview. With psycopg3, I get bytes. The 2 to 3 differences documentation doesn't indicate what could be wrong. -
is_valid() function of the authentication form is not working when the credential is wrong
I have extended the built in authentication form to use bootstrap naming LoginForm. If the user gives wrong credential, I want to show message that "Wrong Credential".But the is_valid() function only work when the credential is (username,password) is exactly the same. Let's say i put username right but wrong password, then the is_valid() function doesn't work.As a result i cant show the message that the password is wrong. But I have created another form by subclassing forms.Form. in that case the is_valid() faunction works for wrong credential too and shows the message for wrong username and password. this is my form. class LoginForm(AuthenticationForm): username = UsernameField( widget = forms.TextInput(attrs={'autocomplete':'off','class':'form-control','placeholder':'Enter your email'}) ) password = forms.CharField( label=_('Password'), strip=False, widget=forms.PasswordInput(attrs={'autocomplete':'off','class':'form-control','placeholder':'Enter your password'}) ) this is the views.py def signin(request): if request.method == 'POST': form = LoginForm(data=request.POST) if form.is_valid(): print('1') username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(request,username=username,password=password) print('2') if user is not None: login(request,user) print('3') return redirect('registration') else: print('4') messages.warning(request,'Wrong Credentials!') else: # Use form.errors for displaying errors print(form.errors) else: print('get') form = LoginForm() return render(request,'account/login.html',{'form':form}) since this form does not work. for testing purpose I've created another form. and this works fine and shows the error message of "Wrong credentials" … -
Flutter & Django : How do we authenticate user by JWT?
I'm developing authentication pages for my app using Flutter for the mobile frontend and Django for the backend. The login functionality works perfectly, but I'm encountering an issue with the logout process. When I try to log out, it returns a "forbidden" error, indicating that the user is not authenticated. I suspect the issue might be related to how I'm setting the jwt in the headers for the HTTP requests in Flutter. Could someone please take a look and help me troubleshoot this? Thank you! Flutter class AuthService { // Base URL for the user endpoints final String _loginUrl = '$BASE_URL/users/login'; final String _isLoggedInUrl = '$BASE_URL/users/is_logged_in'; final String _logoutUrl = '$BASE_URL/users/logout'; Future<String?> login(String email, String password) async { final response = await http.post( Uri.parse(_loginUrl), headers: {'Content-Type': 'application/json'}, body: json.encode({'email': email, 'password': password}), ); if (response.statusCode == 200) { // Store the JWT token in shared preferences final prefs = await SharedPreferences.getInstance(); final token = json.decode(response.body)['jwt']; await prefs.setString('jwt', token); return token; } else { throw Exception('Failed to login'); } } Future<bool> isLoggedIn() async { print("In isLoggedIn"); final prefs = await SharedPreferences.getInstance(); final token = prefs.getString('jwt'); // If token is null, the user is not logged in if (token == null) { … -
multiple await expression blocking the wxecution
I am using django channels for a chatbot implementation and i am using ayncwebsocketconsumer # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) event_type = text_data_json.get('event_type', '-') if event_type not in EventTypeChoicesChat.choices[0]: logger.error(f"{event_type} is not a valid EventType") else: # NOTE: we need to refresh session and set (user_type ,user) on every message await self.refresh_session() self.user = self.scope['user'] if not self.scope['user'].is_anonymous else None self.user_type = text_data_json['user_type'] chat_data = text_data_json['chat_data'] # save the message first(SessionMessage model) saved_msg = await self.save_message({ "session": self.session, "sender": self.user if self.user else None, "user_type": self.user_type, "chat_data": chat_data }) # prepare the message_response to be sent response = { "event_type": event_type, "user_type": self.user_type, "sender_icon": await self.set_sender_icon(self.user_type), "id": saved_msg.id, "created_at": str(saved_msg.created_at), "chat_data": chat_data } # Send message to room group await self.channel_layer.group_send( self.room_group_name, {"type": 'send_chat_message', "data": response} ) # update last message received time on session self.session.last_chat_received_time = datetime.now(timezone.utc).isoformat() await database_sync_to_async(self.session.save)() # If AI is active and the user is not AI, send the message to AI if self.session.is_ai_active and self.user_type != SessionUserTypeChoices.AI: session_id = self.room_name bot_id = await database_sync_to_async(lambda: self.session.bot.id)() org_id = await database_sync_to_async(lambda: self.session.bot.org.id)() goal = 'you are intelligent customer service agent' ai_response_url = settings.AI_BASE_URL + f'/api/v1.0/ai/conversion/{bot_id}/{org_id}' query_params = f"query={chat_data['msg']}&user_session_id={session_id}&goal={goal}" ai_response_url_with_query = ai_response_url … -
How to Properly Decode Quoted-Printable .eml Files in Django to Avoid = Artifacts?
I'm working on a Django project where I need to handle .eml files. The email content often has Quoted-Printable encoding, which causes some characters to be incorrectly displayed. For example, certain characters appear as = signs or have = signs inserted within words. Here’s a sample of what the decoded content looks like: We request all our =ustomers - For any Remittance please make sure to stay in touch with =ur office Tel no : +97150 267 4240 Mr .Kalpesh. =o:p> All the Payment =ill be accepted only to East VISON CONTAINER LINE a/c and NOT any of =he personal account. Also please make =ure to reply the mails only to domain =vcline.com. We wouldn't be =esponsible for any financial fraud in case bank account is not verified =ith us on whatsapp / WeChat. As you can see, characters such as "w" and "R" are replaced with = or the equals sign appears in unexpected places. What I've Tried: Standard Decoding of Quoted-Printable: I tried decoding the email content using Python's quopri library, but the problem persists. Email Package in Python: I used Python's email package to parse the .eml file and manually decoded the content based on the Content-Transfer-Encoding … -
django make migration command error for Table does not exist
We have the models.py file like this : class Car(models.Model): brand = models.CharField(max_length=50 , null=True , blank=True) model = models.CharField(max_length=50 , null=True , blank=True) code = models.CharField(max_length=20 , unique=True) class Label(models.Model): COLORS = ( ('blue' , 'blue'), ('red' , 'red'), ('light_green' , 'light_green'), ('black' , 'black'), ('white' , 'white'), ('orange' , 'orange'), ('purple' , 'purple'), ) name = models.CharField(max_length=20) color = models.CharField(max_length=30 , choices=COLORS) class Skill_Name(models.Model): label = models.ForeignKey(Label , on_delete=models.CASCADE , null=True , blank=True) name = models.CharField(max_length=50) have_different_cars = models.BooleanField(default=True) class Skill(models.Model): car = models.ForeignKey(Car , on_delete=models.CASCADE, null=True , blank=True) skill = models.ForeignKey(Skill_Name , on_delete=models.CASCADE , null=True , blank=True) class Provider(models.Model): user = models.OneToOneField(User , on_delete=models.CASCADE , related_name="user_provider") name = models.CharField(max_length=100) skills = models.ManyToManyField(Skill , blank=True) And when we try to makemigration we get the error that : django.db.utils.ProgrammingError: (1146, "Table 'arenadatabase.providers_skill_name' doesn't exist") i think that order of migration is not right! So I deleted migration files to migrate the app again but It does not worked for me! anybody can help me please? -
Why I can not see the authorize button in drf-spectacular's swagger?
Before we had a monolyth, but now we are moving to microservices architecture, and here the settings for my drf-spectacular, but I do not have the Authorize button as I had before, exactly with this settings just instead of custom authentication was 'rest_framework_simplejwt.authentication.JWTAuthentication', REST_FRAMEWORK = { 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', 'DEFAULT_AUTHENTICATION_CLASSES': ('custom.custom_authentication.CustomAuthentication',), } SPECTACULAR_SETTINGS = { 'TITLE': 'My Title', 'DESCRIPTION': 'My description', 'VERSION': '0.0.1', 'SERVE_INCLUDE_SCHEMA': False, 'SERVE_PERMISSIONS': ['rest_framework.permissions.IsAdminUser'], 'SERVE_AUTHENTICATION': [ 'rest_framework.authentication.SessionAuthentication', 'custom.custom_authentication.CustomAuthentication', ], 'SWAGGER_UI_SETTINGS': {"filter": True, "persistAuthorization": True} } What might be the problem for not seeing the authorize button? -
Why does my Blog API CustomUser have an error when sending request for a CustomUser detail?
I have two Blog API's in Django Rest Framework. One uses Django's default User model whilst the other uses a CustomUser. Authentication works well in both cases. I have similar serializers, viewsets and routers all configured. The endpoints that returns a collection of posts and users works well as well as the endpoint for a single post. Also that of a single user works only while using Django's default user model. However when I try to access a single CustomUser, I get this error: AttributeError at /api/v1/users/3/ 'CustomUser' object has no attribute 'author' Request Method: GET Request URL: http://127.0.0.1:3412/api/v1/users/3/ Django Version: 5.1.2 Exception Type: AttributeError Exception Value: 'CustomUser' object has no attribute 'author' Exception Location: C:\Users\Names\OneDrive\my_apps\django_apps\blog_API\api\permissions.py, line 16, in has_object_permission Raised during: api.views.CustomUserViewSet The exception occurs on the last line: from rest_framework import permissions class IsAuthorOrReadOnly(permissions.BasePermission): """ Object-level permission to only allow authors of an object to edit it. Assumes the model instance has an `author` attribute. """ def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.author == request.user I have looked at the location of the error and tried print debugging to print the User object and in both cases (Default User model and CustomUser … -
Copying database and authentication fails?
I have django project which has database on aws RDS. now I copied the database with command. PGPASSWORD=XXXXXX createdb -U dbuser -h kkk.cgrxw5ome4nb.ap-northeast-1.rds.amazonaws.com -p 5432 -T old_db new_db It copies the database correctly, but I can not login any accounts with new database It says password is uncorrect [auth] Error! Password wrong However I just copied the database, is there any problem? Class MyAuthBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): logger.info("[auth] 2.Try Django auth backend is Auth") try: user = m.CustomUser.objects.get(username=username) except m.CustomUser.DoesNotExist: logger.info("[auth] Error! Django user can not be found") return None else: if user.check_password(password) and self.user_can_authenticate(user): return user else: logger.info("[auth] Error! Password wrong") -
How to restrict frontend pages in React based on user permissions in Django restframework?
I'm developing a web application with Django restframework (backend) and React (frontend). In the backend, I have several endpoints restricted by specific permissions, and that part works well. Now, I need to ensure that in the frontend, each user only sees the pages where they have at least one permission to make changes. Ideas I've considered for implementation: Adding a JSON field to the user table that includes a list of accessible pages for each user. This way, I could easily query the accessible pages directly. During login, along with the token or other response data, map over the user’s permissions to generate a list of accessible pages and send it to the frontend right away. What would be the best approach to implement this kind of access restriction in the frontend? Is there an established method to manage page access in React based on user permissions received from the backend? Thank you in advance for any guidance. -
Count unique values and group by date
I have a table like: client_id action date (datetime) 1 visit 2024-10-10 10:00 1 visit 2024-10-10 12:00 1 visit 2024-10-10 13:00 2 visit 2024-10-10 13:00 So, I need to count amount of unique clients with group by date. The result should look like {'date': 2024-10-10, "count_visits": 2}. I tried several variations with annotate(unique=True) and OuterRef, but it never worked to group by date. -
How could you show a bootstrap alert on mouseover of a choices field in a django form?
I have a questionnaire based on django form and I need to show a note if a user hovers or clicks on a question before it submits. The django form is loaded in from a custom question and question choices model. I had some luck with custom question formatting prior by handing django form label and choices a mark_safe str with html formatting of the title and options within. I took it a step further for this and attempted to put in some java script as well. Though it does not show anything on mouseover of the choice. In this case answer.content would be the individual choice underneath the question. Below is my mark_safe code which is only called when there is an explanatory_note for this answer choice, it is called right before handing it to django form typed choice field. I tried having it within the html page, but it would not work as it wouldn't be connected to an individual choice under a question. I have confirmed that the following str is correctly handed to the django form and used as a choice. It does correctly display answer.content. mark_safe("<p id=\"" + str(n) + "\">" + answer.content + "</p> …