Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django modifying admin edit interface
So here is my admin.py class ContentPageAdmin(admin.ModelAdmin): fields = (("category", "listing_title1", "show_listing1"),) the category is ManyToMany fields, listing_title1 is CharField, and show_listing1 is a BooleanField. Now it will display all of them in one line, but I want to put the show_listing1 below the listing_title1. How can I do that? -
No module named 'django.conf.urls.defaults'
I upgraded from django 3.2.5 to django 4.0.4. I know that this 'django.conf.urls.defaults' must be deprecated. My problem is that I don't get this error in the development environment but when I push to production, it shows the error. Why is this so??? Also I tried to locate the file so that I can change that line of code to the correct one but could find it's location. It's giving me this path which I can't see how to get to (/workspace/.heroku/python/lib/python3.9/site-packages/django/conf/urls/__init__.py)) -
Error ModuleNotFoundError: No module named 'api'
My Python program is throwing the following error: ModuleNotFoundError: No module named 'api' How to remove the ModuleNotFoundError: No module named 'api' error? -
Comments DateTimeField() Django
I'm trying to build a comments section in my website, and I'm pretty much done, but I'm trying to display the time that it was posted, but it keeps displaying the wrong time. This is my code in my models.py Posts class: ''' date = models.DateTimeField(default=timezone.now) ''' I know that the database recognizes something is wrong because it shows me this message: but I don't know how to fix it. Can someone please help me? Thanks! -
Calculating income and expense by filtering according to the entered date
I have a date picker and I will calculate income and expense based on this date. I want to add a parameter named random_date to my function in view.py. I want the user to set the end date. The start time will be today's date. For example, if the user has selected June 1 as the date, I want to sum the income and expenses from today to June 1st. How can I do that? Here is my views.py file: import datetime from django.shortcuts import render from incomes.models import Income, Source from expenses.models import Expense, Category from .models import SummaryModel # Create your views here. def Summary(request): todays_date = datetime.date.today() six_months_later = todays_date + datetime.timedelta(days=180) all_expenses = Expense.objects.filter(owner=request.user, date__gte=todays_date, date__lte=six_months_later) all_incomes = Income.objects.filter(owner=request.user, date__gte=todays_date, date__lte=six_months_later) def get_amount(EorI): amount = 0 for item in EorI: amount += item.amount return amount final_rep = {'Net_Income' : get_amount(all_incomes) - get_amount(all_expenses)} return render(request, 'summary.html', final_rep) Here is my summary.html file: <div class="card"> <div class="card-body"> </select> <div class="form-group"> <label for="">Choose a date</label> <input type="date" value="{{values.date | date:'Y-d-m'}}" class="form-control form-control-sm" name="random_date" /> </div> <input type="submit" value="Submit" class="btn btn-primary btn-primary-sm" /> <div class="container"> <div class="col s12 m12 l4"> <div class="card-panel"> <h8 class="bold">Net Budget</h8> <h1 class="bold">${{ Net_Income }}</h1> </div> … -
django orm foreign key latest data using filter query
class Schedule(models.Model): user = models.ForeignKey(USER, on_delete=models.SET_NULL, null=True) area = models.ForeignKey(Site, on_delete=models.SET_NULL, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) area = Schedule.objects.values("area").annotate(latest=Max('created_at')).values("area") latest = Schedule.objects.values("area").annotate(latest=Max('created_at')).values("latest") Schedule.objects.filter(created_at__in=latest, area__in=area) I got the value I want. However, I am uneasy when I filter with ForeignKey and DateTimeField. Can't there be a better way? Also, can't you make it cleaner other than the code above? -
How to Add uuid field in django Existing User model?
I really need your help, I've been looking everywhere but can't find anything? -
Subtract Year from an object in a Django Project
I'm trying to subtract year data from a model object created in a Django project. I would like to obtain a final value comparing a date in an object registered in my model with the value of the current year, 2022. Something like an anniversary date calculation for an ephemeris project. Logic: Current Year - object with a 'year' value in a date field "1952"; Logic Example: 2022 - some_variable Expected result = 70 My model: class Person(models.Model): dateborn= models.DateField() I'm trying to use .dates() in the logic in my views.py to get the year: from app.models import Person persons = Person.objects.all() dateborn = persons.dates('dateborn','year') then I get a result: <QuerySet [datetime.date(1935, 1, 1)]> OK! I'm struggling now to elaborate a logic to subtract the result of this QuerySet using only the 'YEAR' of the object. I know that if I use an INT I will not be able to perform the calculation. I try: #used resultfinal = 2022 - dateborn AND #used resultfinal = datetime.today().strftime('%d/%m') - dateborn Then #My expected end result would be something like this: resultfinal = 2022 - 1935 I know I'm mixing things up, but I can't find a method of subtracting correctly. :( I … -
I got unexpected keyword argument 'providing_args' after installing Django extensions
I am creating a Django website. I was recently using the management command runserver_plus provided by Django Extensions to run the development server. When I attempt to run the website through terminal I receive the error message: C:\Users\Hp\anaconda3\DJANGO\website> python manage.py runserver_plus --cert-file cert.crt Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main File "C:\Users\Hp\anaconda3\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\Hp\anaconda3\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Hp\anaconda3\lib\site-packages\django\core\management\__init__.py", line 279, in fetch_command klass = load_command_class(app_name, subcommand) File "C:\Users\Hp\anaconda3\lib\site-packages\django\core\management\__init__.py", line 48, in load_command_class module = import_module("%s.management.commands.%s" % (app_name, name)) File "C:\Users\Hp\anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Hp\anaconda3\lib\site- packages\django_extensions\management\commands\runserver_plus.py", line 40, in <module> from django_extensions.management.utils import RedirectHandler, has_ipdb, setup_logger, signalcommand File "C:\Users\Hp\anaconda3\lib\site-packages\django_extensions\management\utils.py", line 6, in <module> from django_extensions.management.signals import post_command, pre_command File "C:\Users\Hp\anaconda3\lib\site-packages\django_extensions\management\signals.py", line 13, in <module> pre_command = Signal(providing_args=["args", "kwargs"]) TypeError: __init__() got an unexpected keyword argument 'providing_args' -
Django Admin Editable but Hidden field
Currently I have an editable field in a model in Django Admin. I would like this to remain editable, but not readable. For example, it would look like a password field with asterisks that an admin can change, but not read. How can I do this? -
Bad request 400 react + django
I am receiving error 400 bad request while trying to authenticate react with django rest framework Here is Signup.js import React from "react"; import { Button, Form, Grid, Header, Message, Segment, } from "semantic-ui-react"; import { connect } from "react-redux"; import { NavLink, Navigate } from "react-router-dom"; import { authSignup } from "../store/actions/auth"; class RegistrationForm extends React.Component { constructor (props) { super(props); this.state = { username: "", email: "", password1: "", password2: "", userType: "", is_student : true }; this.handleSubmit = this.handleSubmit.bind(this); this.handleChange = this.handleChange.bind(this); }; handleSubmit = e => { e.preventDefault(); const { username, email, password1, password2, userType, is_student } = this.state; this.props.signup(username, email, password1, password2, userType, is_student); const signupFormValid = !username?.length || !email?.length || !password1?.length || !password2?.length || !userType?.length ; }; handleChange = e => { this.setState({ [e.target.name]: e.target.value }); }; render() { const { username, email, password1, password2, userType } = this.state; const { error, loading, token } = this.props; if (token) { return <Navigate to="/" />; } return ( <Grid textAlign="center" style={{ height: "100vh" }} verticalAlign="middle" > <Grid.Column style={{ maxWidth: 450 }}> <Header as="h2" color="teal" textAlign="center"> Signup to your account </Header> {error && <p>{this.props.error.message}</p>} <React.Fragment> <Form size="large" method='post' onSubmit={this.handleSubmit}> <Segment stacked> <Form.Input onChange={this.handleChange} value={username} name="username" fluid … -
problem with migrate in heroku in windows 10
Cheers! i am trying to do heroku run python manage.py migrate from git on windows 10 and this is the result ` heroku run python manage.py migrate Running python manage.py migrate on `enter code here`tornilub... starting, run.3211 (Free) Running python manage.py migrate on tornilub... connecting, run.3211 (Free)Running python manage.py migrate on tornilub... up, run.3211 (Free) Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 91, in handle self.check(databases=[database]) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 487, in check all_issues = checks.run_checks( File "/app/.heroku/python/lib/python3.10/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/checks/urls.py", line 24, in check_resolver return check_method() File "/app/.heroku/python/lib/python3.10/site-packages/django/urls/resolvers.py", line 480, in check for pattern in self.url_patterns: File "/app/.heroku/python/lib/python3.10/site-packages/django/utils/functional.py", line 49, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/app/.heroku/python/lib/python3.10/site-packages/django/urls/resolvers.py", line 696, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/app/.heroku/python/lib/python3.10/site-packages/django/utils/functional.py", line 49, in __get__ res = instance.__dict__[self.name] = … -
Deploying django with apache + mod_wsgi _ Error 500
I'm trying to deploy my first django app in windows 10 (x64), so installed apache 2.4(x86), installed and build mod_wsgi (4.9.1) with python 3.8(x86) (I have microsoft visual studio 2019 installed) and configured Apache httpd.conf and httpd-vhosts.conf files. My app runs fine, but the annoying error 500 keeps showing every now and then, and goes away by refreshing the browser every time. There seems to be a bug with python 3.8, so decided to upgrade to python 3.10 (X86), Reinstalled mod-wsgi and other packages using pip in new virtual environment in the same directory, and reconfigured httpd.conf accordingly. now apache service fails to start with error: "windows could not start the Apache2.4 on local computer....". If I change httpd.conf configuration to load and use the python3.8 , Apache starts with no error. but again Error 500 keeps showing. by the way I tried the same with python3.9 (x64) and Apache 2.4 (X64), with no luck. any help would be greatly appreciated. In httpd.conf: This configuration fails: LoadFile "C:/Program Files (x86)/Python310-32/python310.dll" LoadModule wsgi_module "d:/django project/unemployment project/.venv/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win32.pyd" WSGIPythonHome "d:/django project/unemployment project/.venv" This configuration works: LoadFile "C:/Program Files (x86)/Python38-32/python38.dll" LoadModule wsgi_module "d:/django project/unemployment project/venv/lib/site-packages/mod_wsgi/server/mod_wsgi.cp38-win32.pyd" WSGIPythonHome "d:/django project/unemployment project/venv" -
Formset and django-autocomplete-light creates extra value
Formset creates an extra value when I click "add another" button. I don't know how to fix it. I will be happy if you could give me advice. Moreover, the second line does not work, that is, I cannot select any value. It doesn't show any options. forms.py class BirdForm(forms.ModelForm): name = forms.ModelChoiceField( queryset=Bird.objects.all(), widget=autocomplete.ModelSelect2( url='birdautocomplete'), ) class Meta: model = Bird fields = ('name', 'description') BirdFormSet = modelformset_factory( Bird, form=BirdForm, extra=1, ) template.html <div class="check_bird form-row"> <label class="form-label" for="myCheck">If you want to add new bird</label> <input type="checkbox" id="myCheck" onclick="FunctionBird()"> </div> <div class="check_bird_form" id="bird" style="display:none"> {{formset.management_form}} {% for form in formset %} <div class="bird-form form-row"> {{form}} </div> {% endfor %} <button style="margin-top:25px;" id="add-form" type="button">Add Another</button> </div> {{formset.media}} <script> function BirdCoauthor() { var checkBox = document.getElementById("myCheck"); var text = document.getElementById("bird"); if (checkBox.checked == true) { text.style.display = "block"; } else { text.style.display = "none"; } } let birdForm = document.querySelectorAll(".bird-form") let container = document.querySelector("#coauthor") let addButton = document.querySelector("#add-form") let totalForms = document.querySelector("#id_form-TOTAL_FORMS") let formNum = birdForm.length - 1 addButton.addEventListener('click', addForm) function addForm(e) { e.preventDefault() let newForm = birdForm[0].cloneNode(true) let formRegex = RegExp(`form-(\\d){1}-`, 'g') formNum++ newForm.innerHTML = newForm.innerHTML.replace(formRegex, `form-${formNum}-`) container.insertBefore(newForm, addButton) totalForms.setAttribute('value', `${formNum+1}`) } $("#1").val(null).trigger("change"); </script> -
i want to add value to a field by calculating two values for tow fields in django api rest framework not template
#models file I want to add value to deserved_amount field by calculating a payments minus from the class product inside field selling_price ... If there are any modifications to the important classes, I want to deduct a payment from the original amount and then show the remaining amount after each payment to the user... I want the process to rest framework api endpoint # this class adds payment to each product price class Payment(models.Model): PK = models.AutoField(primary_key=True) payments = models.FloatField(default=0) description_paid = models.TextField(max_length=1500, default='') payment_date = models.DateField(default=datetime.date.today) product = models.ForeignKey('Product',related_name='paymentProducts' , on_delete=models.CASCADE) imag_file = models.ImageField(upload_to='uploads' , blank=True , null=True) deserved_amount = models.FloatField(default=0, null=True , blank=True) ''' I want to add value to deserved_amount field by calculating a payments minus from the class product inside field selling_price ... please help me , thanks ''' #this is class add a product this is class add a product this is #class add a product this is class add a product this is class add #**strong text**product class Product(models.Model): JAWWAL = 'JAWWAL' type_category = [ (JAWWAL,'جوال'), ('SCREEN','شاشة'), ('FRIDGE','ثلاجة'), ('LAPTOP','لابتوب'), ('WASHER','غسالة'), ('ELECTRICAL DEVICES','جهاز كهربائي'), ('FURNITURE','موبيليا'), ('ATHER','اخرى'), ] PK = models.AutoField(primary_key=True) cost_price = models.FloatField(default=0) selling_price = models.FloatField(default=0) supplier_name = models.CharField(max_length=70 , blank=True , null=True) category = … -
Failure to access image from ImageField from model to display on one of my html pages
I am working on a commerce app wher a user can create a listing and also upload the image of the listing. The data is handled by a ModelForm: class ListingForm(ModelForm): class Meta: model = Listing exclude = [ 'date_made', 'user', 'category', 'is_active', ] The ModelForm inherits from the Listing model. Pay particular attention to the upload_image attribute: class Listing(models.Model): NAME_CHOICES = [ ('Fashion', 'Fashion'), ('Toys','Toys'), ('Electronic','Electronics'), ('Home', 'Home'), ('Other', 'Other') ] title = models.CharField(max_length= 64) date_made = models.DateTimeField(auto_now_add=True) description = models.TextField() user = models.ForeignKey(User, to_field='username', on_delete=models.CASCADE, related_name='user_listings', null=True) starting_bid = models.DecimalField(decimal_places=2, max_digits=264, default=10.00) upload_image= models.ImageField(blank=True, upload_to='media/') category = models.ForeignKey(Category, on_delete=models.CASCADE, to_field='name', related_name='category_listings', default=NAME_CHOICES[4][0], db_constraint=False) listing_category = models.CharField(max_length=12, choices=NAME_CHOICES, null=True, default=NAME_CHOICES[4][0]) is_active = models.BooleanField(default=True) def __str__(self): return f'{self.title}' I also have tried to make some media file configurations to my app. settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') (global/project) urls.py: urlpatterns = [ path("admin/", admin.site.urls), path("", include("auctions.urls")) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my views.py looks like this, im not sure if it is relevant to the problem: def create_listing(request): if request.method == 'POST': import datetime listing_form = ListingForm(request.POST) # bid = request.POST['starting_bid'] if listing_form.is_valid(): bid = listing_form.cleaned_data['starting_bid'] listing_form.save(commit=False) # listing_form.user = request.user listing_form.user = request.user listing_form.date_made = datetime.datetime.today() listing_form.is_active = … -
Django Model Form is not validating the BooleanField
In my model the validation is not validating for the boolean field, only one time product_field need to be checked , if two time checked raise product_field = models.BooleanField(default=False) product_field_count = 0 for row in range(0,product_field_count): if self.data.getlist(f'product_info_set-{row}-product_field'): product_field_count += 1 if product_field_count <= 1: raise ValidationError( _( "Manage Only Preferred Weeds Need to Be Select Once" )) validation error. -
Three strings of code repeat in three different view-functios
I have three view-functions in views.py in django project that using a same three arguments in them: paginator = Paginator(post_list, settings.POSTS_LIMIT) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) How can I put em in a single function (make an utility) to use one string of code in my view-functions, instead of repeat using three? Thats my first question here, thank you :) -
How can I allow users to send emails through my django app but coming from their own gmail account?
I have a django app where users can send emails through the app to contacts that they upload themselves. I use Sendgrid to send the email and the recipient receives an email from a "white-label" address like hello@mydomain.com Now, I would like to implement a system where I can allow users to send emails through our app but that those emails are sent by their own email address. To make it simple, let's just consider "Gmail" and if a user want they can "login with their gmail account" on my app and then send emails from my app that are sent from their account... I know that Gmail has an API and I wonder if I can leverage it to do what I need. -
Created a virtual environment 'test' in my windows command prompt, but workon test not working in visual studio code? How to fix?
Error: PS C:\Users\ARYAN\projects\project1> workon test workon : The term 'workon' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 workon test + CategoryInfo : ObjectNotFound: (workon:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException -
Django rest framework for Meetingroom Reservation tasks
I need to realize the following tasks: Create employee Create meeting room Get meeting room reservations and the possibility to filter by employee Create reservation (Reservation has title, from and to dates, employees) So, first I created 2 apps Employees and Reservations, this is the Employees' model (Employees/models.py) : from django.db import models from phonenumber_field.modelfields import PhoneNumberField from django.contrib.auth.models import AbstractBaseUser,PermissionsMixin,BaseUserManager # Creating the CustomUserManager class CustomUserManager(BaseUserManager): def _create_user(self, email, password, first_name, last_name, mobile, **extra_fields): if not email: raise ValueError("An Email must be provided") if not password: raise ValueError("The Password is mendatory") user = self.model( email = self.normalize_email(email), first_name = first_name, last_name = last_name, mobile = mobile, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, first_name, last_name, mobile, **extra_fields): extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_active',True) extra_fields.setdefault('is_superuser',False) return self._create_user(email, password, first_name, last_name, mobile, password, **extra_fields) def create_superuser(self, email, password, first_name, last_name, mobile, **extra_fields): extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_active',True) extra_fields.setdefault('is_superuser',True) return self._create_user(email, password, first_name, last_name, mobile, **extra_fields) # Creating User Model class User(AbstractBaseUser,PermissionsMixin): # Abstractbaseuser has password, last_login, is_active by default email = models.EmailField(db_index=True, unique=True, max_length=50) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=25) mobile = PhoneNumberField(null=False) address = models.CharField( max_length=250) is_staff = models.BooleanField(default=True) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name','last_name','mobile'] … -
What's a proper way to SET aurora_replica_read_consistency in django?
I am looking for a proper way to connect to Aurora from a redundant django app. I have a django app that runs in multiple regions. The Aurora cluster in AWS is configured to have a writable master in one region and a read-only replica with write-forwarding in the other region. This, supposedly, allows apps to "transparently" write to the read-only DB. It's not very transparent because it requires for every session to SET aurora_replica_read_consistency=SESSION. I was hoping to achieve this in the DATABASE session of the django settings file like so: DATABASES = { 'default': { 'ENGINE': 'django_prometheus.db.backends.mysql', 'NAME': 'mydb', 'USER': 'admin', 'PASSWORD': 'DB_PASSWORD', 'HOST': 'DB_HOST', 'PORT': '3306', 'OPTIONS': { 'init_command': 'SET aurora_replica_read_consistency=SESSION', }, }, } However, this throws an error on the aurora master, which is writable. The error states something that you can only set this variable on the read-only replica. I.e. my django container won't even boot on the master. I tried screwing with the connection signals; however, I did not find a way to make it run the SET command as the first thing after any new django connection to the DB. Signals seem to require each app to have a signal handler. The way … -
How to run pytest on Django rest framework app?
I want to run a pytest on 201 a successful post with just a single field in my project. I have a middleware.py which does something with the last object in the list whenever the project is ran. I have pytests at the moment to judge length of the entries but I want to run pytest when a post is successfully posted? I wish to do the same with a GitHub workflow test -
[DjangoRest + React]: Can't delete items and problems posting (error 403 and 301)
I'm building a very simple react + django website. Everything was going fine until today I made some changes to both the backend and frontend to add a third app that displays dummy pictures with a description. Up until that point, I was using axios to make get, post and delete requests with no trouble. I just wrote axios.post("api/", item) and it would post the item, or axios.delete(api/{props.id}) and the item would be deleted. Now, none of these work. At first I started getting 403 errors. Doing some troubleshooting, I tried adding the full url to see if it worked. Post worked. axios.post("localhost:8000/api/", item) now posts the item. The thing is that when I try to delete - axios.delete(localhost:8000/api/{props.id}) -, I get a 301 error. Besides kicking myself for not backing up before, what can I do? These are the backend and frontend codes. Frontend: import React, { useEffect, useState } from "react"; import Header from "./UI/Header"; import NewTask from "./tasks/NewTask"; import TaskList from "./tasks/TaskList"; import axios from "axios"; import classes from "./ToDo.module.css"; function ToDo(props) { const [taskList, setTaskList] = useState([]); const refreshList = async () => { await axios.get("todo/").then((res) => { const filteredData = res.data setTaskList(filteredData); }); }; useEffect(() … -
How to properly pass an enum class to the .HTML template in django
I have an Enum class like this one: models.py . . class Status(Enum): New = 1 Modified = 2 Done = 3 and I want to pass this to the html template in order to iterate over it and use it. so in my views.py I am passing it like so views.py from models import Status . . status_options = Status return render(request, 'orders.html', {status_options':status_options}) and the problem is when I try to use it inside the HTML template I don't get any values I tried the following orders.html {% for status in status_options %} {{ status.name }} {% endfor %} But I don't get any output Can anyone provide me with some guides here, please?