Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
running php file with pycharm and redis server
I am working on a django project which requires to run 2 php files. One of the file must have access to the redis database that I configured in docker-compose file. So, how do I run these php files and map redis database. I am using ubuntu os. Any Ideas? Thanks :) -
How can I allow access to my Django web server to someone on the same VPN network?
I have a Django app that I'm running with python manage.py runserver 0.0.0.0:8000 I'm also connected to a corporate VPN for work. I can access this app by going to localhost:8000/admin or 192.x.x.x:8000/admin in my browser, that's fine. What I want to do is provide access to this Django app to my coworker, who is connected to the same VPN as me. How can I do this? EDIT: also want to note I have the django settings file with DEBUG = False ALLOWED_HOSTS = ['*'] -
Display SQL table with primary key pair in Django admin
How can I display an SQL table that has a primary key pair as an unmanaged table in Django admin? More details: I have a Django project running in docker that is sharing a Postgresql DB with another program in another docker container. I want to use Django Admin to display all database tables, including the ones that were created outside of Django. This works fine using the Meta "db_table" and "managed" attributes. However, when I have an SQL table with two primary keys, Django admin gives me an error: column user_settings.id does not exist These are the tables: SQL: CREATE TABLE user_settings( user_id INT, setting_id INT, value INT, PRIMARY KEY (user_id, setting_id) ); Django: class UserSettings(models.Model): user_id = models.IntegerField() setting_id = models.IntegerField() value = models.IntegerField() class Meta: managed = False db_table = 'user_settings' -
Error with setting up minIO in docker-compose: <ERROR> Unable to initialize new alias from the provided credentials
I have trouble with setting up minIO in my docker-compose. I found this problem on several websites and tried to make it work. But I failed :D Anyway, if anyone is able to help me I will call him my personal hero. Here is my code: # docker-compose.yml minio: container_name: minio image: minio/minio ports: - "9000:9000" volumes: - ./minio-data:/data env_file: - app/.env command: server /minio-data mc: image: minio/mc depends_on: - minio entrypoint: > /bin/sh -c " until (/usr/bin/mc config host add myminio http://minio:9000 access-key secret-key) do echo '...waiting...' && sleep 1; done; /usr/bin/mc mb myminio/local-bucket/; /usr/bin/mc policy set download myminio/local-bucket; exit 0; " # settings.py DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = env.str("MINIO_ACCESS_KEY", default='access-key') AWS_SECRET_ACCESS_KEY = env.str("MINIO_SECRET_KEY", default='secret-key') AWS_STORAGE_BUCKET_NAME = env.str("AWS_STORAGE_BUCKET_NAME", default='local-bucket') MINIO_STORAGE_USE_HTTPS = False if DEBUG: AWS_S3_ENDPOINT_URL = env.str("AWS_S3_ENDPOINT_URL", default='http://minio:9000') # .env MINIO_ACCESS_KEY=access-key MINIO_SECRET_KEY=secret-key AWS_STORAGE_BUCKET_NAME=local-bucket AWS_S3_ENDPOINT_URL=http://minio:9000 And thats my console logs: -
Django manual forms
I am trying to get my head around using manual forms. When I have in my forms.py checked that fields name and email is readonly class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['name', 'email', 'body'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['name'].widget.attrs['readonly'] = True self.fields['email'].widget.attrs['readonly'] = True And in the html <form action="." method="post"> {% csrf_token %} <div class="comment-area hide" id="comment-area"> <div class="mb-4"> <label for="{{ form.name.id_for_label }}" class="form-label">{{ form.name.label }}: </label> <input class="input is-medium" name="{{ form.name.html_name }}" type="text" class="form-control" id="{{ form.name.id_for_label }}" placeholder="{{ request.user.username }}" readonly> </div> <div class="mb-4"> <label for="{{ form.email.id_for_label }}" class="form-label">{{ form.email.label }}: </label> <input class="input is-medium" name="{{ form.email.html_name }}" type="email" class="form-control" id="{{ form.email.id_for_label }}" placeholder="{{ request.user.email }}" readonly> </div> <div class="mb-4"> <label for="{{ form.body.id_for_label }}" class="form-label">{{ form.body.label }}: </label> <textarea class="textarea is-small" name="{{ form.body.html_name }}" class="form-control" id="{{ form.body.id_for_label }}"> </textarea> </div> <div class="field"> <div class="control"> <button class="button is-success">Submit comment</button> </div> </div> </div> </form> But still when submitting without name and email, got error on missing both name and email. If anyone can help, much appreciated -
Database error in django+mongodb objects.fiter with boolean field
I am using djongo library to handle mongodb, but still getting database error while filtering queryset using a boolean field. Error: No exception message supplied, django.db.utils.DatabaseError from django.contrib.auth import get_user_model User = get_user_model() users = User.objects.filter(isVerified=True) -
How to create a Django dropdown form using forms.py without a model?
I need to create a simple presentation filter for a Django webpage. Since it's discarded without need for storage, I do not need to use Model overhead. Here is my relevant views.py code: @login_required() def cards(request): # form = CountryForm() f_name = STAT_FILES / 'csv/segment_summary_quart.csv' # pathname = os.path.abspath(os.path.dirname(__file__)) df = pd.read_csv(f_name, index_col=None) pl_name = STAT_FILES / 'pickles/lbounds' pu_name = STAT_FILES / 'pickles/ubounds' lbounds = pickle.load(open(pl_name, "rb")) ubounds = pickle.load(open(pu_name, "rb")) filter_name = [] i = 0 max_i = len(ubounds) while i < max_i: filter_name.append(f'Personal best trophy range: {str(int(lbounds[i])).rjust(4," ")}-{str(int(ubounds[i])).rjust(4," ")}') i += 1 sort_name = [] sort_name.append("Alphabetic Order") sort_name.append("Most Popular") sort_name.append("Least Popular") sort_name.append("Highest Win Rate") sort_name.append("Lowest Win Rate") form = cardStatsForm(filter_name, sort_name) Given that my values may change dynamically, I am trying to establish the cardStatsForm() object without initially knowing the values that will occur when publishing the page to the end user. The following code resides within forms.py: from django import forms class cardStatsForm(forms.Form): def __init__(self, filter_opts, sortOrder, *args, **kwargs): super(cardStatsForm, self).__init__(*args, **kwargs) self.fields['filts'].choices = filter_opts self.fields['sorts'].choices = sortOrder filts = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=(), required=True) sorts = forms.Select(choices=()) Unfortunately I haven't had to worry about the html side yet since I keep getting the following error with respect to … -
Getting Field 'None' expected a number but got 'update'. when using UpdateView in Django
I am using UpdateView for my update page, but I get this error: Field 'None' expected a number but got 'update'. my urls.py looks like this: path('post/<pk>/update/', PostUpdateView.as_view(), name='post_update'), Everything works fine if I change my update URL to anything other than "post". For example, this works fine: path('abcxyz/<pk>/update/', PostUpdateView.as_view(), name='post_update'), I would like to use the word "post" in URL, because i also use it in the other URLs and they work just fine (except for delete view, which gives me the same error). Is there any way to fix this error without changing the URL? Note: It has worked before, but it broke at some point when I was trying to use django-PWA. I'm not sure if this is related though. Thank you for your help! -
numpy warning with django 4 - 'numpy.float64'> type is zero
I just updated numpy and I get the following warning with Django. How can I fix it? /usr/local/lib/python3.9/site-packages/numpy/core/getlimits.py:89: UserWarning: The value of the smallest subnormal for <class 'numpy.float64'> type is zero. -
Django CustomUser Model - Email Adress already taken
I tried to do a CustomUser Manager in Django. When i try to login or register a new user with my form I always get errors like: "Email adress already taken" or "Passwords don't match". I tried different solutions here, but nothing worked for me so far. I'm new to coding so please don't judge me :) models.py from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser, PermissionsMixin ) class MyUserManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError('Users must have an email address') email = self.normalize_email(email) user = self.model(email=email) user.set_password(password) user.save() return user def create_superuser(self, email, password=None): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email, password=password, ) user.is_staff = True user.save() return user class NewUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('Email Adresse'), unique=True) user_name = models.CharField(max_length=20, unique=True) first_name = models.CharField(max_length=30, blank=False) last_name = models.CharField(max_length=50, blank=False) birthdate = models.DateField(null=True, blank=False) start_date = models.DateTimeField(default=timezone.now) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) sex = models.CharField(max_length=1, default='K', choices=Sex.SEX_CHOICES,) vacc = models.CharField(max_length=1, default='K', choices=Vacc.VACC_CHOICES,) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email I always get the error: "Email … -
Best way to design API with Django rest framework working asynchronously
I want to build an API that will get called by different bots to do a variety of stuff. Since I already know that my main API will get a lot of requests, I want it to be asynchronously. I saw that we can use asyncio with django rest framework but is it a good idea ? Is there another way or maybe I should use Flask ? I'm fairly new to the API world so thanks in advance ! PS: I've already started working on it but I'm having a hard time finding how I can make my "post" function async -
Django 4.0 and celery no such file or directory
I updated Django to 4.0 and now I get the following error, can someone please help. The celery version is 5.2.1 The error I get is Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/celery/result.py", line 329, in throw self.on_ready.throw(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/vine/promises.py", line 234, in throw reraise(type(exc), exc, tb) File "/usr/local/lib/python3.10/site-packages/vine/utils.py", line 30, in reraise raise value FileNotFoundError: [Errno 2] No such file or directory [06/Jan/2022 18:15:54] "GET /api/task/37e0fe4d-d149-42c3-81e6-7549d294b3fe/ HTTP/1.1" 500 16113 -
upgrading bootstrap changed form styling
I have Django forms with crispy forms. I upgraded from bootstrap 4.0 to the latest version 5.1.3. I correct most of the changes but I cant figure out why the form styling has changed. You can see the spacing between the form fields has greatly changed. How do I go about correcting this to look like bootstrap 4.0 code: <div class="loginout-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Log In</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="login-register-btn" type="submit">Login</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Need An Account? <a class="ml-2" href="{% url 'register' %}">Sign Up Now</a> </small> <div class="inline"> <small class="text-muted"> Forgot Password? <a class="ml-2" href="{% url 'reset_password' %}">Reset Password</a> </small> </div> </div> </div> -
Can't get JSON data on console
Trying to console.log the data before rendering it on page but I keep getting 404 not found or not attributeName 'Porfile' don't have username as an attribute. I'm a noob when it comes to JSON, I've only started messing around with it recently, please help it's for an assignment JS: $.ajax({ type: 'GET', url: 'my-profile-json/', success: function(response){ console.log(response); }, error: function(error){ console.log(error); } }); Urls: from django.urls import path from django.conf import settings from django.conf.urls.static import static from . import views from .views import ( post_view_json, profile_test_view, MyProfileView, MyProfileData, ) urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("test", profile_test_view, name="test"), path("my/", MyProfileView.as_view(), name="my-profile-view"), path("my-profile-json/", MyProfileData.as_view(), name="my-profile-json"), # endpoints path("posts-json/", post_view_json, name="posts-view-json") ] Views from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.http.response import JsonResponse from django.shortcuts import render from django.urls import reverse from django.core import serializers from .models import User, Post, Profile from django.views.generic import TemplateView, View class MyProfileData(View): def get(self, *args, **kwargs): profile = Profile.objects.get(user=self.request.user) qs = profile.get_proposals_for_following() profiles_to_follow_list = [] for user in qs: p = Profile.objects.get(user__username=user.username) profile_item = { 'id': p.id, 'user': p.username, 'avatar': p.avatar.url, } profiles_to_follow_list.append(profile_item) return JsonResponse({'pf_data': profiles_to_follow_list}) class … -
Django Pandas Dataframe with display with neasted list
i still newbie on django, i would like this ask the table how to create pandas with pivot table with neasted list. data_list = [{'id': '1', 'date':2022-1-10 'car': 'toyota', 'car_material': {'ST1230': {'name': 'Steel', 'qty': 13}, 'MT1239': {'name': 'PVC', 'qty': 8}}}] pivot = pd.DataFrame(data_list) OutPut | id | date | car | car_material | |----|-----------|--------|--------------------------------------------------------------------------------| | 1 | 2022-1-10 | toyota | {'ST1230': {'name': 'Steel', 'qty': 13}, 'MT1239': {'name': 'PVC', 'qty': 8}}} | How to make it like this ? Final Result Output | id | date | car | car_material | name | qty | |----|-----------|--------|--------------|-------|-----| | 1 | 2022-1-10 | toyota | | | | | | | | ST1230 | stell | 13 | | | | | Mt1239 | PVC | 13 | -
Why is the django for loop not working, help would be appreciated
I passed my html templates that are in the templates directory to the functions to render, but they didn't. `def home(request): context = {"classes": classes} return render(request, 'home.html', context) def classes(request): context = {"classes": classes} return render(request, 'classes.html', context)` Here is one of the template files: `<!DOCTYPE html> {% for class_ in classes %} <div> <h3>Enter <a href='classes.html/'>{{class_.name}}</a></h3> </div> {% endfor %}` I know nothing is wrong with anything except the for loop, because I tried it without the loop and it worked. What did do wrong? -
Send message using Django Channels outside the Consumer Class WITHOUT channel layer
I have the problem described in this answer... Send message using Django Channels from outside Consumer class BUT this answer doesn't work in my case because, I don't want or need to use channel layers because my websocket is 1:1, ie limited to asynchronously notifying a single connected web client app of updates, not broadcasting to a channel layer. How can I send a message outside the Consumer class without using a channel layer? (The solution as described errors on [Consumer] has no attribute 'add_group'. class Monitor(WebsocketConsumer): def connect(self): self.accept() async_to_sync(self.add_group)('monitor_group') Am I confused? Is there no way around using channel_layers and a backing store like Redis even if one is only attempting to avoid long-polling for the status of a long-running backend task? -
Django template tags don't show HTML template correctly
I have an HTML template that I want code with django in back-end to develop my site. I have trouble with django template tags. when I use them, such as {% for %} the website template output is corrupted and don't show code of models.py and views.py. home_page.html: <section> <div class="gap100 no-top overlap-75"> <div class="container"> <div class="servic-category"> <div class="row merged"> <div class="col-lg-3"> {% for object in object_list %} <div class="category-box {{ forloop.first|yesno:"selected," }}"> <i class="fa fa-google-wallet"></i> <h2>{{ training_course.title }}</h2> <p>{{ training_course.title }}</p> <a href="#" class="main-btn" title="">ادامه مطلب</a> </div> {% endfor %} </div> </div> </div> </div> </div> </section><!-- services section --> views.py : from django.shortcuts import render from training_courses import TrainingCourses def home_page(request): training_courses = TrainingCourses.objects.all() context = { 'training_courses': training_courses } return render(request, 'home_page.html', context) models.py: from django.db import models # Create your models here. class TrainingCourses (models.Model): title=models.CharField(max_length=150, verbose_name= 'عنوان') description=models.TextField(verbose_name='توضیحات') link=models.URLField(max_length=100, verbose_name='آدرس') class Meta: verbose_name='برنامه آموزشی' verbose_name_plural='برنامه های آموزشی' def __str__(self): return self.title -
Django, DRF: How do I use pagination in raw SQL queries?
I'd like to use the following raw query in a ListAPIView in the Django REST Framework. I'm not sure how to use a raw SQL query instead of a queryset to support pagination. I've looked into it and didn't find much that made sense to me. If I want to use a query set, it would look like this How do I do this if I want to use raw SQL queries? class VideoListView(generics.ListAPIView): queryset = Video.objects.all() serializer_class = VideoSerializer SELECT DISTINCT "t"."id", "t"."title", "t"."thumbnail_url", "t"."preview_url", "t"."embed_url", "t"."duration", "t"."views", "t"."is_public", "t"."published_at", "t"."created_at", "t"."updated_at", EXISTS (SELECT (1) AS "a" FROM "videos_history" U0 WHERE (U0."user_id" IS NULL AND U0."video_id" = "t"."id") LIMIT 1) AS "is_viewed", EXISTS (SELECT (1) AS "a" FROM "videos_favorite" U0 WHERE (U0."user_id" IS NULL AND U0."video_id" = "t"."id") LIMIT 1) AS "is_favorited", EXISTS (SELECT (1) AS "a" FROM "videos_track" U0 INNER JOIN "videos_playlist" U1 ON (U0."playlist_id" = U1."id") WHERE (U1."is_wl" AND U1."user_id" IS NULL AND U0."video_id" = "t"."id") LIMIT 1) AS "is_wl" FROM ( (SELECT "videos_video".* FROM "videos_video" WHERE ("videos_video"."is_public" AND "videos_video"."published_at" <= '2022-01-03 05:20:16.725884+00:00' AND "videos_video"."title" LIKE '%word') ORDER BY "videos_video"."published_at" DESC LIMIT 20) UNION (SELECT "videos_video".* FROM "videos_video" LEFT OUTER JOIN "videos_video_tags" ON ("videos_video"."id" = "videos_video_tags"."video_id") LEFT … -
Cannot start service api: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "python manage.py runserver
I would like to running docker-compose. during running react and django application, docker-compose returns the following error: (base) dominik@Precision:~/PycharmProjects/humanet-docker$ ls api docker-compose.prod.yml docker-compose.yml front nginx (base) dominik@Precision:~/PycharmProjects/humanet-docker$ docker-compose ps Name Command State Ports ------------------------------------------------------------------------------------------------------------------------------------------------------ a7c8de30f648_humanet-docker_api_1 python manage.py runserver ... Exit 127 humanet-docker_db_1 docker-entrypoint.sh postgres Up 5432/tcp humanet-docker_front_1 docker-entrypoint.sh yarn ... Up 0.0.0.0:3000->3000/tcp,:::3000->3000/tcp humanet-docker_nginx_1 /docker-entrypoint.sh ngin ... Up 0.0.0.0:443->443/tcp,:::443->443/tcp, 0.0.0.0:80->80/tcp,:::80->80/tcp humanet-docker_pgadmin_1 /entrypoint.sh Up 443/tcp, 0.0.0.0:5050->80/tcp,:::5050->80/tcp (base) dominik@Precision:~/PycharmProjects/humanet-docker$ docker-compose up humanet-docker_pgadmin_1 is up-to-date humanet-docker_front_1 is up-to-date Starting a7c8de30f648_humanet-docker_api_1 ... humanet-docker_nginx_1 is up-to-date Starting a7c8de30f648_humanet-docker_api_1 ... error ERROR: for a7c8de30f648_humanet-docker_api_1 Cannot start service api: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "python manage.py runserver 0.0.0.0:8000": executable file not found in $PATH: unknown ERROR: for api Cannot start service api: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "python manage.py runserver 0.0.0.0:8000": executable file not found in $PATH: unknown ERROR: Encountered errors while bringing up the project. (base) dominik@Precision:~/PycharmProjects/humanet-docker$ below docker-compose.yml file from my docker version: "3.3" services: front: build: ./front working_dir: /home/dominik/node env_file: ./front/.env.dist volumes: - ./front:/home/dominik/node - /private/etc/ssl:/etc/ssl ports: - 3000:3000 restart: always tty: true api: build: ./api working_dir: /home/dominik/python command: pip install -r requirements.txt && python manage.py runserver 0.0.0.0:8000 volumes: - ./api:/home/dominik/python - /private/etc/ssl:/etc/ssl ports: - … -
how to make django work on debian 11? – python error: KeyFile: 'django'
a few monthes ago, i installed mailman3 on clean installed debian 10 vm, with success – the server was working for long time and distributed hundreds of mails without any issues. The tutorial i implemented completely is that one announced by GNU Mailman itself. After regular debian system upgrade process from 10 to 11 (didn't ever added external package sources, so it was really easy) i tried starting mailman 3 again. Everything works, except the django web framework – that one controlled by qcluster.service. The problem seems to be within executing /opt/mailman/mm/bin/django-admin migrate; the output is as follows (journalctl -u qcluster.service contains the same lines): Traceback (most recent call last): File "/opt/mailman/mm/venv/lib/python3.9/site-packages/django/template/utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/mailman/mm/venv/lib/python3.9/site-packages/django/template/backends/django.py", line 121, in get_package_libraries module = import_module(entry[1]) File "/usr/local/lib/python3.9/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 "/opt/mailman/mm/venv/lib/python3.9/site-packages/hyperkitty/templatetags/decorate.py", line 4, in … -
How can i install text editor in django frontend in my case django summernote
I need to install an editor in the frontend like the image below, I am using react and Django. Please help me it is really hard to find. -
Not able to access media file even if file exists when checked manually
I have a media file that Django isn't able to access, even if it definitely exists if I enter its URL in the browser. Info Language: Python [v.3.9.7] Platform: Django [v.3.2.8] Goal Being able to access the media file Description The thing is, people can upload books on my website. People upload images of these books in different sizes, so I want to be able to handle all of them, so I access the width and height of the image and then use that as the size of the image in the view (CSS). To do that, I've used a custom filter image_size that is going to do all the work of accessing the image and finding its size, which I send back to the view: @register.filter def image_size(img, host): img = host[0] + "://" + host[1] + img with Image.open(img) as image: width, height = image.size dct = { "width": width, "height": height } return dct Here, host[0] is the protocol (request.scheme) of the URL of the image and host[1] is the host name (request.get_host()). Here's my view: def all_books(request): if request.user.is_authenticated: context = { "books": Book.objects.all(), "request": request, "user_profile": UserProfileInfo.objects.get(user=request.user), "mail_sent": False, } else: context = { "books": … -
rendering forms into HMTL using django-easy-select2
I am using django-easy-select2 to handle the entering of data into several manytomanyfields within a model - titled Engagement. I am using bootstrap and crispy forms to render the Engagement form to HTML. The rendering is broadly working as expected/required. However, the size of form fields for manytomany data are initially very small and require data to the selected/entered, before they expand. Once data is entered the fields do expand. But, I would like these fields to initially render as the size set by bootstrap. For example, I've set bootstrap as col-6, but the initial render of the manytomany is only col-1 or even less. When data is entered that field will expand up to col-6 and no further, which good, but I would like the field to start at col-6, even with no data. Relevant code is below. engagements.view: class EngagementCreateView(CreateView): model = Engagement form_class = select2_modelform(Engagement, attrs={'width': 'auto'}) # this sets the widths of the field template_name = "engagements/engagement_create.html" def form_valid(self, form): print(form.cleaned_data) return super().form_valid(form) create engagement template {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <h4>{% if form.instance.pk %}Edit engagement{% else %}Create new engagement{% endif%}</h4> <div class="form-group"> <form method="post" novalidate> {% csrf_token %} … -
How to Loop through enum in Django?
I have a model in Django class Order(models.Model): class Gender(models.IntegerChoices): Male = (1,), _("Male") Female = (2,), _("Female") I want to send male and female in context context["genders"] = Order.Gender I use that in template like this {% for gender in genders %} <p>{{ gender }}</p> {% endfor %} I want to show male and female in front