Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Field 'id' expected a number but got ''
I am trying to display all the posts by a particular user in their profile page.. So if someone visits my profile page, they can see all of my posts and so on. all_post_by_user = Log.objects.filter(author=username) I am getting the post by a particular username.. author is defined in models.py username is passed as an argument to the view.. I am getting the error The below is my profile.html: {% extends 'log/base.html' %} {% block content %} {% load socialaccount %} {% get_social_accounts profile as accounts %} {%load crispy_forms_tags %} <title>Error logger - Profile {{ profile.username }}</title> <div class="content-section card bg-dark text-white p-4"> <div class="media"> {% if profile.username == user.username %} {% if accounts %} <img class='rounded-circle account-img' src="{{ profile.socialaccount_set.all.0.get_avatar_url }}" /> {% else %} <img class="rounded-circle account-img" src="{{ profile.profile.avatar.url }}"> {% endif %} {% else %} {% if accounts %} <img class='rounded-circle account-img' src="{{ profile.socialaccount_set.all.0.get_avatar_url }}" /> {% else %} <img class="rounded-circle account-img" src="{{ profile.profile.avatar.url }}"> {% endif %} {% endif %} <div class="media-body"> <h2 class="account-heading">{{profile.username}}</h2> <p >{{profile.email}}</p> <p>Created on: {{ profile.profile.created }}</p> {% if profile.username == user.username %} <p>Last updated on : {{ profile.profile.updated }}</p> {% endif %} </div> </div> <!-- FORM HERE --> {% if profile.username == … -
Django Foreign Key Relation Fails: Referencing column and referenced column in foreign key constraint are incompatible
I'm trying to add a foreign key relation between two models in Django, but I'm getting this error. Here is the Lab model: class Lab(models.Model): lab_id = models.AutoField(primary_key=True) lab_name = models.CharField(max_length=40) lab_model = models.IntegerField() And here is the Notification model that needs to have a foreign key field relation with the Lab model: class Notification(models.Model): ... lab_extension = models.ForeignKey(NokiaLabs, on_delete=models.CASCADE, null=True, to_field='lab_id') After assigning this foreign key field to the Notification model, I get this error when doing python manage.py migrate: django.db.utils.OperationalError: (3780, "Referencing column 'lab_extension_id' and referenced column 'lab_id' in foreign key constraint [fk constraint name] are incompatible.") It's likely this error will not persist if I remove the AutoField from the Lab model, and use the default id field. But I'm at a point into the project where I can't do that. I also realize a foreign key field is generally not nullable, but for this project, the Notification model may or may not point to a Lab model. -
Group by in Django with field distinction
I have two tables, one for products and one for suppliers, I did a query that returns this: select f.nome, f.cnpj, sum(p.quantidade) as "Quantidade de Produtos", count(distinct categoria_id) as "Categorias com Produtos " from core_produtos p inner join core_fornecedor f on p.fornecedor_id=f.id group by f.nome, f.cnpj order by f.nome ASC; and she returns a table like this: nome | cnpj | Quantidade de Produtos | Categorias com Produtos --------------+--------------------+------------------------+-------------------------- fornecedor 1 | 10.331.608/0001-52 | 7339 | 5 fornecedor 2 | 00.333.725/0001-00 | 7673 | 5 fornecedor 3 | 88.550.421/0001-37 | 8423 | 5 fornecedor 4 | 03.251.500/0001-94 | 14101 | 5 fornecedor 5 | 25.862.630/0001-04 | 8988 | 5 my question is: how do I query using django's ORM? -
Automatic ldap login is possible using django-auth-ldap package?
how to achieve automatic ldap login in django application? is it possible by using django-auth-ldap package? -
is there any way to use the path argument in extra_context dict in django?
I have an url into my url patterns like this: path("object_edit/<id>/",TemplateView.as_view("object_edit.html") There is any way to use de argument in the pattern to pass it as extra_context to the template? -
How can i add diffrent sizes of the same product?
I have created a function where i can add products to my shopping cart. The problem is that when i add one product at a time, from different product that is, it works. But when i try to add the same product in different sizes i get this error, how do i fix this?. def add_cart_size(request, product_id, product_size): product = Product.objects.get(id=product_id) product_size = ProductSize.objects.get(pk=product_size) print('size', product_size) try: cart = Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create( cart_id=_cart_id(request) ) cart.save() try: cart_item = CartItem.objects.get(product=product, cart=cart, size=product_size.name) # noqa:501 if cart_item.quantity < cart_item.product.stock: cart_item.quantity += 1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product=product, quantity=1, cart=cart, size=product_size.name ) cart_item.save() return redirect('cart_detail') def add_cart(request, product_id): product = Product.objects.get(id=product_id) try: cart = Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create( cart_id=_cart_id(request) ) cart.save() try: cart_item = CartItem.objects.get(product=product, cart=cart) if cart_item.quantity < cart_item.product.stock: cart_item.quantity += 1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product=product, quantity=1, cart=cart ) cart_item.save() return redirect('cart_detail') def cart_detail(request, total=0, counter=0, cart_items=None): try: cart = Cart.objects.get(cart_id=_cart_id(request)) cart_items = CartItem.objects.filter(cart=cart, active=True) for cart_item in cart_items: total += (cart_item.product.price * cart_item.quantity) counter += cart_item.quantity except ObjectDoesNotExist: pass return render(request, 'cart/cart.html', dict(cart_items=cart_items, total=total, counter=counter)) # noqa:501 def cart_remove(request, product_id): cart = Cart.objects.get(cart_id=_cart_id(request)) product = get_object_or_404(Product, id=product_id) cart_item = CartItem.objects.get(product=product, cart=cart) … -
How to remove microseconds in django DateTimeField
Hi people I have a datetimefield in my projects Model the original value is the below: 2021-06-15 21:39:06.842317 after using datetime.now().strftime("%Y-%m-%d %H:%M:%S") this is the result: 2021-06-15 21:39:06.000000 the thing is after using the formatted code the result is this: 2021-06-15 21:39:06 but after inserting it, it added .000000 in the end. Does it have to do with DateTimeField itself? I just rerun it just now and I see this warning: RuntimeWarning: DateTimeField AttendanceTbl. start_date received a naive datetime (2021-06-15 21:47:55) while time zone support is active. warnings.warn("DateTimeField %s received a naive datetime (%s)" -
Looping over a queryset based on queryset
I am trying to get data from queryset(Answers) based on values from a queryset(Modules) and adding them finally into a list and sending to front to plot on different graphs. Models.py class Answers(models.Model): _id = models.AutoField(primary_key=True) question = models.ForeignKey(Questions, db_column="question", on_delete=models.SET_NULL, null=True) # points= models.IntegerField(null=True, blank=True) points = models.CharField(max_length = 100 ,choices= asssess_choice, null=True) student = models.ForeignKey(Students, on_delete= DO_NOTHING,) def __str__(self): return str(self.question) class Modules(models.Model): md_id = models.AutoField(primary_key=True) mod_name = models.CharField(max_length=100) # student = models.ForeignKey(Students, on_delete= DO_NOTHING) # percentage = models.FloatField(default="0.00") def __str__(self): return self.mod_name views.py def studentView(request, studentid=None): context = {} cant_assess = 0 yes = 0 no = 0 somewhat_assess = 0 module_query = Modules.objects.values() # print(module_query) # Running a loop based on query and running next query # for module in module_query: # # print (module['md_id']) query = Answers.objects.values().filter(student = studentid) query2 = query.filter(question__modules = [item['md_id'] for item in module_query]) print(query2) for i in query: if i['points'] == 'No': no = no + 1 if i['points'] == 'somewhat': somewhat_assess = somewhat_assess + 1 if i['points'] == 'cannot': cant_assess = cant_assess + 1 if i['points'] == 'Yes': yes = yes + 1 label = [] data = [] data.append(yes) data.append(no) data.append(somewhat_assess) data.append(cant_assess) label.append('Yes') label.append('No') label.append('Somewhat Assess') label.append('cant Assess') … -
Firebase JWT to django credential login
it is possible to login a user from firebase jwt to django if so, what is the tools needed to login a user? Thanks -
Django REST Serializer not getting data from request
I have the following serializer setup to take in a postcode and return a list of service objects: class ServiceSearchSerializer(Serializer): area = CharField(max_length=16) services = DictField(child=JSONField(), read_only=True) def validate_area(self, value): if re.match('^[A-Z]{1,2}[0-9][A-Z0-9]? ?([0-9][A-Z]{2})?$', value) is None: raise ValidationError("This is not a valid postcode.") And I tried to use this to create an API endpoint which out take in the area. class ServiceSearchAPI(GenericAPIView): serializer_class = ServiceSearchSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(raise_exception=True): area = serializer.data['area'] return Response(area) However, when trying to get the area from the serializer, it returns None. But the value for request.data['area'] is correct. Does anyone know why this is happening? -
Prevent Django from localizing numbers in templates
I have a Django template and am using localization by loading the packages and applying translate like this: {% load i18n %} {% load l10n %} .... {% translate "Menu" %} At some point I have a visual element where I provide the CSS width as a float variable from the view. Now when I change the language from en-us to de (German), the dot in the float is replaced with a comma and the value is not valid CSS anymore. This is the element: <div class="progress-header progress-el" style="width: {{p.max_width}}%"></div> I am aware of this question: How to prevent Django from localizing IDs in templates? And I have tried enclosing the relevant element in these tags: {% localize off %} <div class="progress-header progress-el" style="width: {{p.max_width}}%"></div> {% endlocalize %} As well as applying filters: <div class="progress-header progress-el" style="width: {{p.max_width|unlocalize}}%"></div> And: <div class="progress-header progress-el" style="width: {{p.max_width|safe}}%"></div> No success so far - any suggestions? -
Django - when 1 user accesses the same view with different url kwargs - why am I getting cross over of data?
I have a django app that contains samples. On my home page, it displays a table with many samples, containing hyperlinks to the 'Sample page' - which is a view get request. When I click on several of these samples in tandem, to open new tabs, each to a specific tab - I am getting cross over of data - I.e the url sample_id kwargs is different, but the page is displaying the same results which is incorrect. When i refresh the page, the correct sample data appears. Is there any way around this happening is a user is to open several different sample tabs at the same time? This would impact on results and could cause errors in the workflow offered by the django app. *is this because my view is processing too much, so the different view request=s ends up over lapping ? -
How to convert function based views to class based views in Django RestFramework?
I am a beginner learning the Django RestFramework. I had created this for an blog post page for my project. I looked through different tutorials and posts but couldn't really figure out. Can you help me converting this functional view into a class view? Thanks from django.http.response import JsonResponse from django.shortcuts import render from django.http import JsonResponse from rest_framework import serializers from rest_framework.decorators import api_view from rest_framework.response import Response from .serializers import PostSerializer from .models import Post,categories # Create your views here. @api_view(['GET']) def apiOverview(request): api_urls={ 'List':'/article-list/', 'Detail View':'/article-detail/<str:pk>/', 'Create':'/article-create/', 'Update':'article-update/<str:pk>/', 'Delete':'/article-delete/<str:pk>/', } return Response(api_urls) @api_view(['GET']) def articleList(request): articles=Post.objects.all() serializers=PostSerializer(articles,many=True) return Response(serializers.data) @api_view(['GET']) def articleDetail(request,pk): articles=Post.objects.get(id=pk) serializers=PostSerializer(articles,many=False) return Response(serializers.data) @api_view(['POST']) def articleCreate(request): serializers=PostSerializer(data=request.data) if serializers.is_valid(): serializers.save() return Response(serializers.data) @api_view(['POST']) def articleUpdate(request,pk): articles=Post.objects.get(id=pk) serializers=PostSerializer(instance=articles,data=request.data) if serializers.is_valid(): serializers.save() return Response(serializers.data) @api_view(['DELETE']) def articleDelete(request, pk): articles=Post.objects.get(id=pk) articles.delete() return Response('The item has been deleted') -
Django Custom Template Filter - How To Mention Users And Categories
I am making a social networking site, and I want to be able to mention users or categories by using the # symbol. (Example: #User #Category #Other Category). Using a template filter, I want to first find all the # in the string, and then get the word after it. Then I would check in the models for categories: class Category(models.Model): name = models.CharField(max_length=250, unique=True) category_detail = models.TextField(max_length=1250, default='No information is known on this category.') created_date = models.DateTimeField(default=timezone.now) follow_count = models.IntegerField(default=0) followers = models.ManyToManyField(User, related_name='followers') And if it does not match a category I would check if the word after the # is a user. If It is a category, I want to link it using the <a> tag, and if it is a user I also want to link it using the <a> tag. The urls: urlpatterns = [ path('u/@<str:username>', UserPostListView.as_view(), name='user-posts'), # User Profile Link. Link This If After The # The Word Is A User path('c/<str:cats>/', views.category_view, name='category-detail'), # View Category Link. Link This If After The # The Word Is A Category ] Usage: Going back to the example, let's say I have a comment like this: This is such a great post! #some_user #category #other_category … -
Django Cassandra Engine with AWS Keyspace
I am trying to set a django app and connect it to aws keyspace. Trying to do it using django-cassandra-engine Can someone help me with entry for database in settings.py. -
How to add M2M data directly to form in Django
I have a form field which gets added through a Mixin. This field is not saved in the database. Instead, I need to take this field and convert it to a field in the form that will be saved in the database. The field in the database is named receiver: receiver = models.ManyToManyField(EmployeeType, related_name='policies_receiver') Instead of the user selecting the receivers, I would like them to use this new form field which has been added to the form via Mixin: class SelectEmployeeTypeFormMixin(forms.Form): """ Adds a "select_employee_type" radio field to a form. If checked, the appropriate employee types/roles will be applied to the object. """ CHOICES = ( ('this_department', 'Employees in my department.'), ('company_wide', 'All employees in this company.'), ) select_employee_type = forms.ChoiceField( widget=forms.RadioSelect(), choices=CHOICES, initial='this_department', label='Who is this for?' ) The select_employee_type form value needs to be converted to the receiver field in the view. I have done this by saving the form then updating the receiver in the form as such: updated_request = request.POST.copy() if policies_form.is_valid(): if request.user.role.supervisor is None or request.user is policies_form.sender: policies_form.save() if updated_request['select_employee_type'] == 'this_department': subs_id = request.user.subordinates.values_list('role', flat=True) sub_roles = EmployeeType.objects.filter(Q(pk__in=subs_id) | Q(pk=request.user.role.id)) policies_form.instance.receiver.set(sub_roles) policies_form.save() The problem I am having is that I use … -
Form is not being saved in Django admin page
I have faced a problem in my Django project where my form is not being saved as a new listing in my model(listing) and is not even showing on Django's admin page. my models.py : class listing(models.Model): title = models.CharField(max_length=64) describtion = models.CharField(max_length=300) bid = models.FloatField() category = models.ForeignKey(categories, default=1, verbose_name="Category", on_delete=models.SET_DEFAULT) user = models.ForeignKey(User,default='', verbose_name="User", on_delete=models.SET_DEFAULT) image = models.CharField(max_length=400) def __str__(self): return f"{self.title} " create a new listing form : class create(ModelForm): class Meta: model = listing fields = [ 'title', 'describtion','bid','category','image'] views.py : def CreateListing(request): user = request.user if request.method == "POST": form = create(request.POST, instance=user) if form.is_valid(): new_listing = form.save() new_listing.user = request.user new_listing.save() return render(request, "auctions/listing.html") else: return render(request, "auctions/Create.html",{ "form": create }) Ps: I have no problem with my urls.py -
docker-compose up --build states an error but it works after i use docker-compose up what is the problem which gives me the error
First i use docker-compose up --build and this is what i get: Building django_gunicorn Sending build context to Docker daemon 19.46kB Step 1/8 : FROM python:3.8.5-alpine ---> 0f03316d4a27 Step 2/8 : RUN pip install --upgrade pip ---> Using cache ---> ac5d6a64af93 Step 3/8 : COPY ./requirements.txt . ---> Using cache ---> 8dfb848be8a4 Step 4/8 : RUN pip install -r requirements.txt ---> Using cache ---> 0dee442b9c0a Step 5/8 : COPY ./ddc /app ---> 21c33e5463d8 Step 6/8 : WORKDIR /app ---> Running in 9153438d9466 Removing intermediate container 9153438d9466 ---> d27b60805a1b Step 7/8 : COPY ./entrypoint.sh / ---> e497fecdfb76 Step 8/8 : ENTRYPOINT ["sh", "/entrypoint.sh"] ---> Running in f6eb59759a71 Removing intermediate container f6eb59759a71 ---> 6db361baa8e8 Successfully built 6db361baa8e8 Successfully tagged django-docker-compose_django_gunicorn:latest Traceback (most recent call last): File "docker-compose", line 3, in <module> File "compose/cli/main.py", line 81, in main File "compose/cli/main.py", line 203, in perform_command File "compose/metrics/decorator.py", line 18, in wrapper File "compose/cli/main.py", line 1186, in up File "compose/cli/main.py", line 1182, in up File "compose/project.py", line 664, in up File "compose/service.py", line 348, in ensure_image_exists File "compose/service.py", line 1133, in build File "compose/service.py", line 1948, in build FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmp5cv0a52z' [22049] Failed to execute script docker-compose After that … -
how to make username unique only amongst active users
I want to make sure that the username field is unique, but only amongst active users. If an user is inactive, then their username can be used to create a new account. Is this possible in django? I am using MySQL by the way. I have read about a conditional unique constraint, but it only works on postgres. https://docs.djangoproject.com/en/3.2/ref/models/constraints/#condition -
I do not receive a message by mail when registering
I want to register by mail, I did everything according to this guide, only the setting.py is slightly different, I will show it below https://studygyaan.com/django/how-to-signup-user-and-send-confirmation-email-in-django The inspector does not show any red errors, for some reason the message does not come to the mail and registration takes place without confirmation of the mail setting.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' MAILER_EMAIL_BACKEND = EMAIL_BACKEND EMAIL_HOST = 'smtp.mail.com' EMAIL_HOST_PASSWORD = 'mypassfromemail' EMAIL_HOST_USER = 'myemail@mail.ru' EMAIL_PORT = 465 EMAIL_USE_SSL = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER models.py import kwargs as kwargs from django.db import models from django.urls import reverse from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from datetime import datetime, date from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() class Post(models.Model): published = None title = models.CharField(max_length=200) author = models.ForeignKey('auth.User', on_delete=models.CASCADE,) body = models.TextField() header_image = models.ImageField(blank=True, null=True, upload_to="images/") post_date = models.DateField(auto_now_add=True) category = models.CharField(max_length=255, default='coding') def __str__(self): return self.title + '|' + str(self.author) def get_absolute_url(self): #return reverse('post_detail', args=[str(self.id)]) return reverse('home') class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE) name = models.CharField(max_length=255) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): … -
Django login not changing URL
need help. I am using simple Django URL to log in user and send to a required page, but as user sign in URL does not change. Views.py from django.contrib.auth import authenticate, login def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return render(request, 'required.html') The URL does not change it remains http://127.0.0.1:8000/myApp/login/ Please suggest how to change the URL. -
Is the model definition correct in django
I have defined below models in my models.py file. I am trying to populate Allocation table only for the rows where member is null. from django.db import models from django.contrib.auth.models import User # Create your models here. class Member(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) DESIGNATION = [ ('Developer', 'Developer'), ('Tester', 'Tester'), ('Support', 'Support'), ] name = models.CharField(max_length=200, null=True) role = models.CharField(max_length=100, null=True, choices=DESIGNATION) email = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name class Task(models.Model): CATEGORY = [ ( 'Low', 'Low'), ('Medium', 'Medium'), ('Urgent', 'Urgent'), ] STATUS = [ ('Not Started', 'Not Started'), ('In Progress', 'In Progress'), ('Completed', 'Completed'), ] name = models.CharField(max_length=200, null=True) category = models.CharField(max_length=200, null=True, choices=CATEGORY) description = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) member = models.ForeignKey('Member', null=True, on_delete=models.CASCADE) task_status = models.CharField(max_length=200, null=True, choices=STATUS) def __str__(self): return self.name class Allocation(models.Model): member = models.ForeignKey('Member', null=True, on_delete=models.CASCADE) task = models.OneToOneField('Task', null=True, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.task.name And here is my view for task allocation def allocate_task(request, pk): task_details = Task.objects.get(id=pk) form = TaskAllocateForm(instance=task_details) if request.method == 'POST': form = TaskAllocateForm(request.POST, instance=task_details) if form.is_valid(): form.save() return redirect('/') I am creating new tasks with create method which is working fine. And I am trying to … -
How to convert nepali date to english date in drf [closed]
I am getting a problem in converting the Nepali date which I get from the user as input data to English date as output. Here in this code user pass month as user data and I got the Nepali date as output. But I expect to get output as an English date.This is View and the code is here: This is the view code: import datetime import pandas as pd from django.http import JsonResponse from nepali_datetime import REFERENCE_DATE_AD from api.utils.helpers import get_active_session import csv import nepali_datetime def get_first_last_date_month(request): """ function to receive the nepali month and return first and last date of that month """ month = request.GET.get("month") year = nepali_datetime.date.today().year with open("project/month_days.csv") as csvfile: reader = csv.DictReader(csvfile) if month: nep_year = nepali_datetime.date(year, int(month), 1) print(nep_year) no_of_days = [ row.get(str(nep_year.strftime("%B"))) for row in reader if row["Year"] == str(nep_year.year) ] print(no_of_days) if int(no_of_days[0]) > 0: nep_dates = [ str(nepali_datetime.date(nep_year.year, nep_year.month, i)) for i in range(1, int(no_of_days[0]) + 1) ] print(nep_dates) english_dates = str(nep_dates.to_english_date()) print(english_dates) return JsonResponse({"dates": english_dates}) This is the expected output: "dates": [ "2021-01-01", "2021-01-02", "2021-01-03", "2021-01-04", "2021-01-05", "2021-01-06", ] But I got this: "dates": [ "2078-01-01", "2078-01-02", "2078-01-03", "2078-01-04", "2078-01-05", "2078-01-06", "2078-01-07", "2078-01-08", "2078-01-09", "2078-01-10", "2078-01-11", "2078-01-12", "2078-01-13", "2078-01-14", … -
How to create Django project using windows os
I have tried using ...> django-admin startproject mysite but it showed '...' is not recognized as an internal or external command, operable program or batch file. what should I do -
how to display value as radio button using widget_tweaks
I facing a problem in displaying the stored “gender” value as a radio button in a template. I am using widget_tweaks, and this template will allow user to update and save data. To illustrate this problem I have the following: Model: class Student(models.Model): fname = models.CharField(max_length=50) lname = models.CharField(max_length= 50) gender = models.CharField(max_length= 1) # in the database it is either M or F def __str__(self): return '{} {} '.format( self.fname, self.lname) Form: class studentForm(forms.ModelForm): class Meta: model = Student fields = ( 'fname', 'lname', 'gender', ) labels = { 'fname': ('First name'), 'lname':( 'Last name'), 'gender': ( 'Gender'), } def __init__(self, *args, **kwargs): super(studentForm, self).__init__(*args, **kwargs) View: def studentDetails(request,id): oneStudent = get_object_or_404(Student,id=id) oneStudentForm = studentForm( instance= oneStudent) context = { "form":oneStudentForm } return render(request,"students/studentDetails.html",context) and I tried to show Gender in the HTML as the following, but the problem is that condition always False!!: <form method="POST" > {% csrf_token %} <div class="row"> <div class="form-group col-md-3"> <label for="{{ field.id_for_label }}" >{{ form.fname.label }}</label> {% render_field form.fname %} </div> <div class="form-group col-md-3"> <label for="{{ field.id_for_label }}">{{ form.lname.label }}</label> {% render_field form.lname class="form-control req" %} </div> </div> <div class=" col-md-3 mt-3" > {{form.gender}} <!-- this for debugging, to ensure the the value …