Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin Cannot Submit Form
I face some trouble while accessing django admin. It turns out that cannot create new objects from Django Admin. Here is how it looks if I want to create new user: I got the error Blocked form submission to '' because the form's frame is sandboxed and the 'allow-forms' permission is not set. Is there something that I should add in my settings file to resolve this error ? -
Django bulk load
I want to load my page faster in my Django project, so I know there has the "Bulk" option. views.py: class HRListView(Budgetlevel2Mixin, BudgetMixin, LoginRequiredMixin, ListView): model = HR template_name = "budget/hr_list.html" models.py: class HR(models.Model): year_scenario_version = models.ForeignKey( measure_name = models.ForeignKey( employee_type = models.ForeignKey( employee_level = models.ForeignKey( subsidiary = models.ForeignKey( department = models.ForeignKey( currency = models.ForeignKey( hr_list.html: {% block thead %} <tr> <th>ID</th> <th>HR Year Scenario</th> <th>Measure Name</th> <th>Employee Type</th> <th>Employee Level</th> <th>Subsidiary</th> <th>Department</th> </tr> {% endblock %} {% block tbody %} {% for q in object_list %} <tr> <td>{{ q.id }}</td> <td>{{ q.year_scenario_version }}</td> <td>{{ q.measure_name }}</td> <td>{{ q.employee_type }}</td> <td>{{ q.employee_level }}</td> <td>{{ q.subsidiary }}</td> <td>{{ q.department }}</td> </tr> {% endfor %} {% endblock %} How can I improve the page loading time? It takes almost 10 sec for full loading, something around 1200 records. Thanks a lot! -
Django url mapping error - URL doesn't match error
HI I got an error when calling an endpoint from django url Here is my piece of javascript window.location.assign(`customer/?id=1`} My urls.py path('customer/(?P<int:id>\d+)', views.get_customer, name="get_customer") Here is how it is called in the views.py def get_customer(request, id): print(f"the id {id}") # # customer = get_object_or_404(Customer, pk=id) # # print(f"customer {customer}") The Idea is to get the customer record filtered by id passed as query paramas But I got an error Using the URLconf defined in inventorymanagement.urls, Django tried these URL patterns, in this order: admin/ [name='home'] customer/(?P<int:id>\d+) [name='get_customer'] The current path, customer/, didn’t match any of these. Any idea on how to solve this? -
Accordion makes whole div move in the page
When opening a long text accordion, the whole page (or the whole div) moves slightly. I attach a little video to show the problem visually here. I have the accordions displaying information from a django template engine loop, here's the template code: <div class="accordion accordion-borderless" id="accordion_{{ forloop.counter }}"> <div class="accordion-item"> <h2 class="accordion-header" id="heading_{{ forloop.counter }}"> <button class="accordion-button collapsed" type="button" data-mdb-toggle="collapse" data-mdb-target="#collapse_{{ forloop.counter }}" aria-expanded="false" aria-controls="collapse_{{ forloop.counter }}" > {{event.title}} </button> <div id="collapse_{{ forloop.counter }}" class="accordion-collapse collapse" aria-labelledby="heading_{{ forloop.counter }}" data-mdb-parent="#accordion_{{ forloop.counter }}"> <div class="accordion-body"> {{event.description|safe}} </div> </div> </div> </div> What is causing that movement and how can it be solved? -
djongo + mongodb, Array Data Insert Problem
I have a problem. Stack: Django-Rest-Framework + Djongo + Mongodb. Problem: Insert error array data //models.py from django.db import models from djongo import models as djongoModels class House(models.Model): house_id = models.CharField(max_length=256) class Meta: abstract = True class Users(models.Model): _id = djongoModels.ObjectIdField() email = djongoModels.CharField(max_length=256) name = djongoModels.CharField(max_length=256) house = djongoModels.ArrayField( model_container=House ) class Meta: db_table = "drf_users" //serializers.py from .models import Users, Houses from rest_framework import serializers class InsertUserSerializers(serializers.ModelSerializer): email = serializers.CharField(required=True) name = serializers.CharField(required=True) house = serializers.ListField(child=serializers.CharField()) class Meta: model = Users fields = ('email', 'name', 'house') //views.py from .models import Users from .serializers import InsertUserSerializers class UsersViewSet(viewsets.ModelViewSet): queryset = Users.objects.all() serializer_class = InsertUserSerializers permission_classes = [AllowAny] //request.http POST http://<domain>/drf/house/ HTTP/1.1 Content-Type: application/json { "email": "test6@stay.co.kr", "name": "test6", "house": ["SEOU-2023-1023-0002","GYOU-2023-1022-0001"] } //pip freeze asgiref==3.5.2 backports.zoneinfo==0.2.1 certifi==2022.9.24 cffi==1.15.1 charset-normalizer==2.1.1 cryptography==38.0.1 Deprecated==1.2.13 Django==4.1 django-cors-headers==3.13.0 django-filter==22.1 django-oauth-toolkit==2.1.0 django-rest-framework==0.1.0 django-rest-framework-mongoengine==3.4.1 djangorestframework==3.13.1 djongo==1.3.6 dnspython==2.2.1 idna==3.4 jwcrypto==1.4.2 mongoengine==0.24.2 oauthlib==3.2.1 Pillow==9.2.0 pycparser==2.21 pymongo==3.12.3 pytz==2022.2.1 requests==2.28.1 sqlparse==0.2.4 urllib3==1.26.12 wrapt==1.14.1 I want a final db values. enter image description here Is this serializers problem? Or Djongo problem. If remove a serializers house array field, there is no error. What's wrong with my source code. Please help me. -
Object of type set is not JSON serializable while using api
Traceback (most recent call last): File "c:\Kunal\Project\Django Projects\Celery\separate.py", line 12, in <module> resp = json.dumps(client.send_message( File "C:\Users\i7tuf\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\models.py", line 319, in prepare self.prepare_body(data, files, json) File "C:\Users\i7tuf\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\models.py", line 471, in prepare_body body = complexjson.dumps(json, allow_nan=False) File "C:\Users\i7tuf\AppData\Local\Programs\Python\Python39\lib\site-packages\simplejson\__init__.py", line 398, in dumps return cls( File "C:\Users\i7tuf\AppData\Local\Programs\Python\Python39\lib\site-packages\simplejson\encoder.py", line 298, in encode chunks = list(chunks) File "C:\Users\i7tuf\AppData\Local\Programs\Python\Python39\lib\site-packages\simplejson\encoder.py", line 696, in _iterencode for chunk in _iterencode_dict(o, _current_indent_level): File "C:\Users\i7tuf\AppData\Local\Programs\Python\Python39\lib\site-packages\simplejson\encoder.py", line 652, in _iterencode_dict for chunk in chunks: File "C:\Users\i7tuf\AppData\Local\Programs\Python\Python39\lib\site-packages\simplejson\encoder.py", line 652, in _iterencode_dict for chunk in chunks: File "C:\Users\i7tuf\AppData\Local\Programs\Python\Python39\lib\site-packages\simplejson\encoder.py", line 716, in _iterencode o = _default(o) File "C:\Users\i7tuf\AppData\Local\Programs\Python\Python39\lib\site-packages\simplejson\encoder.py", line 272, in default raise TypeError('Object of type %s is not JSON serializable' % TypeError: Object of type set is not JSON serializable Code Image -
Django Create a copy of a Model upon trigger
I'm wondering if the following is possible in Django. As I start my the project, I will create a Model with 'x' fields called BASEMODEL. I will then create another Model called PROJECT with just 1 CharField. I will be creating both these in the usual way models.py, makemigrations, migrate etc. Then as the admin when I add a record to PROJECT with a value 'PROJECT1', is it possible for Django to create a copy of the BASEMODEL called BASEMODEL_PROJECT1 ? I'm not looking for the exact code, just looking for any ideas or links as to how I could possibly do so. Thanks. -
Django authentication always return none
My authentication doesn't seem to work. I got registration and everything, its just the log in and authenticate aspect that doesnt work. I'm not sure why. I'm not sure as to why my django auth returns none. I have this in my settings: AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'UniLinkedApp.auth.MyAuthBackEnd', ) I have my models as: class Register(models.Model): username = models.CharField(max_length = 200) email = models.EmailField(max_length = 200) password = models.CharField(max_length = 200) university = models.CharField(max_length=50) major = models.CharField(max_length = 200) def __str__(self): return self.user class MyAccountManager(BaseUserManager): def create_user(self, username, email, password, university, major): if not email: raise ValueError("Users must have an email address") if not username: raise ValueError("Users must have an username") user = self.model( username=username, email=self.normalize_email(email), password = password, university = university, major = major, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( username=username, email=self.normalize_email(email), password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): username = models.CharField(max_length = 200) email = models.EmailField(max_length = 200) password = models.CharField(max_length = 200) university = models.CharField(max_length=50) major = models.CharField(max_length = 200) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = … -
How to set PIPENV_IGNORE_VIRTUALENVS=1?
While trying to create a venv for a django project while beeing in the projects dir using pipenv, I noticed that after installing django with pipenv (pipenv install django), pipenv sent a message: Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. You can set PIPENV_IGNORE_VIRTUALENVS=1 to force pipenv to ignore that environment and create its own instead. You can set PIPENV_VERBOSITY=-1 to suppress this warning. Creating a Pipfile for this project... Installing django... [= ] Installing django...[packages]... Installation Succeeded Pipfile.lock not found, creating... Locking [packages] dependencies... Building requirements... Resolving dependencies... Success! Locking [dev-packages] dependencies... Updated Pipfile.lock (99c4b9ec1b8891ff787677276760beb6d6d4919c55660da1c713682156a6086c)! Installing dependencies from Pipfile.lock (a6086c)... To activate this project's virtualenv, run pipenv shell. Alternatively, run a command inside the virtualenv with pipenv run. After this I ran the command (pipenv --venv) and got this message: Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. You can set PIPENV_IGNORE_VIRTUALENVS=1 to force pipenv to ignore that environment and create its own instead. You can set PIPENV_VERBOSITY=-1 to suppress this warning. C:\Users\User7G\OneDrive\Desktop\My code\My … -
How to split django 'models.py', 'views.py', 'serializers.py' files into multiple files
Hello, For educational purposes, I am building a django app with multiple models and relationships. According to the official tutorial and many implementations I found online, the database models and serializers as well as views are all defined in single files: "models.py", "serializers.py", and "views.py". So, the project directory looks as follows: > my_app > migrations > __init__.py > admin.py > models.py > apps.py > serializers.py > tests.py > urls.py > views.py Depending on how many models are included in the app, those files may grow to hundreds or even thousands lines of code. As a result, developing and maintaining the application becomes extremely challenging. I would like to split these files so that every model (and coresponding serializer and view) will be defined in a separate per-model files. as follows: > my_app > migrations > models > __init__.py > model1.py > model2.py > model3.py > model4.py > serializers > __init__.py > model1_serializers.py > model2_serializers.py > model3_serializers.py > model4_serializers.py > views > __init__.py > model1_views.py > model2_views.py > model3_views.py > model4_views.py > __init__.py > admin.py > apps.py > tests.py > urls.py I encountered some difficulties in splitting these files and have not yet found an optimal solution. The Problem In … -
How to concatenate the values of a subquery that returns more than one row into a single row in Django
I have this query: forms = forms.annotate( transaction_id=F('id'), program=F('program__name'), action_plan=Subquery(Action.objects.using('db').filter( mid_id=OuterRef('transaction_id'), ).values('plan')) But it returns "django.db.utils.ProgrammingError: more than one row returned by a subquery used as an expression" How can i concatenate all values returned in one row separated by ","? -
Use Javascript to call function in models.py and update model field
I am developing an ecommerce website. I want my customers to view updated total_price field on the sidebar located alongside the order form. My model.py looks as follows: class Order(models.Model): Customer = models.ForeignKey(User, on_delete=models.CASCADE) no_of_pages = models.PositiveIntegerField(default=1) def total_price(self): price_per_page = 20 return no_of_pages * price_per_page Now I have my views.py and forms.py. I have also rendered a html template to display the form and allow the user to place the order by indicating the number of pages. My views.py is as follows: def OrderView(request): order_list = Order.objects.all() if request.POST: form = OrderingForm(request.POST) if form.is_valid(): form.save() return redirect('home') return render(request, 'orderingsystem/ordercreate.html', {"form": OrderingForm}) My aim is to display a the total price on the side of the order page as soon as the customer selects number of pages without any HttpResponse because the form is not yet submitted at this stage. For example: If the Customer selects one page, the total price to be displayed = 1 * 20 = 20; if the customer selects 2 pages, the sidebar widget that displays total price updates automatically to 2 * 20 = 40, without any Http call. In other words, I want something like JavasScript to call def total_price() in my … -
Why Request to an API takes too long time
Maybe this question already exits, if yes sorry When I was making registration the redirect to other page was almost simultaneously, but when I started to send (username,password) data to an api url in order to take token, the website started to load more longer. I am doing it in Django, and it is only me making request, I guess how long it will be if I launch this website. Why it is taking so much time to make request, if there a way to make it faster? -
Submitting a form using POST from a VueJS component to Django backend
I am looking for a method which would allow me to use my created form (found in a vue component) to submit or make a post request to my project's django backend. I am aware of an approach which involves creating a forms.py file and using django's form, however, this is not what I am after. Typically, when using a form of django's, people use the line bound_form = {a form they have imported}. How can this be done with a vue component form? Traditional approach I am trying to avoid: def post(self, request): task = json.loads(request.body) bound_form = TaskForm(task) if bound_form is_valid(): new task = bound_form.save return JsonResponse... Thank you! -
Unable to change Django default templates
I'm learning Django using W. Vincent's "Django for beginners". I got to the part where we have to customize the password change page (p. 186). According to the author: "Django already has created the views and URLs for us, we only need to change the templates." I created a new template password_change_form.html but when I start a local server and go to the localhost/accounts/password_change, I still see the old default page with the "Django Administration" header. Here is the code: {% extends "base.html" %} {% block title %}Password Change{% endblock title %} {% block content %} <h1>Password change</h1> <p>Please enter your old password, for security's sake, and then enter your new password twice so we can verify you typed it in correctly.</p> <form method="POST"> {% csrf_token %} {{ form.as_p }} <input class="btn btn-success" type="submit" value="Change my password"> </form> {% endblock content %} I'm surprised because everything worked well up until this point, as I was able to successfully updated the login and signup pages' templates. What do you think might be going wrong? Thanks. -
Django SearchQuery and SearchRank not finding results when 1 word matches in a 2 word query
I have a list of articles and I want to do a search using the PostgreSQL SearchQuery and SearchRank functionality. Here is the pseudo code: from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank from .models import Article vector = SearchVector('title', weight='A') query = SearchQuery(value) results = Article.objects.annotate(rank=SearchRank(vector, query, cover_density=True).order_by('-rank') for r in results: print(r.rank, r.name) For example, if I search for only "computer" this is what I gets printed: 1 The most powerful computer in the world 0 This man built a plane for his family in his garden 0 Dogs can sense earthquakes before they happen As you can see it all works as expected with the article that contains "computer" in the title getting a rank of 1. But now if I search for something with 2 words "fast computer" the results will all show a rank of 0. 0 Dogs can sense earthquakes before they happen 0 The most powerful computer in the world 0 This man built a plane for his family in his garden According to the "SearchQuery" documentation: If search_type is 'plain', which is the default, the terms are treated as separate keywords So why is still not matching the article with "computer" in the title? … -
Pytest - Access to DB from inside setup_class method
I need to have access on creation from inside the setup_class method. F.e.: @pytest.mark.django_db class TestPerson: @classmethod def setup_class(cls): Person.objects.create(first_name='John', last_name='Snow') # here error happens def setup_method(self): Person.objects.create(first_name='John', last_name='Snow') def test_1(self): assert True It fails with error: RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. For method setup_method it works fine. I did some research in pytest source code and found the place where usual class method setup_method becomes a pytest fixture. So I tried to implement the same approach: def make_setup_class_as_fixture(klass): old_setup_class = klass.setup_class @pytest.fixture(scope='class', autouse=True) def new_setup_class(cls): old_setup_class(cls) klass.setup_class = new_setup_class return klass @make_setup_class_as_fixture @pytest.mark.django_db class TestPerson: def setup_class(cls): Person.objects.create(first_name='John', last_name='Snow') def setup_method(self): Person.objects.create(first_name='John', last_name='Snow') def test_1(self): assert True But fail again with the same error. How to fix it? -
ModuleNotFoundError: No module named 'rest_framework' (tried many solutions but not working)
I have encountered this error. ModuleNotFoundError: No module named 'rest_framework' I have a virtual environment setted up and the rest framework is installed correctly. When I run pip3.10 show djangoframework, I get Name: djangorestframework Version: 3.14.0 Summary: Web APIs for Django, made easy. Home-page: https://www.django-rest-framework.org/ Author: Tom Christie Author-email: tom@tomchristie.com License: BSD Location: c:\users\chan\desktop\testpy\lib\site-packages Requires: django, pytz Required-by: My interpreter is Python 3.10.8 which is the same version and it is for the virtual environment. my VSCode shows my interpreter as Python 3.10.8 ("TESTPY":venv) .\Scripts\python.exe. I also have included the rest_framework in the INSTALLED_APPS in the settings.py INSTALLED_APPS = [ 'rest_framework', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Below is the full error I get. (TESTPY) PS C:\Users\Chan\Desktop\TESTPY> python3 manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Users\Chan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Chan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\Chan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\Chan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\management\__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "C:\Users\Chan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Chan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Chan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\apps\registry.py", … -
Django filter does not accept database fields
Using Django 4.1.2, filtering does not work for database fields. Given the following model: class Activities(models.Model): es_date = models.DateField(blank=True, null=True) ef_date = models.DateField(blank=True, null=True) ls_date = models.DateField(blank=True, null=True) lf_date = models.DateField(blank=True, null=True) Migration done and DB content can be retrieved, for instance it gives back all of them properly: >>>from mymodel.models import Activities >>>Activities.objects.all() <QuerySet [<Activities: Task 33>, <Activities: Task 30>...]> or requesting a particular item also works properly: >>>Activities.objects.get(id=1) <Activities: Task 1> although applying filter for a given field it drops "NameError" error >>>Activities.objects.all().filter(es_date>timezone.now()) Traceback (most recent call last): File "<console>", line 1, in <module> NameError: name 'es_date' is not defined What might be the error? -
Jinja Expression In Statement
I am wanting to include dynamic variables inside of an if statement. {% elif request.path == "/order/{{city}}" %} I have a database I can refer to, to get the city names I need out depending on the url but am having a hard time sending that info in through this if statement. (Everything works dynamically up until this point) Solutions? -
how to find number of patients and and hospitals in a city using values (group by) in django
I'm trying to find number of patients and and hospitals in a city: for example: patients : 13 , hospital : A , city : London patients : 20 , hospital : B , city : NewCastle here is my models.py class City(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class Hospital(models.Model): name = models.CharField(max_length=150) city = models.ForeignKey(City, on_delete=models.CASCADE, related_name="hospital") def __str__(self): return self.name class Patient(models.Model): name = models.CharField(max_length=150) city = models.ForeignKey(City, on_delete=models.CASCADE, related_name="patients") hospital = models.ForeignKey(Hospital, on_delete=models.CASCADE, related_name="patients", blank=True, null=True) here is my query: City.objects.values('name').annotate(patients_no=Count('patients__pk'),hospitals_no=Count('hospital__pk')) but it sums number of patients with number of hospitals! is there away to achieve it please. i have to return number of hospitals in a city, and number of patients in a hospital, note: i dont care about the name of the hospital Thank you in advance. -
Do you query database data in model or view, Django
This is probably a dumb question here but bran new to Python/Django. I've worked with many other frameworks and how the MVC works is in the model is where you make all your queries and then you grab them from the controller to send to the view. In Django it's telling me to make these queries in the view.py file(a controller in other frameworks) Example: Models.py from django.db import models class Moves(models.Model): name = models.CharField(max_length=64) description = models.CharField(max_length=500) position_id = models.IntegerField() is_offence = models.BooleanField(default=True) views.py def half_guard_moves(request): half_guard_moves = Moves.objects.values().filter(position_id=2) return render(request, "moves/halfguardmoves.html", {'half_guard_moves': half_guard_moves}) This works but seems odd because I'm actually making the query in the views(controller) file not the model? Am I doing this correct or is there another way to make queries directly in the model? -
Saving data without using form in Django
I have one application that need save data without using form. The scenario will be a potential employee reserves available gag job offers. The problem is nothing saved. @login_required #here employee reserves that offered jobs on job list def reserve_shift(request, pk): shift = Shift.objects.get(id=pk) if request.method == 'POST': user=request.user reserve_shift.objects.save() return redirect('reserved_shifts') @login_required #the view to all shifts that employee reserved def reversed_shifts(request): user=request.user reserved_shifts=ShiftReservation.objects.all() context={'reserved_shifts':reserved_shifts,'user':user} return render(request,'reserved_shifts.html',context) here is the model that inherited from Shift class class ShiftReservation(Shift): user=models.ForeignKey(get_user_model(),on_delete=models.CASCADE) time_reserved = models.DateTimeField(auto_now_add=True) How should I do it? Thank you! -
Is it possible to dynamically set a field to the number of elements in the database in Django?
Let's say I have an example model: class Item(models.Model): name = models.CharField(max_length=100) Is it possible to add a field which would dynamically change based on number of elements in the database? For example, let's say we have following entries in the database: id name order 0 'Mark' 0 1 'John' 1 If I were to add another user from the Django Admin interface I only want to see options 0, 1 and 2. If I select 2 the new user would be added with that order, if I select 1 the new user would be added with order 1 and 'John' would get order 2. If there's a better way of doing this I'm all for it, I just need to be able to change order of the items from the Django Admin interface in an elegant way. -
The href and click event listeners should be executed sequentially
I'm working on a Django project in which I need to move to a specific URL and then toggle the sub dropdown menu, but the issue is that both things are happening at the same time. Here is my dropdown code <a href="{% url 'my_applications' %}" class="nav_link {% if request.resolver_match.url_name == "payroll_941_files" %}active{% endif %} dropdown-btn"><img src="{% static 'application/img/icon_doc.svg' %} "><span class="nav_name" >My Applications</span> </button> <div class="row dropdown-container "> <div class="col-md-2"> {% for company in companies %} <a href="{% url 'my_applications_id' company.id %}" class="company-row" >{{ company.name | title }}</a> {% endfor %} </div> </div> Here is my Javascript code var dropdown = document.getElementsByClassName("dropdown-btn"); for (var dropdown_size = 0; dropdown_size < dropdown.length; dropdown_size++) { dropdown[dropdown_size].addEventListener("click", function() { console.log(dropdown.length); this.classList.toggle("active"); var dropdownContent = this.nextElementSibling; if (dropdownContent.style.display === "block") { dropdownContent.style.display = "none"; } else { dropdownContent.style.display = "block"; } }); } Now when I click the My application dropdown section both href and toggle running simultaneously.