Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: __init__() got an unexpected keyword argument 'deon_deletefault'
hello I am trying to run a project with python 3.8 and django 3.1.7 and I get the following error: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/mauricio/Escritorio/entornos/red/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/mauricio/Escritorio/entornos/red/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/mauricio/Escritorio/entornos/red/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/home/mauricio/Escritorio/entornos/red/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/home/mauricio/Escritorio/entornos/red/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/mauricio/Escritorio/entornos/red/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/mauricio/Escritorio/entornos/red/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/mauricio/Escritorio/entornos/red/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/mauricio/Escritorio/RedDebate/reddebate/resumen/models.py", line 14, in <module> class Debate(models.Model): File "/home/mauricio/Escritorio/RedDebate/reddebate/resumen/models.py", line 25, in Debate args_max = models.IntegerField(deon_deletefault=1) TypeError: __init__() got an unexpected keyword argument 'deon_deletefault' I send you the code that is associated with the error: # … -
How do I update information in the database using POST in Django?
I'm creating a contact list that lets the user Add, Delete, and Edit using Django. I've been able to slowly work my way through most of it except for updating the information in the database after the user hits "Submit". I've tried a few different methods that I thought might work, but unfortunately I just ended up with Errors. So I'm wondering, after I render the html edit form and the user edits whatever field they choose and hits submit, how do I receive that information and update the database with it? I've read that I need to use a 'POST' but I'm not sure how to set it up. views.py file from django.shortcuts import render, redirect from django.http import HttpResponse, HttpRequest from django.template import loader from .models import Contact def index(request): return HttpResponse("Hello, world. You're at the contacts app.") def list(request): contacts_list = Contact.objects.all() return render(request, 'index.html', {'contact_list':contacts_list}) def add(request): if request.method == 'POST': new_contact = Contact( firstname = request.POST['firstname'], lastname = request.POST['lastname'], age = request.POST['age'], phone = request.POST['phone'], email = request.POST['email'], gender = request.POST['gender'], ) new_contact.save() return redirect('/contacts/list/') return render(request, 'addform.html') def edit(request, cur_id): if request.method == 'GET': contact_to_edit = Contact.objects.get(id=cur_id) contacts_list = Contact.objects.all() return render(request, 'editform.html', {'cur_contact':contact_to_edit, … -
Customizing Django's many-to-many admin widget
I have a many to many field that contains ~7000 options and it is starting to take a long time to load the page when I want to edit or add new objects in the admin interface. I'm aware of the filter_horizontal or filter_vertical options to change the widget for many to many, but is there a way to block the widget from showing me those 7000 options? I only need to be able to add new ones (searching would be nice, but not required). -
Multiple models in a single get_queryset() to populate data in a template
I'm trying to push multiple data sets into a template, home.html, using class based views. I don't know if this is the right way or if there is a better way to do this. views.py class HomePage(ListView): template_name = 'home.html' context_object_name = 'result' def get_queryset(self): query1 = {} query2 = {} query3 = {} query1 = table1.objects.filter(username=self.kwargs['username']) query2 = table2.objects.filter(username=self.kwargs['username']) query3 = table3.objects.filter(username=self.kwargs['username']) return (query1, query2, query3) home.html {% for query1_data in result %} {% if query1_data.url %} <img src="{{query1_data.url}}"> {% endif %} {% endfor %} {% for query2_data in result %} {% if query2_data.text %} ... {% endif %} {% endfor %} It works but it seems like there should be a better way to do this. Thanks! -
Why am I getting error "an unexpected keyword argument 'choises'" in this case?
I am trying to make django models. This is my models.py I am getting this error: TypeError: init() got an unexpected keyword argument 'choises' class Quality(Enum): camrip = "CAMRip" TS = "Telesync" dvdrip = "DVDRip" tvrip = "TVRip" hdtvrip = "HDTVRip" bdrip = "BD-Rip" class Another(models.Model): quality = models.CharField(max_length = 30, choises = [(tag, tag.value) for tag in Quality]) -
Page not found [404] in Django
I am trying to get all the post, posted in the same category. So my url looking like this, '..../category/Sports' where sports is a category. But if I enter this url, I got page, not found. I have also a html file called category. I also made makemigrations and migrate a several times My views.py file: from .models import Post, Category .............. def CatView(request, cats): posts = Post.objects.filter(category=cats) return render(request,'category.html',{"cats":cats, 'posts':posts}) urls.py file: from django.urls import path from .views import * urlpatterns = [ path('',HomeView.as_view(), name='home'), path('article/<int:pk>', ArticleDetailView.as_view(), name='article_detail'), path('add-post/', Addblogview.as_view(), name='add_post'), path('add-category/', AddCategoryview.as_view(), name='add_category'), path('article/edit/<int:pk>', UpdatethePost.as_view(), name='add_task'), path('article/delete/<int:pk>', DeleteThePost.as_view(), name='delete_task'), path('category/<int:cats>', CatView, name='category'), ] If I change <str:cats> I ended up with ValueError Field 'id' expected a number but got 'Sports' My models.py file: from django.db import models from django.contrib.auth.models import User from django.urls import reverse from datetime import datetime, date class Category(models.Model): name = models.CharField(max_length=255, default='uncategorized') def __str__(self): return self.name def get_absolute_url(self): return reverse('article_detail',args=str(self.id)) class Post(models.Model): title = models.CharField(max_length=255) title_tag=models.CharField(max_length=255) author = models.ForeignKey(User,on_delete=models.CASCADE) body = models.TextField() post_date = models.DateField(auto_now_add= True) category = models.ForeignKey(Category,on_delete=models.CASCADE) def __str__(self): return self.title + "|" + str(self.author) def get_absolute_url(self): return reverse('article_detail',args=str(self.id)) My category.html: {{cats}} -
nested custom simple template tag in django
I have a custom template tag as follows : @register.simple_tag() def math(operand1, operator, operand2): add = ['add', 'addition', 'plus'] sub = ['sub', 'subtraction', 'minus'] mul = ['mul', 'multiplication', 'multiply'] div = ['div', 'division', 'divide'] mod = ['mod', 'rem', 'remainder', 'modulus'] pow = ['pow', 'power', 'raiseto', 'powerof', 'exponent', 'exponentiation'] log = ['log', 'logarithm'] if operator in add: return operand1 + operand2 elif operator in sub: return operand1 - operand2 elif operator in mul: return operand1 * operand2 elif operator in div: return operand1 / operand2 elif operator in mod: return operand1 % operand2 elif operator in pow: return operand1 ** operand2 elif operator in log: return math.log(operand1, operand2) else: raise ArithmeticError(f'Couldn\'t find the operator {operator} in math function') And I want to perform a nested operation like the following : <h1>Marks : {% math {% math graph.cutoff_marks|get_dic_item:data "mul" 2 %} "sub" graph.cutoff_marks|get_dic_item:data %}</h1> How do I perform it? -
Exporting data with DJango and import_export, columns are duplicated
I am creating a django app and I'm using the import_export package. I have defined my resource with fields that have both the attribute and column_name set. When I export to xlsx (or csv) I get columns with the attribute as header, and a duplicate column with the column_name header. Including the fields attribute in the Meta subclass doesn't affect this behavior. # app\resources.py class RoleResource(resources.ModelResource): name = Field(attribute="name", column_name="Sales Role") role = Field(attribute="default_role" column_name="System Role") plan = Field(attribute="default_plan" column_name="System Plan") class Meta: model = Role # fields = ('name', 'default_role', 'default_plan') # commenting this doesn't change behavior The final output with Meta.fields commented out has 6 columns: Sales Role, System Role, System Plan, id, default_role, default_plan. The final output with Meta.fields uncommented has 5 columns: Sales Role, System Role, System Plan, default_role, default_plan. I thought the column_name was cosmetic. Why am I getting two duplicated columns? -
Django-Channels multiple connections from the same client
I have a django-channels application deployed with daphne and nginx. There's only one connection url: /ws. Whenever I connect to it (I tried using the standard JS WebSocket and Node websocket implementations) with multiple connections from the same machine, the responses from server to client always go to the last connected ws connection. I pass the remote IP as well as the remote port from nginx to the python application: proxy_set_header X-Forwarded-Port $remote_port; The daphne logs show that the python application is aware of the remote ports: 129.81.255.107:48276 - - [10/Mar/2021:00:25:38] "WSCONNECTING /ws/" - - 129.81.255.107:48276 - - [10/Mar/2021:00:25:38] "WSCONNECT /ws/" - - 129.81.255.107:12111 - - [10/Mar/2021:00:25:40] "WSCONNECTING /ws/" - - 129.81.255.107:12111 - - [10/Mar/2021:00:25:40] "WSCONNECT /ws/" - - Even if I connect through different urls, the problem persists: 129.81.255.107:25976 - - [10/Mar/2021:00:27:13] "WSCONNECTING /ws/aaaaaa/" - - 129.81.255.107:25976 - - [10/Mar/2021:00:27:13] "WSCONNECT /ws/aaaaaa/" - - 129.81.255.107:8010 - - [10/Mar/2021:00:27:15] "WSCONNECTING /ws/bbbbbbb/" - - 129.81.255.107:8010 - - [10/Mar/2021:00:27:15] "WSCONNECT /ws/bbbbbbb/" - - I'm thinking, if I send back the client port as a header in the response (from server to client), the client will know which specific ws connection to direct the response. But I have two problems with that: I … -
I'm new to Django and I'm having trouble displaying categories in this website
Models.py class Listing(models.Model): title = models.CharField(max_length=64, default="") bid = models.ForeignKey(Bid, on_delete=models.CASCADE, related_name="listing", default=None,) description = models.TextField(default="") image_url = models.CharField(max_length=200, default="") date = models.DateTimeField(default=timezone.now) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="listings", default="") is_closed = models.BooleanField(default=False, blank=True, null=True) watchlist = models.ManyToManyField(User, blank=True, related_name="watching") owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="listing", null=False, blank=True, default="") def __str__(self): return self.title #the category class class Category(models.Model): category = models.CharField(max_length=64) def __str__(self): return self.category Views.py This is where I think the problem is because i'm not very familiar with the methods, if I user category = request.POST["category], I get an error saying multivalue dict..., I'm just stuck here category = requset.POST.get("category") listings = category.listings.all() return render(requset, "auctions/categories.html", { "listings":listings, }) **categories.html** {% extends "auctions/layout.html" %} {% block body %} Categories <form action="{% url 'categories' %}" method="post"> <div class="form-group"> <label for="categories">Category</label> <select class="form-control" name="categories" id="categories"> {% for category in categories %} <option>{{category}}</option> {% endfor %} </select> </div> </form> {% for listing in listings %} {% if not listing.is_closed or user == listing.bid.user %} <p></p> <div class="card" style="width: 60rem;"> <img class="card-img-top" style="width: 20rem;" src="{{listing.image_url}}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{listing.title}}</h5> <p class="card-text">{{listing.description}}</p> <p>Bid: {{listing.bid}}</p> <p>Created {{listing.date}}</p> </div> <div class="card-body"> <a href="{% url 'listing' listing.id %}" class="btn btn-primary">More</a> </div> </div> <p></p> {% endif … -
ValueError at /search - Python Django
I'm doing the CS50 Course wiki page, and whenever I try to search for something in my search box (that is something not in my entries) I get ValueError The goal is to return the body of search.html instead of this error. ValueError at /search The view encyclopedia.views.search didn't return an HttpResponse object. It returned None instead. Views.py from django.shortcuts import render, redirect from . import util from django.db.models import Q import markdown from django.http import HttpResponseRedirect def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def topic(request, title): mdStr = util.get_entry(title) if mdStr == None: mdStr = "## Page was not found" mdStr = markdown.markdown(mdStr) return render(request, "encyclopedia/entry.html", {'content': mdStr, 'title': title}) def search(request): search_box = request.GET.get('q').strip() entries_list = util.list_entries() find_entries = list() if search_box in entries_list: # if found the title then it returns the HTML Page. return HttpResponseRedirect(f"wiki/{search_box}") for entry in entries_list: if search_box in entry: find_entries.append(entry) if find_entries: return render(request, "encyclopedia/search.html", { "search_result": find_entries, # list of all the entries that has substring "search": search_box # the query written }) urls.py from django.urls import path, include from . import views urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:title>/", views.topic, name="topic"), path("search", views.search, name="search"), ] search.html {% extends … -
Get path of the uploaded file in FileField Django model to use read_csv
I've been searching a lot but cannot find an answer that works, so decided to post the question in this beautiful community. My question is very similar to the one posted here, but the only solution provided there doesn't work for me (or I need further explanation on how to do it?). Also, read this but didn't work. I have a web app that uses ReactJS for the frontend and Django for the backend. Users upload a file and I need to use pandas in my backend to read that file to a csv. Users successfully upload their file and it is stored in my uploads folder. My problem? I need to get the path to the uploaded file so I can use it in pandas.read_csv(file_path). How can I do this? Here is my models.py: # models.py from django.db import models class UserInput(models.Model): file = models.FileField(upload_to='uploads/', max_length=None) language = models.CharField(max_length=200) features = models.DecimalField(max_digits=1, decimal_places=0) def __str__(self): return self.file, self.language, self.features Here is my views.py: # views.py from .models import UserInput from .serializers import UserInputSerializer from rest_framework import viewsets from rest_framework.permissions import AllowAny, IsAuthenticated import pandas as pd class UserInputViewSet(viewsets.ModelViewSet): queryset = UserInput.objects.all() serializer_class = UserInputSerializer permission_classes = [AllowAny] # file_path … -
SAVE Matplotlib directly as png file instead of base64 file in Database in Django
I am working on a project where I am taking audio files(.wav files) as input and processing them to get image data in Django. I am using matplotlib plot functions and then saving it as a Base64 png file in my database. and then decoding it in the front end so that users can view the output.Can some please help me how to save a proper png file in my DB rather than saving as a base64 file first and then later decoding it while viewing it? I want to further use these images as input in y machine learning saved model for further process.PS: Base64 files occupy more space than normal png files. views.py def home(request): if request.method == 'POST': audios = request.FILES.getlist('audios') for s in audios: sample_rate, sound_data = scipy.io.wavfile.read(s) data_points = sound_data[:, 0].size length = data_points / sample_rate data_shape = sound_data.shape data_type = sound_data[:, 0].dtype # fourrier transform y_fourrier = np.abs(fft(sound_data[:,0])) x_fourrier = np.linspace(0.0, sample_rate, data_points, endpoint=True) y_fourrier = y_fourrier[0:data_points // 2 + 1] x_fourrier = x_fourrier[0:data_points // 2 + 1] #transform to log scale y_fourrier_db = np.log10(y_fourrier) plt.figure() plt.plot(x_fourrier, y_fourrier_db) plt.axis("off") plt.margins(0,0) f = io.BytesIO() plt.savefig(f, format='png') f.seek(0) photo= base64.b64encode(f.read()).decode('utf-8').replace('\n', '') f.close() image=Images.objects.create( photo=photo, ) img … -
How would I go about creating an order-by feature that runs in the Django template?
I created a car dealership site and I am struggling on the last feature which is an order-by feature that manipulates the order vehicles are shown in the template. After googling for hours on how to go about this, the closest I got was being told to use order-by in the view before the template is rendered or there is regroup which I read about in the documentation but struck out there. Neither of these are suitable as I'd like users to change the order of the vehicles by price and other fields in the template, much like how you would order products on any ecomm site. I know AJAX is great for DOM manipulation but I just cant seem to crack it. I was thinking I could create a new url/view to change the order-by field which might work only it would return all objects and not those initially searched for by the user. Does anyone have advice on how to go about this? -
Django Framework Simple Class
Sorry to bother but first time posting here and very very new to Django, very very new to Python, possibly very new to the Internet :| I'm currently learning Django and I setup a Django Project like so: app_admin/ and inside this folder it has the default urls.py, settings.py, wsgi.py etc.. I created an app and so now I have: app_admin/ app_name/ and inside this folder views.py, models.py etc... I read that it's best to keep your apps separated but now when I try to import any Classes from models.py even within app_name/ let's say a file main.py. When I try to do an from .models import class-name I get these errors that it cannot import django.db My biggest confusion is what does the difference between django-admin startproject APP and then you can create an app like so python3 manage.py startapp APP. I'm quite confused about this. I want to build an app that can retrieve server info like python version, ip of server, kernel version, apache version etc... and I am trying to follow best practices but I guess I am not quite sure what I am doing :/ I am very stupid so please forgive me. -
Django image field default image
How to set the default image in my profile_picture? profile_image = models.ImageField(null=True,blank=True, upload_to="images/", default='post_user/image/profile_image.png') -
I manually Deleted my database from pgAdmin now Makemigration doesnt work
I am using postgresql as my database and I am using Pgadmin as a management tool. I was having an issue and I learned I need to use "python manage.py myapp zero" So This was universal solution in Stackoverflow for my problem and It didnt work even after whatever I did. So I had the genius idea of deleting the database from pgadmin and recreating again. Since there was nothing important in it. Now I cant makemigration. and Cloning app from Github didnt solve my problem. What can I do? Main Error I am getting when tried to makemigration: django.db.migrations.exceptions.BadMigrationError -
Customising django form field rendering
I am attempting to customise Django form rendering. I am rendering my form out into HTML like this: <form action="." method="POST" class="form-group"> {% csrf_token %}{{ form.non_field_errors }} {% for field in form.visible_fields %} <div class="fieldWrapper"> <br> {{ field.errors }} {{ field.label_tag }} <br> {{ field }} <br> </div> {% endfor %} <input type="submit" class="btn btn-success" value="Submit Questionnaire" /> </form> For one of my fields, I have a multiple-choice option which renders the {{ field }} as a "li/ul" tag, hence I get bullet-points next to checkboxes, an example of which is displayed below: I am trying to get rid of the bullet point. -
For Loop in Django template just repeats the last value in dictionary
I am receiving data from an API that I am looping over in my template. Every value comes out fine but the date. Because the template cant format the date as a string I formatted it in my view (shown below). But now when I pass that datetime variable into my template it just shows the same date for each iteration, every other value is correct. How can I get the dates iterated over properly? Thanks! for game in games: date = game['schedule']['date'] datetime_date = datetime.strptime(date, '%Y-%m-%dT%H:%M:%S.%fZ') game_date = datetime_date.strftime('%B %d, %Y') game_time = datetime_date.strftime('%-I:%M %p') context = { 'games': games, 'game_date': game_date, 'game_time': game_time } return render(request, 'games/games.html', context) {% for game in games %} <div class="col-12 col-lg-6 mb-4"> <div class="gamecard p-2"> <div class="row"> <div class="col-12"> <h3 class="game-summary white opacity-90 text-center font-800 mb- 0">{{ game.summary }} </h3> <p class="white opacity-90 mb-0 text-center"> {{ game_date }} {{ game_time }} </p> <p class="white opacity-90 mb-2 text-center"><small> {{ game.venue.name }} - {{ game.venue.city }}, {{ game.venue.state }}</small> </p> </div> </div> {% endfor %} -
Passing dictionary index as variable to url in Django template
I am trying to pass a string stored in a dictionary to url to be used as a variable. I want it to be passed to the function the url is pointing to. I tried putting it in {{ post.username }} but it won't accept it. Currently, I have it in quotes as "post.username" but it accepts is as the literal string and not the string stored in the dictionary. Any help would be appreciated. Template {% for post in posts %} <div class="row"> <div class="col-sm-3"> </div> <div class="col-sm-6"> <div class="card" style="width: 40rem;"> <div class="card-header bg-white"> <a href='{% url "user_view" "post.username" %}'><img class="rounded-circle" src="{{ post.user_image }}" style="width:30px; height: 30px;"> {{ post.user_name }}</a> <div class="text-black-50 mt-2">{{ post.created_date }} ago</div> </div> <img class="card-img-top" src="{{ post.picture }}" alt="Post Image" style="width: 100%; height: 30vw; object-fit: cover"> <div class="card-body"> <p class="card-text">{{ post.description }}</p> <a href="">Comments | {{ post.comments }}</a> </div> </div> </div> <div class="col-sm-3"> </div> </div> URL path('user_view/<account_id>', views.user_view, name='user_view') I tried path('user_view/<str:account_id>' but no luck View def user_view(request, account_id): user = User.objects.get(username=account_id) user_prop = UserProperty.objects.get(user_id=user) account_info = [user_prop.profile_photo, account_id, user_prop.bio] print(account_info) return render(request, 'users/user_view.html', {'account_info': account_info}) When I click on the anchor on the website, it gives me this address : http://localhost:8000/user_view/post.username -
Is there an alternative to coverage for the unittest in Django?
I would like to know if it exists an alternative to the coverage package for the unittest in Django because I am looking for a tool which told me the number of functions, class which are covered. Do you know if this kind of tools for Django exist ? I knox for php there is phpunit which give this kind of metrics. Thank you very much -
can anyone explain to me the basics of Django Plotly?
I work on Plotly graphs and when I run the server the result on a page is 500 Internal Server Error. I really disappointed with tutorials and materials that explain dealing with the graph in Django where I can't understand a lot of stuff so, I need to demonstrate what's happening with me because I don't understand how can I set up and run the app which contains Plotly graphs. I need to know how I run a server in Django with Plotly but I don't need to use any server except localhost. how can I configure Plotly in-app individual whereby doesn't damage the rest of the applications in the same project where when I ran the server the app looked like has damaged. please insert a simple graph if it is possible to explain this mission and how can I render it into HTML smoothly into the plotly_app tag. also, I read about this line in one of an article about Plotly but I couldn't understand what it wants to tell me: "The registration code needs to be in a location that will be imported into the Django process before any model or template tag attempts to use it". … -
Django timedate conversion
In my Django program, an API call is being run to retrieve data about appointments that are taking place during the day. In the html template, I have the following: {% for session in schedule %} <div class="list-classes">{{ session.SessionType.Name }} with {{ session.Staff.FirstName }} at {{ session.StartDateTime }} until {{ session.EndDateTime }}</div> {% endfor %} The problem is that the output looks like this: Cool massage 60 min with Keanu at 2021-03-09T15:20:00-08:00 until 2021-03-09T18:00:00-08:00 How can I make it look like this instead? Cool massage 60 min with Keanu at **3:20** until **6:00** -
How I let the not authenticate users see the other profile without login in Django
How I let the not authenticate users see the other profile without login in Django, because when not authenticate user try to the users' profile this happen Account matching query does not exist I wanna let them able to see the profile without this problem happen my view account = Account.objects.get(pk=user_id) view_account = account my_account = Account.objects.get(username=request.user) if view_account in my_account.following.all(): follow = True else: follow = False -
Dynamically include variables from Player Class in Verbose_Name field of formfield?
I'm struggling with a problem in Django. Let's say I define a new object in a Player class in Django (in models.py) like so: class Player(BasePlayer): color = models.StringField( verbose_name = "What is your favorite color?", ) color_repeat = models.StringField( verbose_name = "What are some things that are {color}?", ) I want to be able to replace {color} with the value that is stored in Player.color. I understand that this might be impossible to do so within models.py. If I have just one of these fields, I can omit the verbose_name and just manually expose a variable in pages.py and attach a label in the corresponding .html file like so: <div id="color_repeat" class="formlabel">What are some things that are <b>{{ Player.color }}</b>? </div> {% formfield player.color_repeat %} However, I have some 50 or so fields that need to dynamically show content stored in the player class, and don't want to manually modify the formlabels in pages.py for all of them. Is there a more convenient way to modify verbose_name of many fields to refer to some variable stored in the Player class? I was told Custom Field creation might be necessary, but Django documentation is not particularly easy to navigate on …