Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Postgres search functionality that allows to user to search UUID string in database table in Django APP
I would like to use postgres to perform searches on a django app, most pf the resources seem to focus on full text search. However I would like the ability to search by UUID, Peoples' names, Reference numbers etc. I have googled to find resources and examples, but thinking is coming up. Please assist, with links or ideas on hoe to tackle this. Our Django app is using SQLAlchemy -
Django autoescape still displays HTML Tags for a custom filter
I have created a custom filter, that basically looks like this from django import template from datetime import datetime from django.contrib.humanize.templatetags.humanize import intcomma from django.utils.safestring import mark_safe register = template.Library() def into_bs_badge(value): # <span class="badge badge-primary">Primary</span> # <span class="badge badge-secondary">Secondary</span> # <span class="badge badge-success">Success</span> # <span class="badge badge-danger">Danger</span> # <span class="badge badge-warning">Warning</span> # <span class="badge badge-info">Info</span> # <span class="badge badge-light">Light</span> # <span class="badge badge-dark">Dark</span> badge = '<span class="badge badge-primary">' + str(value)+ '</span>' return badge # return mark_safe(badge) register.filter('into_bs_badge', into_bs_badge) In my page I have {% autoescape off %} {{ value.credits_count | into_bs_badge}} {% endautoescape %} But I still gets something like, instead of rendering the actual badge <span class="badge badge-primary">28</span> I have also tried return mark_safe(badge) But when I use mark_safe i get nothing display in the page, I am wondering what could i possible be missing -
django.utils.crypto get_random_string() causing duplicate key error?
I'm using get_random_string() from django.utils.crypto to generate a random short_id for my model. There's only a few dozen entries. from django.utils.crypto import get_random_string class MyModel(models.Model): ... short_id = models.CharField(default=get_random_string, max_length=12, unique=True) For some reason, I'm getting a duplicate key error when I try to run my migration: Any ideas? DETAIL: Key (short_id)=(88hUwNQjTIns) is duplicated. -
How to add IP whitelist in an HTTP API?
I want to add the feature of allowing only some IP addresses(list would be given already) to access my HTTP API, written with DJango and Django Rest Framework. -
How to get recent values in this db?
I use sqlite. class Member(models.Model): member_id = models.AutoField(primary_key=True) is_update = models.IntegerField(default=0) member_name = models.CharField(max_length=50) member_group = models.IntegerField(default=0) room_name = models.CharField(max_length=20) bed_name = models.CharField(max_length=20) gender = models.IntegerField(default=0) birth_date = models.DateField() phone_number = models.CharField(max_length=11) protector = models.CharField(default='protector',max_length=50) def __str__(self): return str(self.member_id) def initIsUpdate(self): self.is_update = 0 return 0 class Inpatient(models.Model): member_id = models.ForeignKey(Member, on_delete=models.CASCADE, db_column = 'member_id', related_name='member') inpatient_status = models.IntegerField(default=0) is_in_room = models.IntegerField(default=0) is_on_bed = models.IntegerField(default=0) heart_rate = models.IntegerField(default=0) breath_rate = models.IntegerField(default=0) update_time = models.DateTimeField(auto_now_add=True, blank=True) protector_name = models.CharField(max_length=50) def __str__(self): return str(self.member_id) And Members are 4 people.. Each Members have same values in Inpatient DB. It gets new queryset for every 1 sec. And I want get 4 Member's most recent Inpatient DB. How I get that DB?? -
How to generate a testing report in Django using selenium and LiveServerTestCase?
I have been using LiveServerTestCase to build test cases for my Django project for a month. Now, I am creating more test cases using Selenium and LiveServerTestCase together to test how my project runs automatically. I want to know how can I generate and export a testing report using Selenium and LiveServerTestCase. Is there an inbuilt solution from selenium that allows me to do so? Or I have to code the part of generating the file? Sorry, I am new to Django and Selenium. Thanks in advance! -
How to calculate date between different fields in two querysets with same foreign key in Django
I am using Django. Is there a way to count between different fields in a queryset with the same foreign key??!! That is, we want to subtract register_date from injection_date. You want to get (2021-1-03) - (2021-10-31) = 3days. injection_date enroll_date student_id (외래키) 2021-10-31 52 2021-11-03 52 Below is the code I've written so far, how do I fix it?! Please help. [views.py] injection_enroll = Student.objects\ .annotate(injection_enroll=F('injection_date') - F('enroll_date'))\ .values('injection_enroll') -
Text editor summernote for admin panel Django loading very slowly
I have an Enterprise model and there are more than 60 fields in this model, Summernote-Django has been added to the text editor. In my case, 25 fields in one model have been added to the text editor by the Summernote-Django, the problem is that this model on the admin panel is very, very slow to load. How can I optimize Summernote-Django? I added 'lazy': True to the settings, but it didn't help.Perhaps you would recommend another library for adding text editors to the django administration more optimized? Here is a screenshot on the Enterprise page, on dev tools shows that more than 100 js/jQuery files are being uploaded from Summernote-Django -
Multiple templates in a single Listview
I have some ListViews implemented seperately with different template_names with similar model,How can i use implement them in one single List view that can take multiple templates? Views.py class ManagerOpenedTicketView(LoginRequiredMixin,TemplateView): template_name = 'app/pm_open_tickets.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tickets'] = Ticket.objects.filter(status = 'Opened',created_by = self.request.user) return context class ManagerCompletedTicketView(LoginRequiredMixin,TemplateView): template_name = 'app/pm_completed_tickets.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tickets'] = Ticket.objects.filter(status = 'Completed',created_by = self.request.user) return context -
What is the difference in using Django Rest API vs django.contrib.auth to build a login/logout app
I am new to Django and I want to build a login and logout for a chat app I am making which I plan to deploy eventually. From the online tutorials I see, there are some that use the Django Rest API framework, and some use the pre-installed django.contrib.auth Is there any difference in choosing which to use? -
Trying to stay DRY in Django: Refactoring repetitive code in Views
I have a lot of different list views for tables. Each view differs only in the template used. My only successful strategy involves using a decorator containing the common code and then returning 'pass' for the view function. The problem I face is if I want to add individual code to a specific list view that differs from the others. Is there a better way of doing this? Here is my decorator: def my_decorator(html=""): def my_decorator(*args, **kwargs): def wrapper(request, *args, **kwargs): bacteria = Bacteria.objects.all() bacteria_count = bacteria.count() bacteriaFilter = BacteriaFilter(request.GET, queryset=bacteria) bacteria = bacteriaFilter.qs remaining = bacteria.count() common_tags = Bacteria.tags.most_common()[:8] ''' context = {"bacteria": bacteria, 'common_tags': common_tags, 'bacteria_count': bacteria_count, 'bacteriaFilter': bacteriaFilter, 'remaining': remaining} ''' return render(request, html, locals()) return wrapper return my_decorator And here are several examples (I have over 15 tables) of the list view functions: @my_decorator(html="bacteria/generalPhysiology.html") def general_physiology_view(request): pass @my_decorator(html="bacteria/enzymeActiveTable.html") def enzyme_activity_table_view(request): pass -
Django autocomplete light Select2 widget not appearing
I have been following the DAL tutorial and can access a json object at http://127.0.0.1:8000/entry/river-autocomplete/?q=S So i know my view is working. Beyond that I cannot seem to get anything but the standard widget for ForignKey. From looking at the following posts in stackoverflow I feel that some static files or javascript libraries are not loading properly but for the life of me I cannot figure out how to fix this. django-autocomplete-light template not rendering autocomplete widget django-autocomplete-light displays empty dropdown in the form Below are all of the files that I think pertain to this issue. If I can clarify things any further please let me know. views.py #autocomplete view class RiverAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): #User filtering code goes here if not self.request.user.is_authenticated: return River.objects.none() qs = River.objects.all() if self.q: qs = qs.filter(river_name__istartswith=self.q) return qs models.py class River(models.Model): river_name = models.CharField(max_length=50) aw_id = models.CharField(max_length=20) state = models.CharField(max_length=5) def __str__(self): return "{river}".format(river=self.river_name) class JournalEntry(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField() river = models.ForeignKey("River", on_delete=models.CASCADE) flow = models.FloatField() description = models.TextField(max_length=250) public = models.BooleanField(default=False) # picture = models.ImageField() def __str__(self): return "{river}--{date}".format(river=self.river, date=self.date) forms.py from django import forms from . import models from .widgets import FengyuanChenDatePickerInput from dal import autocomplete class … -
How to disable access to a django APIs based on is_active boolean field?
I have an author's model with a field: is_active = models.BooleanField(default=False) I wish to restrict access to the author whose is_active=False. I can use something like this in every api: get_object_or_404(uuid=id, is_active=True) But I wish to globally restrict access to the UUID whose is_active=false, instead of actually writing this statement in every api. Is there a way I can do that? -
Django Rest Framework nested relationship performance on SerializerMethodField
I have been looking for an answer but get none. This is the situation: I have 3 models defined like this: class State(models.Model): name = models.CharField(max_length=150, null=False) code = models.CharField(max_length=5, null=False) class City(models.Model): name = models.CharField(max_length=150, null=False) code = models.CharField(max_length=7, null=False) state = models.ForeignKey(State, related_name='cities', on_delete=models.RESTRICT) class Home(models.Model): code = models.CharField(max_length=25, null=False city = models.ForeignKey(City, related_name='homes', on_delete=models.RESTRICT) The response that the people needs on homes is something like this [ { "code": "10011", "city": "Municipio 1", "state": "Departamento 1" }, { "code": "10012", "city": "Municipio 1", "state": "Departamento 1" } ] I was able to create that response doing this with the serializer: class HomeSerializer(serializers.ModelSerializer): city = SlugRelatedField(slug_field='name', queryset=City.objects.all()) state = SerializerMethodField() class Meta: model = Home fields = ['code', 'city', 'state'] def get_state(self, obj): return obj.city.state.nombre But Im not sure if this is the right way to do it, home is a table that is gonna grow up a lot (maybe 1M+ rows), and I am thinking that this solution is gonna hit the database multiple times. Now I know that I can add filtering and pagination, but I am concern about the performance of this solution. I also tried with depth = 2 but they hated it. I've … -
How to change the renaming pattern when there are duplicate files
Let's say I upload a file to my Django App (A.pdf) Over time I realize that that file contains an error. I want to upload that file back to my website and keep the old file, but I want the file name to change to A(1).pdf I implemented a drag & drop system with Dropzone.js and everything is working but, when a file is duplicated the system assigns new names randomly. This is an example: How can I get rid of the _QXjmarl string and replace it with (N) pattern? E.g. (1), (2), (3)...(45), (N) Dropzone.js: var Drop = Dropzone.options.DidDropzone = { autoProcessQueue: false, //stops from uploading files until user submits form paramName: "filename", // The name that will be used to transfer the file maxFilesize: 1024, // Maximum size of file that you will allow (MB) clickable: true, // This allows the dropzone to select images onclick acceptedFiles: '.psd, .csv, .doc, .docx, .xls, .xlsx, application/csv, application/docx, application/excel, application/msword, application/pdf,application/vnd.ms-excel, application/vnd.msexcel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, text/anytext, text/comma-separated-values, text/csv, text/plain, image/*, video/*,', //accepted file types maxFiles: 20, //Maximum number of files/images in dropzone parallelUploads: 20, previewTemplate: '<div class="dz-preview dz-image-preview">'+ '<div class="dz-image">'+ '<img data-dz-thumbnail />'+ '</div>'+ '<div class="dz-details">'+ '<div class="dz-filename"><span data-dz-name></span></div>'+ '<div class="dz-size" data-dz-size></div>'+ '</div>'+ … -
On adding a Model using the Admin Panel in Django, is there a way to implement altering other Models?
I am using the standard Admin Panel in Django that has a Model, Product, that contains its information. the Product has a TextField() Summary of words. I would like to implement a Keyword model that has a single word. The idea is that the Keyword would be applied to multiple Products if the Product has the Keyword's word in its Summary. I am trying to implement that when the Admin in the Admin panel adds a Keyword model, the server would automatically assign each Product that Keyword. The issue is that I do not know how to edit the Admin Panel's add function to edit other models upon adding one model. My current understanding in Django is that you could create a custom view to add a Keyword, but I would like to have the option to implement it in the Django Admin Panel as well. -
Using manytomany field as foreignkey in the other class under model in Django
Models.py Here I am trying to use the attribute: working_hours which is manytomany - as a foreignkey in other model please help me sort the concern if possible class AvailableTime (models.Model): available_time = models.CharField(max_length=100) def __str__(self): return str(self.available_time) class AttendantAvailability(models.Model): attendant_name_choices=[('AN1',"Ipsum Lorem"), ('AN2',"Lorem Lorem"),] attendant_name = models.CharField(max_length=3, choices=attendant_name_choices) def attendant_name_lookup(self): for choice in self.attendant_name_choices: if choice[0] == self.attendant_name: return choice[1] return '' booked_date = models.DateField(null=True, blank=True) working_hours = models.ManyToManyField(AvailableTime) def __str__(self): return str(self.working_hours) class ServiceDetail(models.Model): name = models.ForeignKey(ServiceName, null=True, on_delete=models.CASCADE,) category_name = models.ForeignKey(Category, default = None,on_delete=models.CASCADE,) preferred_time = models.ForeignKey(AttendantAvailability) def __str__(self): return str(self.preferred_time) This isn't working for me !! I need to use the Manytomany field "working_hours " as the foreignkey in other class ERROR: self.models_module = import_module(models_module_name) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\User\Service_Management\Salon_Services\models.py", line 45, in <module> class ServiceDetail(models.Model): File "C:\Users\User\Service_Management\Salon_Services\models.py", line 122, in ServiceDetail preferred_time = models.ForeignKey(AttendantAvailability) NameError: name 'AttendantAvailability' is not defined Please help! -
trouble with Django Channels and connecting with Flutter
Problem: When trying to connect to channels, I get an error in flutter: WebSocketChannelException: WebSocketException: Connection to 'http://"###my ip ###":8000/ws/joingroup/8598969d-3dfa-4017-849c-dcbb71c1f9f0/#' was not upgraded to websocket I am using the websocket channel package and in a flutter controller I have: WebSocketChannel? channel; //initialize a websocket channel bool isWebsocketRunning = false; void startStream() async { if (isWebsocketRunning) return; //check if socket running var url = 'ws://${ip}:8000/ws/joingroup/${Get.parameters['groupid']}/'; this.channel = WebSocketChannel.connect( Uri.parse(url), //connect to a websocket ); channel!.stream.listen( (event) { print(json.decode(event)); }, onDone: () { isWebsocketRunning = false; }, onError: (error) { debugPrint('ws error $error'); } ); } question 1) why does it say 'http://..." when I clearly outlined it as a ws url. in the back end I am using django channels. app routing:: from django.urls import re_path from django.urls import path #this is utilizing relative paths. this is more advanced paths. # from . import consumers websocket_urlpatterns = [ path('ws/joingroup/<slug:groupid>/', consumers.ChatConsumer ) ] and routing for project: # mysite/routing.py from channels.auth import AuthMiddlewareStack #hooking into auth that django provides^ from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator import myapp.routing from django.core.asgi import get_asgi_application # the allowedhosts is for what ever is in your allowehost in setting.py application = ProtocolTypeRouter({ # (http->django … -
Timestamps are added to the model with a different timezone
I am aware that thousands of similar questions have been asked on SO, but after researching a few hours I did not find any solution that worked. I am using Django 3.2.8 I have checked many StackOverflow questions and answers, none have worked for me. For example this one I also checked the official docs like ten times. Here is my models.py: from django.db import models from django.contrib.auth.models import User class FileHistory(models.Model): filename = models.FileField(null=True, blank=True, upload_to="project_files/") user = models.ForeignKey( User, null=True, blank=True, on_delete=models.SET_NULL, ) timestamp = models.DateTimeField(auto_now_add=True, blank=True) And my settings.py (truncated), following the suggested configuration (L10N false and Time_Zone changed to 'Asia/Tokyo': TIME_ZONE = 'Asia/Tokyo' USE_I18N = True USE_L10N = False USE_TZ = True -
Django: timezone conversion inside templates
I am attempting to convert UTC dates to my users timezones. All dates are stored in the database as UTC and each users timezone is also stored (captured when they signed up). The problem is, when I use timezone.activate(user_timezone) to try and convert the dates to the users timezone in my templates using the {% timezone on %} template tag, it keeps returning the same UTC date. I have tried every settings configuration possible but the problem continues. views.py from dateutil.relativedelta import relativedelta import def home(request): if request.method == 'GET': #users stored timezone e.g 'america/chicago' users_tz = reqeuest.user.timezone #activate users timezone timezone.activate(request.user.timezone) return render(request, 'home.html') home.html {% load tz %} ... {% localtime on %} <div style="float: right;"><b>Registered: </b> {{ user.registered_date }}</div> {% endlocaltime %} settings.py ... USE_I18N = True USE_L10N = True TIME_ZONE = 'UTC' -
encrypt and decrypt image using javascript
My server using this python function to encrypt and decrypt images. I want to do the same encryption in the frontend and send to this function in the backend. how to convert this method into JavaScript def encrypted_decrypted_image(image): key = 48 count = 0 for index, value in enumerate(image): count += 1 image[index] = value ^ key if count == 10: break return image -
How to use HTMLCalendar
I'm using Django, and I'm using the HTMLCalendar module to print a calendar on a page. Currently, the code below works fine, but when the date between 'from date' and 'to date' is more than 2days, I want to express it in one line instead of adding an event to each date belonging to the period. No matter how hard I searched, I couldn't find any posts with similar difficulties, and I haven't been able to solve them on my own for several days. Help! [models.py] class Leave(models.Model): title = models.CharField(max_length=50, blank=True, null=True) from_date = models.DateField(blank=True, null=True) end_date = models.DateField(blank=True, null=True) memo = models.TextField(blank=True, null=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True) is_deleted = models.BooleanField(default=False) create_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) @property def get_html_url(self): url = reverse('leave:leave_edit', args=(self.id,)) return f'<div class="event-title" colspan="{self.end_date - self.from_date}"><a href="{url}" style="color:black;"> {self.title} </a></div>' [forms.py] class LeaveForm(ModelForm): class Meta: model = Leave # datetime-local is a HTML5 input type, format to make date time show on fields widgets = { 'from_date': DateInput(attrs={'type': 'datetime', 'class': 'datepicker', 'autocomplete': 'off'}, format='%Y-%m-%d'), 'end_date': DateInput(attrs={'type': 'datetime', 'class': 'datepicker', 'autocomplete': 'off'}, format='%Y-%m-%d'), 'user': Select(attrs={"disabled": 'disabled'}), } fields = ['title', 'from_date', 'end_date', 'memo', 'user'] def __init__(self, request, *args, **kwargs): super(LeaveForm, self).__init__(*args, **kwargs) # input_formats … -
django allauth send me to /accounts/social/signup/# after I complete my authentication with google sing-in
I integrated djang0-allauth with my app but something is not fully working. Every time I try to login/sign by visiting http://127.0.0.1:8000/accounts/google/login/ and following the google auth flow, I am eventually sent to http://127.0.0.1:8000/accounts/social/signup/ where I am stuck in some sort of loop of sing-in and sing-up. I guess I didn't set-up my settings properly? Or maybe I need to do something with the adapters.py Just for context, I have a custom user model which maybe is also creating issues? settings """ Django settings for mywebsite project. Generated by 'django-admin startproject' using Django 3.2.5. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os import django_on_heroku import django_heroku import cloudinary import cloudinary_storage import dj_database_url from decouple import config import cloudinary.uploader import cloudinary.api # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', False) #env docs https://apple.stackexchange.com/questions/356441/how-to-add-permanent-environment-variable-in-zsh LOCAL = os.environ.get('ARE_WE_LOCAL', False) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True DEBUG_PROPAGATE_EXCEPTIONS = … -
How to get the duration of video when file is uploaded in the Django view.(with ffprobe)
I am creating a video streaming service with the Django. I want to get the duration of video when the video is uploded. So i've installed ffmpeg with brew (Mac OS), and created the command with subprocess but didn't working. I don't know what I have to do. These are things that I tried. views.py class MovieUpload(user_mixins.MoiveUploadPermissionView, FormView): """MovieUpload View""" form_class = forms.MovieUploadForm template_name = "movies/movie_upload.html" def form_valid(self, form): movie = form.save() filename = movie.video.path result = subprocess.check_output( f'ffprobe -v quiet -show_streams -select_streams v:0 -of json "{filename}"', shell=True, ).decode() fields = json.loads(result)["streams"][0] duration = fields["tags"]["DURATION"] print(duration) movie.user = self.request.user movie.save() return redirect(reverse("movies:detail", kwargs={"pk": movie.pk})) I tried this, but makes the error: Command 'ffprobe -v quiet -show_streams -select_streams v:0 -of json "/Users/bami/Documents/cineacca/uploads/SampleVideo_1280x720_20mb.mp4"' returned non-zero exit status 1. I tried with just filename, not filepath but the error was the same. class MovieUpload(user_mixins.MoiveUploadPermissionView, FormView): """MovieUpload View""" form_class = forms.MovieUploadForm template_name = "movies/movie_upload.html" def form_valid(self, form): movie = form.save() filename = movie.video.path duration = subprocess.check_output( [ "ffprobe", "-i", f"{filename}", "-show_entries", "format=duration", "-v", "quiet", "-of", "csv=%s" % ("p=0"), ] ) print(duration) movie.user = self.request.user movie.save() return redirect(reverse("movies:detail", kwargs={"pk": movie.pk})) This code makes the same error. class MovieUpload(user_mixins.MoiveUploadPermissionView, FormView): """MovieUpload View""" form_class = forms.MovieUploadForm template_name … -
Django and HTML- how to apply styling to specific answers
I am working on a Django project where I have a survey form and this corresponding HTML syntax : <label for="id_form-{{ forloop.counter0 }}-answer">Answer:</label> {% for answer in answers %} <label for="id_form-{{ forloop.counter0 }}-answer"> <input type="radio" name="form-{{ forloop.parentloop.counter0 }}-answer" id="id_form-{{ forloop.counter0 }}-answer" value="{{answer.id}}"> {{answer.text}} {% if answer.image %} <img src="/static/mysurveys/{{answer.image}}.png"> {% endif %} </label> {% endfor %} This syntax is working fine for now, but my question is, how can I get rid of the for loop so that I can apply specific stylings to each answer? In this case, the user is supposed to select an image from a group of images as the answer, and I just want the images to be arranged in a circle container. I have tried something like this: <label for="id_form-{{ forloop.counter0 }}-answer">Answer:</label> <div class="circle-container"> <label for= 'id_form-{{ forloop.counter0 }}-answer' class='center'> <input type="radio" name="form-{{ forloop.parentloop.counter0 }}-answer" id="id_form-{{ forloop.counter0 }}-answer" value="{{answer.id}}"> <img src="/static/mysurveys/female_neutral.png"> </label> <label for= 'relaxed' class='deg22_5'> <input type="radio" name="form-{{ forloop.parentloop.counter0 }}-answer" id="id_form-{{ forloop.counter0 }}-answer" value="{{answer.id}}"> <img src="/static/mysurveys/female_relaxed.png"> </label> But, with this code the answer is not being recorded in the database and I am getting an error that says: Formset is NOT valid. [{'answer': ['This field is required.']}]. Please, let me know of any …