Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to map virtual environment's Python instead of the global on Windows production server for a django project
I have a Django project running on the production on Windows 10. I am using nginx and waitress. I've been using the global Python on my server (Python 3.9.5). I was wondering how I can use a virtual environment instead of the global on the production server? I can't figure out how I can map my django application to the new python in the virtual environment. Any ideas how I can accomplish that? -
Django url-erro
Am a begineer in django and i am trying to link my django app's(called base) urls into the my project urls file but i keep getting errors And yes i created a file for urls in my app called apps.urls from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('base.urls')),] -
Cannot establish connection from Django to MySQL
I built 2 containers, one for project with python-3.4.10 and another for MySQL (with mysql-5.7-debian). When I try to run any command for example: python manage.py makemigrations {name} or python manage.py runserver 0.0.0.0:8000 it gives me the following error: django.db.utils.OperationalError: (2003, 'Can\'t connect to MySQL server on \'127.0.0.1\' (111 "Connection refused")') I have literally tried everything and went through each stack issues related to it. But the issue still persists. When I connect on MySQL Workbench (which is installed on my base OS: Windows 11) with the running MySQL container, it gets connected but when I run the command of python manage.py ... on the different container it shows me the above error. Could you please help me out here? Thank you. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 's_db', 'USER': 'root', 'PASSWORD': 'root', 'HOST': '127.0.0.1', 'PORT': '3306', } } docker-compose.yaml version: '3.8' services: web: image: s-compose:latest ports: - 8000:8000 command: > sh -c "python manage.py runserver 0.0.0.0:8000" volumes: - ./s:/home/app/webapp depends_on: - database database: image: mysql:5.7-debian ports: - 3306:3306 environment: MYSQL_ROOT_PASSWORD: root .Dockerfile FROM python:3.4.10 ENV Dockerhome=/home/app/webapp RUN mkdir -p $Dockerhome WORKDIR $Dockerhome COPY ./sansthaonline $Dockerhome RUN pip install -r req.txt; exit 0 EXPOSE 8000 ## testing … -
.env file didn't copy into docker container on AWS EBS
I have the following project structure locally |-- docker-compose.yml |-- docker-entrypoint.sh |-- Dockerfile |-- nginx | `-- loc | `-- nginx.conf |-- poetry.lock |-- pyproject.toml `-- src |-- my_project | |-- asgi.py | |-- __init__.py | |-- settings.py | |-- urls.py | `-- wsgi.py |-- __init__.py |-- manage.py |-- .env In Dockerfile I have the following line COPY /src/ /workdir/ Elastic Beanstalk takes env variable and stores them in .env file by the following path /var/app/current then when the container has been built, the env file wasn't copied inside. I made a workaround by copying .env file COPY .env /workdir/ but it doesn't look like a good solution. Should I move everything from /src folder to one level above? -
How do I update an existing many to many field in Django REST?
I have a plot model like this: class Plot(models.Model): garden = models.ForeignKey('perma_gardens.Garden', on_delete=models.CASCADE) plant = models.ManyToManyField('perma_plants.Plant', related_name='%(class)s_plant', blank=True) def __str__(self): return self.name It contains a field for plants in many to many. In my database, I already have several plants created. And I would like to be able to update the plot model by adding plants to it by ID, I realized a function partial_update in the views.py file but when I update the plot by adding a plant to it based on its ID, it tells me that: "A plant object with this custom id field already exists." Here is my serializers.py file : class GardenSerializer(serializers.ModelSerializer): class Meta: model = Garden fields = ('id', 'name',) class PlantSerializer(serializers.ModelSerializer): class Meta: model = Plant fields = ('custom_id', 'name', "category", 'image', 'facility_rate', 'sunshine_index', 'irrigation_index') class WritePlotSerializer(WritableNestedModelSerializer, serializers.ModelSerializer): plant = PlantSerializer(many=True) class Meta: model = Plot fields = '__all__' Here is my views.py file : class PlotViewSet(viewsets.ModelViewSet): queryset = Plot.objects.all() def create(self, request, *args, **kwargs): serializer = WritePlotSerializer(data=request.data, many=isinstance(request.data, list)) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def partial_update(self, request, *args, **kwargs): instance = self.queryset.get(pk=kwargs.get('pk')) serializer = WritePlotSerializer(instance, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) def delete(self, request, pk): snippet = … -
How can i see my installed Django on Centos 7 server?
I newly installed django on centos 7 server but how can i see my working django website. I have server ip address and also website. Firstly Do I need to change the domain dns with the server ip address? -
Django WebSocket Routing "Not route for path"
I'm trying to get a simple Django Web App with WebSockets going, and can't get the routing to work. I have a basic Consumer, ProgressConsumer, that is used as base for two other Consumers. class ProgressConsumer(WebsocketConsumer): max_anims = None def connect(self): # self.set_max_anims() self.log_cache = "" print("Websocket connected.") if (not self.max_anims): raise NotSetError("max_anims not set") self.room_group_name = "progress" self.accept() self.start_progress_update() def start_progress_update(self): cached_progress = 0 progress = 0 while progress != 100.0: time.sleep(1) if (updates := self.get_log_updates()) == "": continue if "Error" in updates: self.send(json.dumps({"error": updates})) self.clean_log() self.close(3000) return if (progress := self.calculate_progress(updates)) == cached_progress: continue self.send(json.dumps({ 'type': 'progress', 'message': progress, })) cached_progress = progress def disconnect(self, close_code): print("Websocket disconnected. Code: ", close_code) def get_log_updates(self) -> str: if self.log_cache == self.get_log_cache(): return "" s1 = set(self.log_cache.split("\n")) s2 = set(self.get_log_cache().split("\n")) self.log_cache = self.get_log_cache() return str(s1.symmetric_difference(s2)) def calculate_progress(self, difference: str) -> float: if not "Animation" in difference: return 0.0 animation_id = float(re.search("Animation (\d+)", difference).group(1)) return ((animation_id + 1) / self.max_anims) * 100.0 def clean_log(self): raise NotImplementedError("clean_log not implemented") def get_log_cache(self) -> str: raise NotImplementedError("get_log_cache not implemented") The two other consumers are: class FunctionImagesProgressConsumer(ProgressConsumer): max_anims = 4 def clean_log(self): with open("function_images/project_files/logs/_ComplexFunctionScene.log", "w") as f: f.write("") def get_log_cache(self) -> str: with open("function_images/project_files/logs/_ComplexFunctionScene.log", "r") as … -
Django : Ignore a __in type filter in the queryset if it searches the empty list
Having this code sequence queryset = self.filter( brand_id__in=( UserObjectPermission.objects.filter( content_type=brand_ctype, user=user, ).values_list('object_pk') ) ) If there is no UserObjectPermission object that matches the filter content_type=brand_ctype, user=user then the end result will be empty queryset, because brand_id __in will search in [empty queryset]. But I need the reverse. If there is no UserObjectPermision object for this filter (content_type=brand_ctype, user=user) then return all objects, that is, ignore this filter ( brand_id__in=(UserObjectPermission.objects.filter( content_type=brand_ctype, user=user, ).values_list('object_pk') ) I need the brand_id__in filter to run only if there is at least one object in the queryset I hope I was quite understood. Please help) -
Redirecting the user to the same page after POST
I'm building a tournament organizing tool but I have run into an issue. I have a view called index (currently the only view) that shows the tournament leaderboard as well as a table of unfinished matches and a table of finished matches. For each of the unfinished matches I have added an input field for each player where the user can type the scores. Each match also has a submit button. What I want to happen is that when the submit button is clicked, the match is finished and the match result (the scores in the input fields) are saved to the database. I then want the user to see the same page again (with the match moved from unfinished to finished). The problem I'm having is getting the player to be redirected to the same page again. I've tried looking around for similar questions and the answers to them and I have tried a couple of different things like if request.method == "POST": return render(request, './') or if request.method == "POST": return redirect(request.path) or if request.method == "POST": return index(request) all of them redirect me to /index.html which does not exist - my urlpatterns look like this urlpatterns = … -
How to reference a file from root folder to any django app folder
Here i'm create to create an entry which takes a HTML file input. Now I'm trying to do with the following code but getting permission denied. How can I reference that HTML template in my testcase. # CREATE EMAIL TEMPLATE data = { "user":user, "platform_subscriber":project, "name": "TESTCASE TEMPLATE", "html_template": "../nice.html" } email_template, created = EmailTemplate.objects.custom_get_or_create(data) print("The key",email_template) self.email_template = email_template.id log : aise SuspiciousOperation("Attempted access to '%s' denied." % name) django.core.exceptions.SuspiciousOperation: Attempted access to '../nice.html' denied. -
Best way to create a dropdown of values from the same model and save it as text in a Charfield of same model
I have a model "TnaTemplateModel" class TnaTemplateModel(models.Model): id = models.UUIDField(primary_key = True,default=uuid.uuid4, editable=False) template_name = models.ForeignKey(TemplateNameModel, verbose_name="template name", null=False, blank=False, on_delete=models.CASCADE, help_text="Select the template") process_name = models.ForeignKey(ProcessModel, verbose_name="process name", null=False, blank=False, on_delete=models.CASCADE, help_text="Select the process") sequence = models.IntegerField(verbose_name="Process Sequence",null = False,blank = False) is_base = models.BooleanField() dependent_process = models.CharField(verbose_name="Dependent Process",null=True, blank= True,max_length= 150) formula = models.IntegerField(verbose_name="Formula", null= True,blank = True) remarks = models.CharField(verbose_name="Process remarks", null= True, blank = True,max_length= 300) class Meta: unique_together = ["template_name", "process_name"] def __str__(self): return str(self.template_name) I need to save entries from a form where dependent_process field will be a list of all processes in TNATemplateModel with the desired template_name and where is_base = True. For this I have created 2 views and 2 forms 1 each for first saving all the entries with is_base = True and second for saving entries which will have a dependent_process as a dropdown from the previously added is_base = true processes. Views.py #for saving processes with is_base = true def baseprocesscreatenew(request,pk): template_name = TemplateNameModel.objects.get(id=pk) data = {'template_name': template_name.id,'is_base': True} dependent_list = TnaTemplateModel.objects.filter(template_name = template_name.id) if request.method == 'POST': form = BaseProcessModelformNew(request.POST,initial= data) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('templatepointslist_new',kwargs={'pk':pk})) else: form = BaseProcessModelformNew(initial= data) print(form.errors) return render (request,"tna/template_tna/baseprocessmodel_create.html",{'form':form,'dependent_list':dependent_list}) #for saving dependent … -
Django admin not showing users after user customization
I customized my user authentication. Using Django 3. In models.py I have; class User(AbstractUser): is_patient = models.BooleanField(default=False) is_dentist = models.BooleanField(default=False) is_manager = models.BooleanField(default=False) In views.py I have below for user creation and login; def create_account_dentist(request): if request.method == 'POST': #Create Dentist Type User username = request.POST.get('username') password = request.POST.get('password') mobile_num = request.POST.get('mobilenum') user_profile = User() user_profile.username = username user_profile.email = username user_profile.set_password(password) user_profile.is_dentist = True user_profile.is_staff = True user_profile.is_active = True user_profile.mobile_number = mobile_num user_profile.save() login(request, user_profile) return redirect(reverse('dentist-section')) My sttings.py : AUTH_USER_MODEL = 'myapp.User' When i check /admin page i see only groups section. But i want to see the users, permissions and user groups together. My DB tables are : auth_group, auth_group_permissions, auth_permission, django_admin_log, django_content_type, django_migrations, django_session, myapp_dentist, myapp_manager, myapp_patient, myapp_user, myapp_user_groups, myapp_user_user_permissions Although i created users in myapp_user, i dont see and manage them in django admin page Below is screeshot from myapp_user table : -
Multiple translations for given entity in Django
I have a Django app, where one of the universal entities is called Organization. But this is a multitenant applications, and some tenants call their organizations 'Companies', another call them 'Pharmacies' - it depends of their business type. The types of organization are known upfront, so I can prepare translations for their names (in two or more languages) and store a preference which one to use. My question is: how can I select translation in the view depending of the tenant setting? -
Django Rest Framework - Object of type <> is not Json seralizable
I'm new to django rest framework and need some help. I have ApiView: class SomeApiView(APIView): def get_url(self, some_id): return generate_url(Choices.BOOK, some_id) def get(self,request): id = request.query_params.get("some_id") result_url = self.get_url(id) return Response({'result_url': result_url}) here when sending request I get next error: Object of type Choices is not Json serializable. Choices looks like this: class Choices(Enum): BOOK="book" MOVIE="movie" GAME="game" how can I fix this error? Thank you in advance -
I need to create unit tests for my urls in a django project
I have this url which returns the json data of my models but I don't know how to create a unit test for a url like this path("list/", views.json_list, name="json_list"), -
Similar tools like Devexpress for Django
Would like to know if there exists any tools similar to Devexpress gui for Django projects. I found the following link which was posted more than 10 years ago. Maybe currently any solution would be available now? -
Django form in form
I wonder if it is possible to make form in form by using django. For example: class Category(models.Model): title = models.CharField(max_length=200) icon = models.ImageField(upload_to="icons", default="icons/dot.png") def __str__(self): return self.title def get_posts(self): return Post.objects.filter(category__title=self.title) class Post(models.Model): author = models.ForeignKey(Account, on_delete=models.CASCADE) title = models.CharField(max_length=200) category = models.ForeignKey(Category, on_delete=models.CASCADE) description = models.CharField(max_length=400) date_posted = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title While I was working with forms based on these models I was splitting CategoryForm and PostForm into two forms (category had to be made before post to make user able to choose new category during making new post) and then into two views. class PostForm(forms.ModelForm): class Meta: model = Post exclude = ('author',) class CategoryForm(forms.ModelForm): class Meta: model = Catergory fields = '__all__' def newPostView(request): if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.author = request.user obj.save() return redirect('home') form = PostForm() context = {'form':form} return render(request, 'blog/post_form.html', context) def newCategoryView(request) ... ... ... I'd like to make one newPost form which will have Category form implemented - I mean I'd like to be make it possible to choose category from already made categories or make new one if its needed without using another view How can I make it … -
ModuleNotFoundError: No module named 'my_script'
I wanna connect PSQL to django, but store my password not in settings, so I thought I should keep the password in another file, than I import file with password to settings: ... from my_frst_site.local_settings import db ... DATABASES = { 'default': db,} ... my file with password: db = {'ENGINE': 'django.db.backends.postgresql', 'NAME': 'poll_db', 'USER': 'app_manager', 'PASSWORD': 'TWENTY04', 'HOST': 'localhost', 'PORT': '5432', } Now the file structure looks like this: structure of files When I enter command py manage.py check --database default I got error: File "C:\Projects\MY_APP\my_frst_site\my_frst_site\settings.py", line 13, in from my_frst_site.local_settings import db ModuleNotFoundError: No module named 'my_frst_site.local_settings' Anybody know how to fix this problem? -
Django Forms not displaying in html in Django 3
Here i am using Django3 and Python 3.7 I am not able display my form fields while trying to add a custom field initially but as soon as i click Save custom fields button the fields as displaying Here is my views.py class EavAttributeCreateView(CustomAdminMixin, CreateView): model = ClientAttribute form_class = EavAttributeForm template_name = "core/eav_attribute_form.django.html" def form_valid(self, form): print("*** in form valid... ***") try: self.object = form.save(commit=False) self.object.order = form.cleaned_data.get("order", "0") self.object.client = self.request.user.client self.object.type = self.kwargs.get("type") self.object.save() except ValidationError as e: form._errors = e.message_dict return self.form_invalid(form) messages.success(self.request, 'The attribute "{0}" was successfully saved.'.format(self.object.slug)) return redirect(self.get_success_url()) def get_context_data(self, **kwargs): context = kwargs context["eav_type"] = self.kwargs.get("type") context["special_datatypes"] = { "enum": ClientAttribute.TYPE_ENUM, } return context def get_success_url(self): return reverse("entity_attribute_list", kwargs={"type":self.kwargs.get("type")}) Here is my forms.py class EavAttributeForm(forms.ModelForm): description = forms.CharField(max_length=256, required=False, label=u"Hint", help_text="User-friendly custom field name.") datatype = forms.ChoiceField(choices=Attribute.DATATYPE_CHOICES) type = forms.CharField(max_length=20, required=False, widget=forms.HiddenInput) order = forms.FloatField(required=False, initial="0", help_text=u"The fields are ordered according to this number, from the lowest to the highest.") enum_group = ChoicelessTypedMultipleChoiceField(required=False, label="Choice values", coerce=enum_value, widget=forms.CheckboxSelectMultiple) class Meta: model = Attribute fields = ["type", "name", "description", "required", "order", "datatype", "enum_group", "in_enquiry_form", "is_auto_filter"] exclude = ("in_enquiry_form", "is_auto_filter") def clean_enum_group(self): ..... ..... Here is my template.html <div class="row"> <div class="span10 offset1"> <!-- START … -
[ErrorDetail(string='Incorrect type. Expected pk value, received str.', code='incorrect_type')]
hi guys I am a novice to django,and I have been making a CRUD with Products having categories,sub categories,colors,size.When I am trying to make a new "category" the data isnt getting displayed on webpage heres the error: below is the serializer of Categories and the foreign key and the insert_cat function when I am trying to insert a data into webpage it comes blank I am not sure where I am going wrong,please help -
Django server only listening to socket server and ignoring routes
Here is my WSGI.py file in django, im importing the folder called "webSocket" that contains the views.py file where the server code for the socket is written from django.core.wsgi import get_wsgi_application from webSocket.views import server import socket import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'b2b_backend.settings') application = get_wsgi_application() # make the app run with socketio application = socket.WSGIApp(application, server) here is my urls.py file in root folder of django, the routes are working fine before adding the socket server to the project from django.urls import include, path urlpatterns = [ path('users/', include('database_models.b2b_user.urls')), ] here is my socket server file in the webSocket folder views.py file import socket import threading SERVER = "localhost" PORT = 8000 HEADER = 64 ADDR = (SERVER, PORT) FORMAT = 'utf-8' DISCONNECT_MESSAGE = "!DISCONNECT" server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(ADDR) def handle_client(conn, addr): print(f"[NEW CONNECTION] {addr} connected.") connected = True while connected: msg_length = conn.recv(HEADER).decode(FORMAT) if msg_length: msg_length = int(msg_length) msg = conn.recv(msg_length).decode(FORMAT) print(f"[{addr}] {msg}") if(msg == DISCONNECT_MESSAGE): connected = False conn.send("test".encode(FORMAT)) conn.close() def start(): server.listen() while True: conn, adrr = server.accept() thread = threading.Thread(target=handle_client, args=(conn, adrr)) thread.start() print(f"[ACTIVE CONNECTIONS]", {threading.active_count() - 1}) print(f"[STARTING] server is starting on {SERVER}:{PORT}") start() what is the problem: when running the django server, it starts … -
In django, can the .using('db') keyword take a variable?
Example.objects.using('db').raw() Instead of db could we have a variable that would correspond to the appropriate database? -
Cookiecutter requirements instalation problem
I'm learning Django(just started) using Django Crash Course book and for going on I have to install cookiecutter. There are a template there: gh:roygreenfeld/django-crash-starter. I activate venv, install cuckiecutter template, and when I try to install requirements, I get a bunch of errors. I have tried several templates, all gave me some errors. The example from the textbook gives this: Using cached wrapt-1.14.1-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl (77 kB) Building wheels for collected packages: Pillow, django-allauth, ipdb, pytest-sugar, django-test-plus, factory-boy, django-coverage-plugin, termcolor Building wheel for Pillow (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/mikhail/programming/exercises/python/django_crash_course/everycheese/venv/bin/python3.9 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-jj_zmz6q/Pillow/setup.py'"'"'; __file__='"'"'/tmp/pip-install-jj_zmz6q/Pillow/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-ipb4dz0c cwd: /tmp/pip-install-jj_zmz6q/Pillow/ Complete output (6 lines): usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: setup.py --help [cmd1 cmd2 ...] or: setup.py --help-commands or: setup.py cmd --help error: invalid command 'bdist_wheel' ---------------------------------------- ERROR: Failed building wheel for Pillow Running setup.py clean for Pillow Building wheel for django-allauth (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/mikhail/programming/exercises/python/django_crash_course/everycheese/venv/bin/python3.9 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-jj_zmz6q/django-allauth/setup.py'"'"'; __file__='"'"'/tmp/pip-install-jj_zmz6q/django-allauth/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-_r7vlqar cwd: /tmp/pip-install-jj_zmz6q/django-allauth/ Complete output (6 lines): usage: setup.py [global_opts] … -
How to save file in creating folder when data inserto the data base django
I want to save file in automatically created folder related with Employee id_number. I add following code in models.py from django.db import models class Employee(models.Model): id_number = models.CharField(primary_key=True, null=False, blank=False, unique=True, max_length=15) full_name = models.CharField(max_length=255, null=False, blank=False) name_with_initials = models.CharField(max_length=255, null=False, blank=False) surname = models.CharField(max_length=255, null=False, blank=False) phone = models.CharField(max_length=15, null=False, blank=False) dob = models.DateField(null=False, blank=False) gender = models.CharField(max_length=10, null=False, blank=False) email = models.EmailField() address = models.CharField(max_length=255, null=False, blank=False) class EmployeeAttachments(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) cv = models.FileField(upload_to=f'employee/attachments/', max_length=100) i want to save cv file in ex:- media->employee->attachments->emp001->emp001.pdf can any one tell me how to do this in django, django-rest-framework -
Editing the 1st Row using Django Forms is not working, but working for the rest rows. How to rectify it?
I have a Django Form which has a problem. It is not editing the 1st row of the table of the database fetched in the template and working fine from 2nd rows onwards. the issue seems to be with the dynamic URL: Suppose in this HTML table :- as I hit the edit button for 1st row, no new URL is generated, i.e. same old URL say http://xxx.xx:xx/djangoapp/state_wise is returned, which just refreshes the page :- but while I hit the edit button for the 2nd row and onwards, the URL changes dynamically as http://xxx.xx:xx/djangoapp/edit_data_from_db/8086/? and the edit form appears as : the forms.py file is as: class details_to_database(forms.ModelForm): class Meta: model = GroupDetail BOOL_CHOICES = ((True, 'Yes'), (False, 'No')) UNIT_CATEGORIES = (('ABC', 'ABC'), ('DAMU', 'DAMU')) fields = ["unit_type", "state_name", "unit_name", "district_name", "block_name", "village_name", "village_covered", "number_of_groups", "number_of_farmers"] labels = { "unit_type":"Unit Type", "state_name":"State Name", "unit_name":"Unit Name", "district_name":"District Name", "block_name":"Block Name", "village_covered":"Village Covered (Yes/No)", "number_of_groups":"Number of groups", "number_of_farmers":"Number of farmers"} widgets = { "unit_type":forms.Select(attrs={"class":"form-control", "id":"unit_type_id"}, choices=UNIT_CATEGORIES), "state_name":forms.TextInput(attrs={"class":"form-control", "id":"state_name_id"}), "unit_name":forms.TextInput(attrs={"class":"form-control", "id":"unit_name_id"}), "district_name":forms.TextInput(attrs={"class":"form-control", "id":"district_name_id"}), "block_name":forms.TextInput(attrs={"class":"form-control", "id":"block_name_id"}), "village_name":forms.TextInput(attrs={"class":"form-control", "id":"village_name_id"}), "village_covered":forms.Select(attrs={"class":"form-control", "id":"village_covered_id"}, choices=BOOL_CHOICES), "number_of_groups":forms.NumberInput(attrs={'min': '1',"class":"form-control", "id":"number_of_groups_id"}), "number_of_farmers":forms.NumberInput(attrs={'min': '1',"class":"form-control", "id":"number_of_farmers_id"}) } The model.py file is as: BOOL_CHOICES = ((True, 'Yes'), (False, 'No')) UNIT_CATEGORIES = (('ABC', 'ABC'), …