Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Tom-Select as Django Widget
I would like to use tom-select as an Django autocomplete select-widget. In the corresponding database table (Runners) are several hundred rows, so that I can't load all into the html page. In the model RaceTeam I have a ForeignKey to Runner. The select widget will be used in whole pages and in html fragments (via htmx). I tried subclass django.forms.Select, but this sucks all db rows into widget.choices. -
how to return number of distinct values django
i'm working on project for an hotel family = 'family' single = 'single' room_types = ( (family , 'family'), (single , 'single'), ) class Room(models.Model): room_no = models.IntegerField(unique=True) beds = models.IntegerField(default=2) balcon = models.BooleanField(default=False) room_type = models.CharField(max_length=15,choices=room_types,default=single) this is my views(query) lists = Room.objects.order_by().values('balcon ','beds','room_type').distinct().annotate(total=Count('beds',distinct=True)+Count('balcon',distinct=True)+Count('room_type',distinct=True)) i expect the query to return something like this beds: 4 , balcon : True , room_type : single , total : 10 beds: 3 , balcon : True , room_type : family, total : 4 and so on but it doesnt return as i expected ! is it possible to make a group by based on several fields and count based on that selected fields please ? thank you for helping .. -
django How to add multiple images with foreignkey
in our application, users must add a ad through the form Models.py: class Ad(models.Model): title=models.CharField('Заголовок',max_length=150,null=False,blank=False) content=models.TextField('Описание',max_length=500) price=models.PositiveIntegerField('Цена',help_text='0 = Договорная') date=models.DateTimeField('Дата',auto_now_add=True) def __str__(self): return self.title class Meta: verbose_name='Обьявление' verbose_name_plural='Обьявлении' class Images(models.Model): image=models.ImageField('Изображение',upload_to='upload_images/%Y/%m/%d/') ad=models.ForeignKey(Ad,on_delete=models.CASCADE) class Meta: verbose_name='Фото' verbose_name_plural='Фото' Views.py: def add_new(request): if request.method=='POST': form=AddForm(request.POST) if form.is_valid(): valid_form=form.save() for image in request.FILES.getlist('images'): photo=Images(ad=valid_form,image=image) photo.save() return HttpResponseRedirect('/') else: form=AddForm() return render(request,'add_post.html',{'form':form}) and as a result, ad.title is added to the database, and if I write photo = Images (ad = valid_form.pk, image = image), then an error occurs. help me please -
Missing required flag: » -a, --app APP parent app used by review apps
Guys I am trying to run my app, but everytime I have this problem. I tried to run it also with only -app flag. Here is what I tried: heroku run --app movie-raterr I got a message: Error: Missing required flag: » -a, --app APP parent app used by review apps heroku run » Error: Missing required flag: » -a, --app APP parent app used by review apps When I tried to run only with -app flag I got another kind of error: heroku run bash at Run.run (C:/Users/Mateusz/AppData/Local/heroku/client/7.54.1/node_modules/@heroku-cli/plugin-run/lib/commands/run/index.js:27:19) at Run._run (C:/Users/Mateusz/AppData/Local/heroku/client/7.54.1/node_modules/@oclif/command/lib/command.js:44:31) -
how to get some filtered results from class based views in Django rest framework?
My models.py from django.db import models from django.contrib.auth.models import User import datetime from django.utils import timezone # Create your models here. class LiveClass(models.Model): standard = models.IntegerField() no_of_students_registered = models.IntegerField(default=0) class Meta: verbose_name_plural = 'Class' def __str__(self): return str(self.standard) + ' class' class User_details(models.Model): name = models.OneToOneField(User, on_delete = models.CASCADE, max_length=30) standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE) email = models.EmailField(max_length=30) mobile_number = models.IntegerField() class Meta: verbose_name_plural = 'User_details' def __str__(self): return self.name class Mentor(models.Model): name = models.CharField(max_length=30) details = models.TextField() ratings = models.FloatField(default=2.5) class Meta: verbose_name_plural = 'Mentors' def __str__(self): return self.name class LiveClass_details(models.Model): standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE) chapter_name = models.CharField(max_length=30) chapter_details = models.TextField() mentor_name = models.ForeignKey(Mentor, max_length=30, on_delete=models.CASCADE) class_time = models.DateTimeField() end_time = models.DateTimeField() isDoubtClass = models.BooleanField(default=False) doubtsAddressed = models.IntegerField(default=0) class Meta: verbose_name_plural = 'LiveClass_details' def __str__(self): return self.chapter_name class SavedClass(models.Model): class_details = models.ForeignKey(LiveClass_details, on_delete=models.CASCADE) name = models.ForeignKey(User_details, on_delete=models.CASCADE) is_registered = models.BooleanField(default=False) is_attended = models.BooleanField(default=False) class Meta: verbose_name_plural = 'SavedClasses' def __str__(self): return 'SavedClass : ' + str(self.class_details) my serializers.py from rest_framework import serializers from . import models class LiveClass_serializer(serializers.ModelSerializer): class Meta: model = models.LiveClass fields = '__all__' class User_details_serializer(serializers.ModelSerializer): class Meta: model = models.User_details fields = '__all__' class LiveClass_details_serializer(serializers.ModelSerializer): class Meta: model = models.LiveClass_details fields = '__all__' class Mentor_serializer(serializers.ModelSerializer): class Meta: … -
'tuple' object has no attribute 'user'
Thank you so much for your help, i really appreciate it. I get this error "'tuple' object has no attribute 'user'" Anybody can tell me if my codes is right. im trying to make artist followers system. View.py @api_view(['GET']) @permission_classes([IsAuthenticated]) def artist_follow(request, pk): artist = Artist.objects.get(pk=pk) current_user = User.objects.get(pk=request.user.id) # check the current user already followed the artsit, if exist remove it else add if artist.followers().user.filter(user=current_user).exists(): # This line throw error artist.followers().user.remove(current_user) else: artist.followers().user.add(current_user) return Response(status=status.HTTP_200_OK) Model.py class Artist(models.Model): name = models.CharField(unique=True, max_length=100) ..... def __str__(self): return self.name def followers(self): return ArtistFollower.objects.get_or_create(artist=self) class ArtistFollower(models.Model): artist = models.OneToOneField(Artist, on_delete=models.CASCADE) user = models.ManyToManyField(User, related_name='user_artist_followed') def __str__(self): return self.artist.name -
How to get Image file size in django model?
I wanna save image file size in database after uploading it. How can I do that in django models? It'll also work if I can get the size in the views. But since there can be multiple images in one Community post, I am unable to get the size for each of them. My models.py file: from django.db import models import os class Community(models.Model): title = models.CharField(max_length=100) description = models.TextField(max_length=500) def __str__(self) -> str: return self.title class CommunityImages(models.Model): post = models.ForeignKey(Community, on_delete=models.CASCADE) height = models.IntegerField(null=True, blank=True) width = models.IntegerField(null=True, blank=True) image = models.ImageField(upload_to='communityImages/%Y/%m/%d', blank=True, null=True, height_field='height', width_field='width') @property def images_exists(self): return self.communityImages.storage.exists(self.communityImages.name) def community(self): return self.post.id def __str__(self): return "%s %s " % (self.post_id, self.image, ) class Meta: verbose_name_plural = "Community Images" My views.py file: from django.http import JsonResponse from .models import CommunityImages, Community import json import os def image_detail(request, post_id): community_post = {} communityPostImages = list(CommunityImages.objects.filter(post=post_id).values('id','image', 'height', 'width')) for i in range(len(communityPostImages)): communityPostImages[i]['img_name'] = os.path.split(communityPostImages[i]['image'])[-1] communityPostImages[i]['type'] = os.path.splitext(communityPostImages[i]['img_name'])[-1].replace('.', '') communityPostImages[i]['dimension'] = str(communityPostImages[i]['height']) + "x" + str(communityPostImages[i]['width']) community_post['communityPostImages'] = communityPostImages data = json.dumps(community_post, indent=4, sort_keys=False, default=str) return JsonResponse(data, safe=False) Thanks in advance! -
how do I properly write django helper functions in order to check for new rows, and if the data was changed?
I am trying to write two functions in Django as helpers where it will help me to check if new data is coming or if the existing data was changed for further update is_new_row - will understand if the row is new and add it to an array that will be bulk created is_data_modified - will look for the row in the old data and understand if the data of that row is changed and will update only if its changed old_data = Person.objects.all() for row in api_data: if is_new_row(row, old_data): new_rows_array.append(row) else: if is_data_modified(row, old_data): ... # do the update else: continue helpers def is_new_row(row, old_data): ?? def is_data_modified(row, old_data): ?? -
Django-crontab can't make model query
I have a model inside tools app called ApiKeys and tried to update the model in specific time intervels. I used django-crontab for this purpose. CRONJOBS = [ ('*/1 * * * *', 'tools.cron.reset_api_calls','>>logs.log') ] function - from .models import ApiKeys def reset_api_calls(): try: keys = ApiKeys.objects.all() for key in keys: key.api_calls = 0 key.save() except Exception as e: print(e) model - class ApiKeys(models.Model): key_token = models.CharField(max_length=50, primary_key=True) api_calls = models.IntegerField(default=0) las_used_date = models.DateTimeField(default=timezone.now) But it gives error log - no such table: tools_apikeys Note: The table does exist in database and accessible through django-shell and views.py as well. -
How to create own model that can authenticate like admin user in django
I create own model user but can't authenticate it like in admin user # myapss/models.py from django.db import models from django.contrib.auth.hashers import make_password, check_password from django.db.models.manager import Manager class MyOwnManager(Manager): ... class MyOwnUser(models.Model): username = models.CharField(max_length=50, unique=True) password = models.CharField(max_length=255) ... objects = MyOwnManager() I want to authenticate this model without using AbstractUser or AbstractBaseUser #myapps/views.py from .models import MyOwnUser def login(request): # Authentication -
Kafka custom logging handler makes django app unlisten on port
I have a django app and I need to send my logs to the kafka server. So I implemented a custom handler as below: import logging from kafka import KafkaProducer class KafkaHandler(logging.Handler): def __init__(self, hosts=['DEFAULT_KAFKA_HOST:DEFAULT_KAFKA_PORT'], topic='DEFAULT_KAFKA_TOPIC'): logging.Handler.__init__(self) self.producer = KafkaProducer( bootstrap_servers=hosts, security_protocol='SASL_SSL', sasl_mechanism='SCRAM-SHA-512', sasl_plain_username='KAFKA_USER', sasl_plain_password='KAFKA_PASSWORD', value_serializer=lambda v: json.dumps(v).encode('utf-8'), linger_ms=10) self.topic = topic The problem here is that when I run the django app via python manage.py runserver in my local app runs without any trouble but my localhost doesn't listen on the specific port. output of netstat -tulpn: (Not all processes could be identified, non-owned process info will not be shown, you would have to be root to see it all.) Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 127.0.0.53:53 0.0.0.0:* LISTEN - tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN - tcp6 0 0 :::80 :::* LISTEN - tcp6 0 0 ::1:631 :::* LISTEN - udp 0 0 127.0.0.53:53 0.0.0.0:* - udp 0 0 0.0.0.0:631 0.0.0.0:* - udp 0 0 0.0.0.0:5353 0.0.0.0:* - udp 0 0 0.0.0.0:54922 0.0.0.0:* - udp6 0 0 :::58148 :::* - udp6 0 0 :::5353 :::* - But after I comment out the producer initialization everything works … -
Celery retry exception errors
I'm working on a project that requires me to reschedule tasks and I'm running into a problem. Would appreciate any feedback. I get a celery.exceptions.Reject error when attempting to retry a celery task. I've tested with a minimal tasks.py as listed below. Here is the code. tasks.py: from celery import Celery, Task from celery.utils.log import get_task_logger from django.conf import settings app = Celery('tasks', broker=settings.CELERY_BROKER_URL, backend=settings.CELERY_RESULT_BACKEND) logger = get_task_logger(__name__) @app.task(bind=True) def task_process_notification(self): try: if not random.choice([0, 1]): # mimic random error raise Exception() requests.post('https://httpbin.org/delay/5') except Exception as e: logger.error('exception raised - retry in 5 secs') raise self.retry(exc=e, countdown=5) Celery log traceback: [2021-06-19 04:21:19,342: INFO/MainProcess] celery@macbook-pro-16.lan ready. [2021-06-19 04:21:23,762: INFO/MainProcess] Received task: stocks.tasks.task_process_notification[ff372faa-febf-4d47-8628-2851a740cac3] [2021-06-19 04:21:23,765: ERROR/ForkPoolWorker-9] stocks.tasks.task_process_notification[ff372faa-febf-4d47-8628-2851a740cac3]: exception raised - retry in 5 secs [2021-06-19 04:21:23,775: ERROR/ForkPoolWorker-9] stocks.tasks.task_process_notification[None]: exception raised - retry in 5 secs [2021-06-19 04:21:23,777: WARNING/ForkPoolWorker-9] Task stocks.tasks.task_process_notification[ff372faa-febf-4d47-8628-2851a740cac3] reject requeue=False: Traceback (most recent call last): File "/Users/TLK3/PycharmProjects/stratbot/stocks/tasks.py", line 303, in task_process_notification raise Exception() Exception During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/TLK3/PycharmProjects/stratbot/venv/lib/python3.8/site-packages/celery/app/task.py", line 721, in retry S.apply_async() File "/Users/TLK3/PycharmProjects/stratbot/venv/lib/python3.8/site-packages/celery/canvas.py", line 235, in apply_async return _apply(args, kwargs, **options) File "/Users/TLK3/PycharmProjects/stratbot/venv/lib/python3.8/site-packages/celery/app/task.py", line 561, in apply_async return self.apply(args, kwargs, task_id=task_id or uuid(), File "/Users/TLK3/PycharmProjects/stratbot/venv/lib/python3.8/site-packages/celery/app/task.py", line … -
How to list integer field of distinct values in ascending order in Django
I am using django as backend and PostgresSql as backend. One problem I'm getting is sorting the distinct values in ascending order. I Have Distinct values in filter as: 16,14,4,64,8,6,12,10,18,2,32,24 now i want those values as 2,4,6,8,10....... I have code like this to get those distinct values filter_cores = Processor.objects.distinct().values('cores') HOW I CAN DO IN ASCENDING ORDER? -
how can i delete a permission from a group
I'm working on a small project using Django / Rest Framework, and now i would like to add soem permissions / Groups. I would like to know how can i add and delete a permission from a group i already did some research on Google and here i found only how to add but i'm steel looking for a way to delete a permission from a group, this is what i found : from django.contrib.auth.models import Group, Permission from django.contrib.contenttypes.models import ContentType from api.models import Project new_group, created = Group.objects.get_or_create(name='new_group') # Code to add permission to group ??? ct = ContentType.objects.get_for_model(Project) # Now what - Say I want to add 'Can add project' permission to new_group? permission = Permission.objects.create(codename='can_add_project', name='Can add project', content_type=ct) new_group.permissions.add(permission) Can someone explain to me how to delete a permission from a group ? Thank you -
Better ways to generate codes in django (python)
I am working on an authentication project where I am applying different features like email verification, password reset and these features rely on emails. Now i want to send a code to the user through an email and verify that on the backend. Now to generate the code(5-digit), this is what i did; import random code = random.randint(10000, 99999) print(code) I just want to know is this a better way to do so. Are there any drawbacks or just fine. -
bootstrap5 - how to next and prev button reduce the area?
I want to use bootstrap carousel. But the next and previous buttons are too long up and down to use the nevbar. how to next and prev button reduce the area? -
django.urls.exceptions.NoReverseMatch: Reverse for 'drafts' with keyword arguments '{'pk': 3}' not found. 1
Iam getting error "django.urls.exceptions.NoReverseMatch: Reverse for 'drafts' with keyword arguments '{'pk': 3}' not found. 1" I have created a button for delete view, and it is not working. whebever iam clicking on button the above error is coming. Kindly help here is the code : in views.py class DraftsView(ListView): model=models.NewPost context_object_name='newpost' class DraftsEditView(DetailView): context_object_name='draft_view' model=models.NewPost template_name='blogapp/newpost_details.html' # pk_url_kwarg="id" class DraftsUpdateView(UpdateView): fields=('Author','Title','Text') model=models.NewPost class DraftsDeleteView(DeleteView): model=models.NewPost context_object_name='newpost' success_url=reverse_lazy("blogapp:drafts") In urls.py urlpatterns=[url('about/',views.about,name='about'), url('register/',views.register,name='register'), url('user_login/',views.user_login,name='user_login'), url('newpost/',views.NewPostView,name='newpost'), url('drafts/',views.DraftsView.as_view(),name='drafts'), # path('drafts/<int:pk>/',views.DraftsEditView), path('<int:pk>',views.DraftsEditView.as_view(),name='view_draft'), path('update/<int:pk>/',views.DraftsUpdateView.as_view(),name='update'), path('delete/<int:pk>/',views.DraftsDeleteView.as_view(),name='delete') ] in newpost_details.html <a href="{% url 'blogapp:delete' pk=draft_view.pk %}"> <input class="btn btn-danger" type="text" name="" value="Delete"> </a> -
How to pass values to input field's value with spaces
<form action="handleAppointment/" method="post" > {% csrf_token %} <div class="inputfield"> <label for="doctor" class="label">Doctor</label> <input type="text" name="doctor" id="doctor" class="input" value={{ doctorName.name }} > </div> this is my form i want full value from database.but here {{doctorName.name}} is showing value which is before space. def bookAppointment(request , id ): doctor = Doctor.objects.filter(id = id ).first() print(doctor.name) context = {'doctorName': doctor} return render(request , 'patient/appointmentForm.html' , context) after running this code it shows ' Tapan Shah ' as output in terminal. which is full name but it shows ' Tapan ' before space value in frontend. -
Deploy django with apache2 error - ModuleNotFoundError: No module named 'encodings'
I tried to deploy my django app to my local vagrant but show the error below. '/var/www/venv/lib/python3.8/lib/python38.zip', '/var/www/venv/lib/python3.8/lib/python3.8', '/var/www/venv/lib/python3.8/lib/python3.8/lib-dynload', Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x00007f69c61ddc40 (most recent call first): <no Python frame> This code is log with apache2 tail /var/log/apache2/error.log <VirtualHost *:80> ServerName 192.168.2.26 DocumentRoot /var/www/django_app WSGIScriptAlias / /var/www/django_app/dj_rest_ql/wsgi.py # adjust the following line to match your Python path WSGIDaemonProcess 192.168.2.26 processes=2 threads=15 display-name=%{GROUP} python-home=/var/www/venv/lib/python3.8 WSGIProcessGroup 192.168.2.26 <directory /var/www/django_app> AllowOverride all Require all granted Options FollowSymlinks </directory> Alias /static/ /var/www/django_app/static/ <Directory /var/www/django_app/static> Require all granted </Directory> </VirtualHost> This is directory deployment /var/www/django_app /var/www/venv Is everyone used to meet this problem, please give me the solution, Thanks you in advance. Or if anyone have an good article for deploy djano with apache2 or nginx, please recommend me some. -
How to pass a token to views that require authentication in django rest framework
I have an app that stores users and their posts. To view the page of a user, I want it to require authentication for a given user. I'm not quite sure how to implement this because before without DRF, I'd just check if the current user was the same as the id requested in the url like page/users/10. DRF generates tokens for each user which I have specified when they register with this: class RegisterView(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": Token.objects.get(user=user).key }) Each token keys to a user like here: What I am wondering is how can I get each of these tokens to be used to authenticate the user. If the user logs in with his account, how will I be able to get the token and then pass it to the restricted views? -
How to render fields with many-to-many relationship on django templates
I am using generic views in Django-3.2 where I have a many-to-many relationship. I am trying to put the names of all the authors for a book as a string on a template. The model is like this: class Book(models.Model): book_name = models.CharField(max_length=200) author = models.ManyToManyField(Author) The Author class has a field called author_name which is also returned from the __str__ method. The generic view class that I am using is like this: class BookView(generic.DetailView): model = Book template_name = 'books/book.html' I tried using <span>{{ book.author }}</span> which produced books.Author.None. Later, I tried using <span>{{ book.author.author_name }}</span>, and this didn't retrieve any result. I didn't get an error in either of the cases. How do I put the data on the template for such many-to-many field? -
How to pass data acquired from vue.js to django template
The problem is that I can't utilize the data of vue instance within the tag of django template. So, Here is example code vue.js const vm=new Vue({ el:#app, delimiters:["${", "}"], data(){return{name:""}}, methods:{ /* getting data from django model with axios/DRF */ ..... axios.get("api/items/").then(response) => {this.name=response) this code work well and index.html .... <body> <p>Your item is ${name}</p> <p v-html=name></p> <p> Price is {{price}} </p> /*this come from context of django view */ </body> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script> "name" can be displayed on the django template What I want to do is "name" can function as value (or parameter) in tag of django template for example <body> {% with bookname=name %} {{bookname}} {% endwith %} ...... <a herf="{% url 'top:booklist' name %}" > </body> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script> This does return error, not work. Of course, "${name}" is no success, instead "name" <a herf="{% url ' top:booklist ' ${name %}" > Please tell me how to pass "name" to django template tag I use Pyhton 3.7 Django 2.2 Vue CDN, not use Vue CLI thank you -
Adding a simple new account in the django admin doesn’t ask for the correct fields
I’m new to django and am sure this is probably a quick spot for most. I essentially want to: Change the default User model to use an email (and password) to log in (instead of username) Add extra fields to the default User model I’ve followed a video tutorial that resulted in me writing this code: Models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError("Users must have an email address") if not password: raise ValueError("Users must have a password") user = self.model( email=self.normalize_email(email), # converts chars to lowercase password=password, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): # password=None? user = self.create_user( email=self.normalize_email(email), password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=100, unique=True) date_joined = models.DateTimeField( verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) first_name = models.CharField(max_length=100, null=True, blank=True) last_name = models.CharField(max_length=100, null=True, blank=True) # username field unwanted - only added to get rid of fielderror "Unknown field(s) (username) specified for Account. Check fields/fieldsets/exclude attributes of class AccountAdmin." username = models.CharField(max_length=30, unique=True, blank=True) # … -
Can pytest-django completely replace Django built-in test
I prefer to use pytest for writing all of my tests. I don't really like the unittest-style that the django.test offers, and I'm sure I'm not the only one... I made the switch to pytest years ago, and have never looked back! However, now I'm working my way through the Django tutorials, and have reached the testing section, and would like to use pytest instead of django.test. So far, it seems that pytest-django would be the perfect tool for the job! This blog post makes a good argument for using pytest-django, and it seems like I would be able to test my entire Django application using pytest-django. My question is: Can I completely forego using django.test and use pytest-django instead? Or, will there be some parts of my application that I would need to test using django.test? -
How to render form 'attribute'/field widget with template tag
Here is my html template code {% if subject == 'BAFS' %} {{ form.bafs_result.errors }} {{form.bafs_result.label}} {{ form.getSubjectResultAttrName:subject }} here is the python code in the template filter from django import template register = template.Library() @register.filter def getSubjectResultAttrName(form, subject): subjectAttrName = subject.lower() + "_result" subjectAttr = form.fields[subjectAttrName] return subjectAttr What I am trying to do is to render {{form.bafs_result}}, in which bafs_result is a Choicefield in the form. However, the above yields this: I have also tried replacing the subjectAttr assignment with: subjectAttr = form.fields[subjectAttrName].widget or subjectAttr = getattr(form, subjectAttrName) which gives the error: 'Form' object has no attribute 'bafs_result'