Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django How to insert into model with dynamic key value pairs?
I am obtaining Model instance from my applabel and modelname by the below mentioned format. target_model = django.apps.apps.get_model(app_label=appname, model_name=modelname) And Obtaining model instance like this model = target_model() Need to insert the row in db using this model. I am having key value pairs in variable I have tried below mentioning two ways. key = "model_id" value = "some_value" model[key] = value model.save() and setattr(model, key, value) model.save() Both are not working for me. Any Django (python) Engineers helps me to move further? -
first and last methods used excluded items
i used last() to get last item of queryset after exclude some items as below: holidays = HolidayModel.objects.all().values_list('date', flat=True) result = BorseExchangeLog.objects.exclude( hint_time__date__in=holidays ) # output 1 print(list(result.valuse_list('hint_time__date',flat=True).distinct('hint_time__date'))) #output2 print(result.last().hint_time.date()) but in output2 print item that not exists in output1 i test that by first() and problem was there too what is problem? my code is wrong or bug from django orm? using django2.2 and postgresql -
Django ORM query to update reverse many to many field
Models look like: class Book(models.Model): name = models.TextField(verbose_name='Book Name') class Author(models.Model): name = models.TextField(verbose_name='Author Name') Books = models.ManyToManyField(Book) Book can have many authors and Author can have written many books Now, There is a list like: [ {Book_id1:[Author_id1, Author_id2]}, {Book_id2:[Author_id2, Author_id3]}, ] This information is required to be updated in the DB. How can this be done in an efficient way using ORM? (Currently the DB may have Book_id1 linked with [Author_id1,Author_id3] so the update should be able to add author_id2 and delete author_id3 as well) -
Is there a way to convert HTML div to a video format (MP4 or any other) in Python/Django?
I am trying to render a HTML page and use a specific inside it to convert it to video format. Explanation: I know HTML is static content but it is necessary for me to convert it to a video format (it is a requirement). I need to know if there is a way which can render a page and export it to a video format. It can either be a direct HTML to MP4 conversion or capture rendered div (Not record canvas) as an Image and then convert that image to the video format. Technology Stack: Django Django templates HTML JAVASCRIPT Any help would be appreciated. -
Django and reactjs: How to create notification feature
I have django backend and reactjs frontend. I am running some tasks in celery on the backend. Now when the tasks are completed, I want to inform the user in real time, when the webapplication is open I have done the frontend in reactjs. I heard this can be done using polling or webhooks. I want to use webhooks. How to do this. What should i do on the backend side and also on the frontend side -
django: simulate a flags Field using BInaryField
So I'm trying to simulate a flags field in Django (4.0 and Python3) the same way I could do in C or C++. It would look like this: typedef enum{ flagA = 0, flagB, flagC } myFlags; Having a uint8 that by default is 00000000 and then depending on if the flags are on or off I'd do some bitwise operations to turn the three least significant bits to 1 or 0. Now, I could do that in my model by simply declaring a PositiveSmallIntegerField or BinaryField and just creating some helper functions to manage all this logic. Note that I DO NOT NEED to be able to query by this field. I just want to be able to store it in the DB and very occasionally modify it. Since it's possible to extend the Fields, I was wondering if it would be cleaner to encapsulate all this logic inside a custom Field inheriting from BinaryField. But I'm not really sure how can I manipulate the Field value from my custom class. class CustomBinaryField(models.BinaryField): description = "whatever" def __init__(self, *args, **kwargs): kwargs['max_length'] = 1 super().__init__(*args, **kwargs) For instance, if I wanted to create a method inside CustomBinaryField, like the following, … -
Interpolate Django model
I have a Django model with data with a Date and a numerical value. Sometimes some dates are missing. Is there a way to automatically interpolate the data? For instance: 2021-Dec-20: 10 2021-Dec-19: 8 2021-Dec-15: 4 would become: 2021-Dec-20: 10 2021-Dec-19: 8 2021-Dec-18: 7 2021-Dec-17: 6 2021-Dec-16: 5 2021-Dec-15: 4 I have written some code to do this manually triggered with Django Background Tasks but I was wondering if there is a more standard approach to do this? -
How do I replace MemcachedCache with PyMemcacheCache in Django?
I'm running my website on Django 3.2. I read in Django’s cache framework that MemcachedCache and python-memcached are deprecated. I installed pymemcache==3.5.0 on my staging server and changed to CACHE_URL=pymemcache://127.0.0.1:11211 in env.ini. But if I uninstall python-memcached with pip I receive an error message, that indicates that MemcachedCache is still used by my code, and it fails on import memcache. My code uses the following imports: from django.core.cache import cache from django.core.cache.backends.base import DEFAULT_TIMEOUT How do I replace MemcachedCache with PyMemcacheCache so that MemcachedCache will not be used in my code? -
Django: OR search with the field value of the model and the m2m field value of that model is slow
Django: It takes a long time to filter the m2m model from the m2m-connected model by specifying the field values of the m2m model This question is similar to this one, but when I do a filter using the m2m field from a model that is tied to m2m, the query is very slow. How can I reduce the number of useless INNER JOIN as shown in the answer to the question above? Video.filter(Q(title__icontains='word') | Q(tags__name__icontains='word')).order_by('-published_at') Query issued SELECT "videos_video"."id" FROM "videos_video" LEFT OUTER JOIN "videos_video_tags" ON ("videos_video"."id" = "videos_video_tags"."video_id") LEFT OUTER JOIN "videos_tag" ON ("videos_video_tags"."tag_id" = "videos_tag"."id") WHERE (UPPER("videos_video"."title"::text) LIKE UPPER('%word%') OR UPPER("videos_tag"."name"::text) LIKE UPPER('%word%')) ORDER BY "videos_video"."published_at" DESC; EXPLAIN(ANALYZE, VERBOSE, BUFFERS) QUERY PLAN ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Gather Merge (cost=51955.59..52038.90 rows=714 width=24) (actual time=1209.450..1305.089 rows=335972 loops=1) Output: videos_video.id, videos_video.published_at Workers Planned: 2 Workers Launched: 2 Buffers: shared hit=1617 read=19577, temp read=14576 written=14846 -> Sort (cost=50955.57..50956.46 rows=357 width=24) (actual time=1194.858..1209.600 rows=111991 loops=3) Output: videos_video.id, videos_video.published_at Sort Key: videos_video.published_at DESC Sort Method: external merge Disk: 3712kB Buffers: shared hit=1617 read=19577, temp read=14576 written=14846 Worker 0: actual time=1187.952..1202.470 rows=110827 loops=1 Sort Method: external merge Disk: 3696kB Buffers: shared hit=556 read=6211, temp read=5020 written=4740 Worker 1: actual time=1189.482..1203.544 rows=113757 loops=1 Sort Method: external merge Disk: … -
Django/Pillow - Image resize only if image is uploaded
I'm able to upload an image and resize it, but if I submit the form without images I get this error The 'report_image' attribute has no file associated with it. What should I do if no image is uploaded? This is my models.py class Report(models.Model): options = ( ('active', 'Active'), ('archived', 'Archived'), ) category = models.ForeignKey(Category, on_delete=models.PROTECT) description = models.TextField() address = models.CharField(max_length=500) reporter_first_name = models.CharField(max_length=250) reporter_last_name = models.CharField(max_length=250) reporter_email = models.CharField(max_length=250) reporter_phone = models.CharField(max_length=250) report_image = models.ImageField(_("Image"), upload_to=upload_to, null=True, blank=True) date = models.DateTimeField(default=timezone.now) state = models.CharField(max_length=10, choices=options, default='active') class Meta: ordering = ('-date',) def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.report_image.path) if img.height > 1080 or img.width > 1920: new_height = 720 new_width = int(new_height / img.height * img.width) img = img.resize((new_width, new_height)) img.save(self.report_image.path) def __str__(self): return self.description -
ckeditor5 error "toolbarview-item-unavailable" on Vuejs3 and Django
I am using CkEditor5 on my Vuejs3 and Django project, it works fine but I cannot use additional features, gives me error toolbarview-item-unavailable. What should I do to upload pictures to my django app? Features I got Features I want to get <script> import ClassicEditor from '@ckeditor/ckeditor5-build-classic'; export default { data() { return { editor: ClassicEditor, editorData: '<p>Asosiy malumotlar</p>', editorConfig: { // The configuration of the editor. toolbar: { items: [ 'heading', '|', 'alignment', '|', 'bold', 'italic', 'strikethrough', 'underline', 'subscript', 'superscript', '|', 'link', '|', 'bulletedList', 'numberedList', 'todoList', 'fontfamily', 'fontsize', 'fontColor', 'fontBackgroundColor', '|', 'code', 'codeBlock', '|', 'insertTable', '|', 'outdent', 'indent', '|', 'uploadImage', 'blockQuote', '|', 'undo', 'redo' ], } } } }, } </script> -
Guidance question: Dockerized Django backend, and React front end Intranet application authentication question
This is more of a guidance question for a situation where we're stuck. Basically we've to deploy an Intranet application on client's Windows based network. Our API backend is written in Django which serves React based frontend, during offline development phase we used DRF - AuthUsers, Django Rest Framework and Simple JWT tokens, and deployed using Linux Docker Images. We've to deploy these in client's environment for which we've to implement Single Sign-On, Windows active directory authentication. Ideal target is Kubernetes but for first cut we can use plain old Docker containers. After some research, and input from client's IT dept, we've to use Apache2 Webserver docker container, set Kerberos config, keytab and deploy in same domain as that of Active Directory. We've few blockers: 1) Should we create 2 separate Apache2 based docker images, one to host Django backend and other for React frontend? 2) Where should we implement AD Authentication? i.e. frontend or backend? 3) If AD authentication needs to be impelemented, what are the required npm packages that we can try out? Most of articles/blogs for this scenario are referring to MSAL.js but our AD is on premises, not Azure based. We're using Axios for calling Django … -
Assertion Error - calling an function method inside another function in Django
I have created two API's ("startshift", "endshift") when they click on the "startshift" and "endshift" button, an another API "UserShiftDetailsAPI" will be called which return the response based on "UserStartShift" and "UserStopShift".These API are working correctly I have created a conditional statement in "UserShiftDetailsAPI" for both "UserStartShift" and "UserStopShift" but its giving as assertion error. I don't know how to call the both API method inside the function. Here, What I have tried views.py: startshift @api_view(['POST', 'GET']) def UserStartShift(request): if request.method == 'GET': users = tblUserShiftDetails.objects.all() serializer = UserShiftStartSerializers(users, many=True) return Response(serializer.data) if request.method == 'POST': UserId = request.data.get('UserId') Ip = request.data.get('Ip') PortNumber = request.data.get('PortNumber') cursor = connection.cursor() r=cursor.execute('EXEC [dbo].[Usp_StartShift] @UserId=%s, @IP=%s, @Port=%s', (UserId, Ip, PortNumber,)) return Response(True, status=status.HTTP_200_OK) endshift @api_view(['GET', 'POST']) def UserStopShift(request, UserId): if request.method == 'GET': cursor = connection.cursor() cursor.execute('EXEC [dbo].[USP_StopShift] @UserId=%s',(UserId,)) return Response(True) elif request.method == 'POST': serializer = UserShiftEndSerializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) In GET method I have applied the condition but its showing an error. It should return the response based on the "UserStartShift and "UserStopShift" method UserShiftDetails @api_view(['GET']) def UserShiftDetailsView(request, userid): try: users = tblUserShiftDetails.objects.filter(UserId=userid) except tblUserShiftDetails.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': if UserStartShift == True: cursor … -
Django HTTP Error 404: Not Found: Using a config.json file in my views
I have 3 apps and one is called 'cv' but for this app I use a config.json file but it keeps giving me a 404-error when loading the page. My project is called "project_1" and my urls.py is defined as: urlpatterns = [ path("", include("cv.urls")), path("admin/", admin.site.urls), path("projects/", include("projects.urls")), path("blog/", include("blog.urls")), ] http://127.0.0.1:8000/admin http://127.0.0.1:8000/projects and http://127.0.0.1:8000/blog can be reached, but when I open http://127.0.0.1:8000 It gives me the error. In the cv-directory, I have my urls.py defined as: urlpatterns = [ path("", views.index, name="cv_index"), ] And my cv/views.py as: def index(request): BASEURL = request.build_absolute_uri() url = BASEURL + "/static/configuration/configuration.json" response = urllib.request.urlopen(url) configuration = json.loads(response.read()) return render(request, "index.html", configuration) Where my json configuration is located in the cv directory under static>configuration>configuration.json When I change my index function in cv/views.py to just render the request and give back my index.html file, it goes fine. So I expect it has something to do with this piece of code: BASEURL = request.build_absolute_uri() url = BASEURL + "/static/configuration/configuration.json" response = urllib.request.urlopen(url) configuration = json.loads(response.read()) My traceback looks like this: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.6 Python Version: 3.9.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'projects', 'blog', 'cv'] Installed … -
cant get hello world in django
I have python version 3.10.1 and django version 4.0 url in project( name = home)` from django.contrib import admin from django.urls import path,include urlpatterns = [ path('',include('hello.urls')), path('admin/', admin.site.urls), ] url in app (name = hello) from django.contrib import admin from django.urls import path,include urlpatterns = [ path('',include('hello.urls')), path('admin/', admin.site.urls), ] views in app from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Hello World") I tried running server with and without adding 'hello' in setting.py still i get only default page. stuck from 3 days -
django : 'app name' is not a registered namespace
i have a "NoReverseMatch" error, how can i slove this i don't understand- Project_name/urls.py path('orders/',include('orders.urls')), ordres/urls.py from .views import chack_out path('chack_out/', chack_out, name='chack_out') ordres/views.py def chack_out(request): ..... product(anther app name)/product/templates/cart.html <form action="{% url 'orders:chack_out' %}" method="POST"> {% csrf_token %} error page -
The model is used as an intermediate model, but it does not have a foreign key error with through models
I am new to Django and currently trying to improve on a design I have been using. This is my models.py file. from djongo import models import uuid PROPERTY_CLASSES = ( ("p1", "Video Property"), ("p2", "Page Property"), ("trait", "Context Trait"), ("custom", "Custom Property") ) class Device(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) class Platform(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) class EventPlatformDevice(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = "Event Specifics" event_field = models.ForeignKey('Event', on_delete=models.CASCADE) applicable_apps = models.ForeignKey('Platform', on_delete=models.CASCADE) applicable_devices = models.ManyToManyField('Device') property_group = models.ManyToManyField('PropertyGroup', blank=True) custom_properties = models.ManyToManyField('Property', blank=True) class Event(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255, unique=True) applicable_platforms = models.ManyToManyField(Platform, through=EventPlatformDevice) class PropertyGroup(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=100) applicable_properties = models.ManyToManyField('Property') class Property(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) #applicable_platform = models.ManyToManyField(Platform, through=PlatformDevice) property_class = models.CharField(max_length=20, choices=PROPERTY_CLASSES) format_example = models.TextField(blank=True) notes = models.TextField(blank=True) The issue I am running into is with the EventPlatformDevice model. Right now in the Admin Panel I am able to select multiple items for the applicable_devices, property_group, and custom_properties field. The applicable_apps field is a single select. I am trying to turn that into a multi select as well but when changing the … -
The current path, /django_plotly_dash/app/test/, didn’t match any of these
We have a platform deployed on Django and we wanted to implement a dashboard created using plotly and dash in the existing Django application that we have. I followed some tutorials and integrated the dashboard application just the way everyone did but whenever I tried to go to the application url I get this message: The current path, /django_plotly_dash/app/test/, didn’t match any of these. I have created an app cars_dashboard. settings.py: MIDDLEWARE = [ 'django_plotly_dash.middleware.BaseMiddleware' ] INSTALLED_APPS = [ 'django_plotly_dash.apps.DjangoPlotlyDashConfig', 'channels', 'channels_redis', 'cars_dashboard' ] CRISPY_THEME_PACK = 'bootstrap4' ASGI_APPLICATION = 'cars_dashboard.routing.application' PLOTLY_DASH = { 'stateless_loader': 'cars_dashboard.dash_app.cars_dashboard', 'cache_arguments': False, 'serve locally': False } CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { 'hosts': [ ('127.0.0.1', 6379), ], }, }, } STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'django_plotly_dash.finders.DashAssetFinder', 'django_plotly_dash.finders.DashComponentFinder', 'django_plotly_dash.finders.DashAppDirectoryFinder', ] PLOTLY_COMPONENTS = [ 'dash_core_components', 'dash_html_components', 'dash_bootstrap_components', 'dash_renderer', 'dpd_components', 'dpd_static_support', ] main website's urls.py: urlpatterns = [ path('django_plotly_dash/', include('django_plotly_dash.urls')), path('cars_dashboard/', include('cars_dashboard.urls')), ] cars_dashboard views.py import django_plotly_dash from django.shortcuts import render, HttpResponse def home(request): return render(request, 'cars_dashboard.html') cars_dashboard urls.py from django.urls import path from . import views from .dash_app import cars_dashboard urlpatterns = [ path('', views.home, name='home'), ] The third line in the above code import the cars_dashboard.py script which contains the code for dashboard … -
Django Unit Test Login and Registration
I'm new with Django. I would like to write a unit test to test login (and possibly registration) but after several attempts I'm not sure where to start. Would you have any suggestions on how I could write these tests? Another question is: would be in this case BDD the best choice (with Behave) or should I remain for unit-test here? Thanks Code for the view.py: from django.shortcuts import get_object_or_404, render, redirect from django.urls import reverse from django.contrib.auth import login,logout,authenticate from labs.models import Category from .forms import createuserform def index(request): categories = Category.objects.all() context = { 'categories':categories, } return render(request, 'landing/index.html', context) def registerPage(request): if request.user.is_authenticated: return redirect('/labs') else: form=createuserform() if request.method=='POST': form=createuserform(request.POST) if form.is_valid() : user=form.save() return redirect('/login') context={ 'form':form, } return render(request,'landing/register.html',context) def loginPage(request): if request.user.is_authenticated: return redirect('/labs') else: if request.method=="POST": username=request.POST.get('username') password=request.POST.get('password') user=authenticate(request,username=username,password=password) if user is not None: login(request,user) return redirect('/') context={} return render(request,'landing/login.html',context) def logoutPage(request): logout(request) return redirect('/') -
Regex in django query is throwing InterfaceError: (-1, 'error totally whack')
Query1: Model.objects.filter(slug__istartswith="dfe") This is working fine in the shell. while Query2: Model.objects.filter(slug__regex="^dfe") This is throwing Error, InterfaceError: (-1, 'error totally whack') What could be the issue? -
Django , unable to get URL parameter from GET request
I have a class that accept user input and returns the filtered database class SearchView(ListView): model = Post ... ... def get_queryset(self): qs = self.model.objects.all() state = self.request.GET.get('state') print (state ) return qs When passing url, it supposed to print the state data from URL, but its not. -
django-celery-beat spams due tasks
I'm using django-celery-beat for some hourly/daily tasks. However, strange behaviour made me clueless what to do. I'm creating a task using this piece of code: periodic_task = apps.get_model('django_celery_beat', 'PeriodicTask') interval_schedule = apps.get_model('django_celery_beat', 'IntervalSchedule') schedule, _ = interval_schedule.objects.get_or_create(every=2, period='hours') periodic_task.objects.update_or_create( task=TASK, defaults={'name': 'Check missing documents', 'interval': schedule}, ) where TASK is a string pointing to this task: @app.task(ignore_result=True) def task(): <things to do> pass In the code you see that I use an interval of 2 hours, and once I started the beat with celery -A [project-name] beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler, no error pops up (I don't know if it actually works, 2 hours is a lot of time). However, when I change the interval to 1 hour, it spams these: [2021-12-21 15:32:45,333: INFO/MainProcess] Task app.tasks.task[6c0343b0-faf1-4eae-a8e0-721c862120a9] succeeded in 0.0s: None [2021-12-21 15:32:45,336: INFO/MainProcess] Scheduler: Sending due task <task description> (app.tasks.task) and then it continues to eternity, only stoppable with Ctrl+C. I do have the RabbitMQ Management plugin installed, and from the UI everyting looks fine - no queue, nothing unacked, etc. Any clue what this could cause? Even after purging the queue, it still happens (with celery -A [project-name] purge). -
django signal wont work after adding a save function
I have a simple model like this: class ScientificInfo(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) info1 = models.CharField(max_length=64, choices=SURVEY_CHOICES, blank=True) info2 = models.CharField(max_length=64, choices=SURVEY_CHOICES, blank=True) info3 = models.CharField(max_length=64, choices=SURVEY_CHOICES, blank=True) is_interviewed = models.BooleanField(default=False) def save(self, *args, **kwargs): if self.info1: self.is_interviewed = 'True' super(ScientificInfo, self).save(*args, **kwargs) Every time a user is added to the app, a ScientificInfo object will be created for it using this signal: @receiver(post_save, sender=User, dispatch_uid='save_new_user_survey') def survey_create(sender, instance, created, **kwargs): user = instance if created: survey = ScientificInfo(user=user) survey.save() everything worked fine until I added that save method inside my model. the method works but the signal is disabled. Can you guys help me? thanks -
Annotation inside an annotation in Django Subquery?
I've got a few models and am trying to speed up the page where I list out users. The issue is that I was leveraging model methods to display some of the data - but when I listed the Users out it was hitting the DB multiple times per User which ended up with hundreds of extra queries (thousands when there were thousands of User objects in the list) so it was a serious performance hit. I've since began using annotate and prefetch_related which has cut the queries down significantly. I've just got one bit I can't figure out how to annotate. I have a model method (on Summation model) I use to get a summary of Evaluation data for a user like this: def evaluations_summary(self): evaluations_summary = ( self.evaluation_set.all() .values("evaluation_type__name") .annotate(Count("evaluation_type")) ) return evaluations_summary I'm trying to figure out how to annotate that particular query on a User object. So the relationship looks like this User has multiple Summations, but only one is ever 'active', which is the one we display in the User list. Each Summation has multiple Evaluations - the summary of which we're trying to show as well. Here is a summary of the relevant parts … -
How to bootstrap style ModelFormset
I've have a view that uses the formset factory but I'm trying to style the rendered html form. But the usual styling for forms doesn't work and im not sure what i need to do to apply the CSS stytles. My View def get_questionnaire(request, project_id, questionnaire_id): # Get the Response object for the parameters response = Response.objects.get( project_name_id=project_id, questionnaire_id=questionnaire_id ) AnswerFormSet = modelformset_factory(Answer, fields=('answer',), extra=0) answer_queryset = Answer.objects.filter(response=response ).order_by('question__sequence' ).select_related('question') if request.method == 'POST': # to be completed pass else: # Get the list of questions for which no Answer exists new_answers = Question.objects.filter( questionnaire__response=response ).exclude( answer__response=response ) # This is safe to execute every time. If all answers exist, nothing happens for new_answer in new_answers: Answer(question=new_answer, response=response).save() answer_formset = AnswerFormSet(queryset=answer_queryset) return render(request, 'pages/formset.html', {'formset': answer_formset}) for the moment im just trying to style a single field by applying the widgets in forms.py. But this isn't working. class answer_formset(ModelForm): class Meta: model = Answer fields = ('answer',) widgets = { 'answer': forms.Select(attrs={'class': 'form-select'}), } HTML {{ formset.management_form }} {% for form in formset %} {{ form.id }} {{ form.instance.question.question }} {{ form.answer }} <br> {% endfor %} Thanks