Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Grouping group permissions in django and drf
I'm creating ecommerce website with many apps (catalog, analytics, sale, warehouses, users...) and I created group permissions for each of apps (like group which has all permissions in catalog app and etc). I also created a new admin-dashboard. I want to make dynamic role-based authentication and let's say superAdmin wants to create role like "operator" and he should add some of the groups as permissions (for example he can access to catalog and sale group permissions). How can I group another groups dynamically? Or are there any better methods? -
Html to PDF conversion in Django
I have to convert an html page to pdf format and download it in Django.I have used xhtml2pdf library for the same.But the issue is i have to create 3 pages with different contents from database with header and footer in a single pdf file.I am not getting an idea,how to manage this.Can anyone help me how to handle it -
Trying to place postgresql database information inside a dotenv file to hide important info, like passwords etc
I'm using the django rest framework and trying to connect a postgresql database. If I have the connection to the database written explicitly in the settings.py file, running python manage.py runserver works fine, but as soon as I replace the database connection with the dotenv values, the connection breaks. How do I fix this? example This works fine DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'ticketdb', 'USER': 'postgres', 'PASSWORD': 'pretendmyrealpasswordishere', 'HOST': 'localhost', } } This does not and throws this error. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_USER_PASSWORD'), 'HOST': os.environ.get('DB_HOST'), 'PORT': os.environ.get('DB_PORT'), } } Traceback Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "/home/mikha/.local/share/virtualenvs/django-tracker-Ko6xeuHD/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/mikha/.local/share/virtualenvs/django-tracker-Ko6xeuHD/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 137, in inner_run self.check_migrations() File "/home/mikha/.local/share/virtualenvs/django-tracker-Ko6xeuHD/lib/python3.10/site-packages/django/core/management/base.py", line 564, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/mikha/.local/share/virtualenvs/django-tracker-Ko6xeuHD/lib/python3.10/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/home/mikha/.local/share/virtualenvs/django-tracker-Ko6xeuHD/lib/python3.10/site-packages/django/db/migrations/loader.py", line 58, in __init__ self.build_graph() File "/home/mikha/.local/share/virtualenvs/django-tracker-Ko6xeuHD/lib/python3.10/site-packages/django/db/migrations/loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/mikha/.local/share/virtualenvs/django-tracker-Ko6xeuHD/lib/python3.10/site-packages/django/db/migrations/recorder.py", line 81, in applied_migrations if self.has_table(): File "/home/mikha/.local/share/virtualenvs/django-tracker-Ko6xeuHD/lib/python3.10/site-packages/django/db/migrations/recorder.py", line 57, in has_table with self.connection.cursor() as cursor: File "/home/mikha/.local/share/virtualenvs/django-tracker-Ko6xeuHD/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/mikha/.local/share/virtualenvs/django-tracker-Ko6xeuHD/lib/python3.10/site-packages/django/db/backends/base/base.py", … -
500 internal Server Error while setting up django in apache
I was working to setup apache2 for my django and while i started my apache server it shows 500 error ` <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match t`your text`his virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn Alias /static /var/www/isvr/static <Directory /var/www/isvr/static> Require all granted </Directory> <Directory /var/www/isvr/isvr_certs> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/var/www/isvr python-home=/var/www/isvr/myprojectenv WSGIProcessGroup myproject WSGIScriptAlias / /var/www/isvr/isvr_certs/wsgi.py ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is … -
How to redirect urls?
this is my main urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include("shop.urls")), ] i want that any url enter by user it will redirect to shop.urls and find here. like if user enter /index it will search index in shop.urls not in main urls my shop.urls from django.urls import path from . import views urlpatterns = [ path('', views.index), path('index', views.index), ] -
Django formtools Wizard done function not executed
(Reference: Django formtools done function not executed) I am trying to do the same thing. The steps are working and individual form data able to get, but after the submit button is clicked and final form is submitted, I expect all three form data to be submitted at once and the done function has to process that but it is not happening. I am not able to find the reason why. Because of policy I can't share the code but putting a dummy code here and logic what I am implementing. Kindly please direct. Following is my code, (This is a Edit Form I am trying to create, in each form init method is also overrided for initial data wrt pk, this all is working not an issue) done.html {% extends CURRENT_TEMPLATE %} {% load static %} {% block content %} Hi you are watching done.html {{ data }} {% endblock content %} form.html {% extends CURRENT_TEMPLATE %} {% load i18n %} {% block content %} <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> <form action="" method="post">{% csrf_token %} <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form.as_table }} {% … -
TypeError: check_password() missing 1 required positional argument: 'encoded'
I am trying to authenticate the user made using python manage.py shell, the password looks like :- pbkdf2_sha256$390000$------------------------$- . I have used custom user model (abstractbaseuser) and a email authentication backend, right now I am handling the user authentication by diretly creating the user in the DB table. settings.py AUTH_USER_MODEL = 'accounts.Usermanagement' AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'accounts.backends.EmailAuthBackend', ] backends.py # from django.contrib.auth.models import User from django.contrib.auth.hashers import check_password from django.contrib.auth import get_user_model Usermanagement = get_user_model() class EmailAuthBackend: def authenticate(self,request,username,password): print("Custom authenticate rqst: ",request) try: user = Usermanagement.objects.get(emailid=username) # print(password) # print(user.password) # print(check_password(password)) # print(user.check_password(password)) if user.password == password or user.password == check_password(password): #! PROBLEM return user return None except user.DoesNotExist: return None def get_user(self,user_id): try: return Usermanagement.objects.get(pk=user_id) except Usermanagement.DoesNotExist: return None managers.py from django.contrib.auth.models import BaseUserManager from django.contrib.auth.hashers import make_password class UsermanagementCustomUserManager(BaseUserManager): # create_user(username_field, password=None, **other_fields) def create_user(self,emailid,roleid,organizationid,firstname, password=None, passwordexpirydate="2022-12-12 12:00:00",createdby=0,modifiedby=0): """ Creates and saves a User with the given email, date of birth and password. """ if not emailid: raise ValueError('Users must have an email address') user = self.model( emailid=self.normalize_email(emailid), roleid = roleid, organizationid=organizationid, firstname = firstname, password= make_password(password), createdby = createdby, modifiedby = modifiedby, ) views.py from django.contrib import messages from django.http import HttpResponse from django.contrib.auth import … -
Why is Django database save not permanently saving the update?
I am using a postgresql database. I am updating a certain field of an existing database row and saving it again. However, this is change not reflecting inside the database (viewing it on DBeaver). The bizarre thing is that the change is properly reflected using the debugger and querying the database with the same ID. p_details: ProjectDetails = ProjectDetails.objects.get(pk=res['id']) p_details.build_status = ProjectBuildEnums.PASSED.value if res['error'] is None else ProjectBuildEnums.FAILED.value p_details.build_error = json.dumps(res) p_details.save(update_fields=["build_status", "build_error"]) sleep(1) new_p = ProjectDetails.objects.get(pk=res['id']) This is the line of code where I am updating the database. After the save, I am requerying the database using the same primary key ID. At this instance, using the debugger, I can see the changes clearly. However, viewing this database using DBeaver after refreshing the database doesnt show this change yet. Once the view is complete, and I refresh the database again, this change is still not present, meaning the update has disappeared. Does anyone know what is going on? After the above lines, the ProjectDetails database is no longer being touched. No errors are shown in the terminal/debugger either. -
How can I automatically update two objects in same model after 7 days continuously on Django?
I have a 2 models that I wish to interact/update every 7 days without needing me to execute. ( wether the website is online or offline )( local hosting for now ) class Model: name = model... quantity = models.IntegerField(default=0) obj A name = A quantity = 0 obj B name = B quantity = 1,000,000 I'm trying to find a way to transfer 1000 from obj B to obj A, every 7 days. I am looking but still can't find an answer that simplifies this situation. Thanks for the help! I haven't tried anything yet since I do not know where to start. I know how to update objects manually, on page load or with signals. it may have something to do with DateTime but I am not sure. Currently, there is no date field in the model. Or celery, but I have never used it before. -
How to update custom user's model fields using APIView update method
I am trying to code up a APIView's update method so I can change model fields in my custom AbstractUser model. I read the documentation for APIViews and other examples, but most of them involved another OneToOne 'profile' model like in this example and or coding up the serializer which I don't think it's necessary for user model(correct me if I'm wrong) I am unsure how to implement the same update method for a user model. This is my custom user model. I am trying to update referred_count and tokens fields here from frontend users/models.py class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = None first_name = models.CharField(max_length=100, default="unknown") last_name = models.CharField(max_length=100, default="unknown", blank=True) profile_pic = models.CharField(max_length=200, default="unknown") premium = models.BooleanField(default=False) referred_count = models.IntegerField(default=0) tokens = models.IntegerField(default=0) email = models.EmailField(unique=True, db_index=True) secret_key = models.CharField(max_length=255, default=get_random_secret_key) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = UserManager() class Meta: swappable = "AUTH_USER_MODEL" users/api.py class UpdateFields(ApiAuthMixin, ApiErrorsMixin, APIView): def update(self, request, *args, **kwargs): # update various user fields based on request.data # I am not sure what should go inside here. return request.user.update(request, *args, **kwargs) I want to send something like the following from frontend which will pass through the UpdateFields APIView and 'patch' … -
Django CSRF Token missing from ajax request
So i'm building a project in Django for a "password manager" I've built my modules and correctly implemented the Item insertion via Django ModelForm, with csrftoken and all that. Now i need to make an ajax request for updating the fields of the Item, and wanted to do on the same page so from Js when opening a LoginItem to edit the content I send a GET request as such fetch(`edit/login=id`) .then((response) => response.text()) .then((form) => { const edit_form = document.createElement('form'); edit_form.setAttribute("method", "post"); edit_form.setAttribute("id", "edittest"); edit_form.innerHTML = form; //append the form then in script.js, on submit: fetch(`edit/login=id}`, { method : "PUT", Headers:{ "X-CSRFToken": getCookie("csrftoken"), "Content-type": "application/json", }, mode:"same-origin", body : JSON.stringify(body), }) .then((response) => response.json()) .then((data) => { console.log(data) }) in Views.py def edit_login(request, id): if request.method == GET: login = Entry.objects.get(id=id) // setting initial values for the form initial = { "title": login.title, "username": login.username, "password": login.password, "note": login.note, "folder": login.folder, "protected":login.protected, "favorite": login.favorite, } // setting the initial values to the ModelForm form = LoginForm(initial=edit) return render(request, 'vault/new_item.html', {"entry_form": form, 'uri_field': uri}) else if request.method == "PUT": if request.user == login.owner: data = json.loads(request.body) print("test") # execution does not reach here return JsonResponse({"message": "Succesfully edited"}, status = 200 … -
OneToOne related other model field converted to boolean field check box in form to show or hide model fields doesn’t work
I have these two django blog models in models.py ` class Snippet(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') code = models.TextField() ... class Post(models.Model): # id = models.AutoField(primary_key=True) # the same field in comment model for multi-inheritance (post_id) id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) slug = models.SlugField(max_length=200, db_index=True, unique=True, editable=False) # add unique=True in slug (never repeat) title = models.CharField(max_length=200, db_index=True, default='') tag = models.ManyToManyField(Tag, blank=True, help_text="Select a tag for this post", related_name='post_tags') snippet = models.OneToOneField(Snippet, on_delete=models.CASCADE, related_name='post_snippets') ... **and i have forms to add new post as follows** class PostModelChoiceField(ModelChoiceField): def label_from_instance(self, obj): return "Post #%s) %s" % (obj.id, obj.title) class SnippetForm(forms.ModelForm): post = PostModelChoiceField(queryset=Post.objects.all()) class Meta: model = Snippet fields = '__all__' class PostForm(forms.ModelForm): class Meta: model = Post #fields = '__all__' #fields = ['title', 'tag', 'maintainer', 'post_img', 'content', 'snippet', 'genre', 'language', 'video', 'post_type', 'urls', 'views', 'status' ] labels = {'snippet': _('Add Code'),} exclude = ('creator', 'slug',) widgets = { 'snippet': forms.CheckboxInput(attrs={'type': 'checkbox', 'class': 'checkbox', 'id': 'post-snippet'}) } def clean(self): snippet = self.cleaned_data.get('snippet') if snippet: self.fields_required(snippet.title, snippet.code, snippet.title, snippet.linenos, snippet.language, snippet.style, snippet.highlighted) # ['title', 'code', 'linenos', ....] else: self.cleaned_data['snippet'] = False return self.cleaned_data def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.queryset … -
ECS Fargate - Running Django project image - uwsgi command not found
I tried change the uwsgi path, and add it to requirements file as well, but it not works either -
MonkeyPatchWarning: Monkey-patching ssl after ssl has already been imported may lead to errors
Background I've got a Django app that is heavily iobound, so per docs I've read, I'm trying to get gunincorn working with gevent for the best performance. Error dev1 | Patching Started dev1 | /app/Dev/wsgi.py:19: MonkeyPatchWarning: Monkey-patching ssl after ssl has already been imported may lead to errors, including RecursionError on Python 3.6. It may also silently lead to incorrect behaviour on Python 3.7. Please monkey-patch earlier. See https://github.com/gevent/gevent/issues/1016. Modules that had direct imports (NOT patched): ['urllib3.util (/usr/local/lib/python3.9/site-packages/urllib3/util/__init__.py)', 'urllib3.util.ssl_ (/usr/local/lib/python3.9/site-packages/urllib3/util/ssl_.py)']. dev1 | monkey.patch_all(thread=False, select=False) dev1 | Patching Done dev1 | /usr/local/lib/python3.9/site-packages/paramiko/transport.py:236: CryptographyDeprecationWarning: Blowfish has been deprecated dev1 | "class": algorithms.Blowfish, dev1 | /usr/local/lib/python3.9/site-packages/gunicorn/workers/ggevent.py:38: MonkeyPatchWarning: Patching more than once will result in the union of all True parameters being patched dev1 | monkey.patch_all() dev1 | /usr/local/lib/python3.9/site-packages/gunicorn/workers/ggevent.py:38: MonkeyPatchWarning: Patching more than once will result in the union of all True parameters being patched dev1 | monkey.patch_all() dev1 | /usr/local/lib/python3.9/site-packages/gunicorn/workers/ggevent.py:38: MonkeyPatchWarning: Patching more than once will result in the union of all True parameters being patched dev1 | monkey.patch_all() ... Setup wsgi.py # Needs to happen first print("Patching Started") from gevent import monkey monkey.patch_all(thread=False, select=False) # monkey.patch_all() from psycogreen.gevent import patch_psycopg patch_psycopg() print("Patching Done") import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Dev.settings') application … -
Django - Admin user only able to create data. FOREIGN KEY constraint failed for normal users
I'm creating a simple CRUD application to brush up on my Django skills (it's been a long time!) but I'm getting the below errors when I have a non-admin users create anything, either via the frontend or the sites backend: FOREIGN KEY constraint failed I'm also getting this error when I'm logged in as the admin user and try to update the user field in the Django Admin panel. The functionality itself works, as I can create activities through the frontend and backend when I'm logged in as the superuser. I've also tried deleting migrations etc.. but there doesn't seem to be any resolutions. The site itself uses Django's allauth models, but with custom models to fit the general purpose, but I'm still using the AllAuth user model as my foreign key, as the other model is a UserProfile: Below is my models.py file for the activities: class Activity(models.Model): class Meta: verbose_name_plural = 'Activities' activity_id = models.AutoField(primary_key=True) host = models.ForeignKey(User, on_delete=models.CASCADE, related_name="activity") name = models.CharField(max_length=254, null=False, blank=False) date = models.DateField() start_time =models.TimeField() end_time = models.TimeField() location = models.CharField(max_length=40, null=False, blank=False) description = models.CharField(max_length=140, null=False, blank=False) available = models.BooleanField(default=True) def __str__(self): return str(self.activity_id) With the view: def create_activity(request): if request.method == … -
Offloading extensive calculations in save method of Django custom FileField
I'm building a gallery webapp based on Django (4.1.1) and Vue. I want to also upload and display videos (not only images). For supporting formats, that don't work in a video html tag, I'm converting these formats to mp4 via pyffmpeg. For that I created a custom field for my model based on FileField. In it's save method I take the files content, convert it and save the result. This is called by the serializer through a corresponding ViewSet. This works, but the video conversion takes way too long, so that the webrequest from my Vue app (executed with axios) is running into a timeout. It is clear, that I need to offload the conversion somehow, return a corresponding response directly and save the data in the database as soon as the conversion is finished. Is this even possible? Or do I need to write a custom view apart from the ViewSet to do the calculation? Can you give me a hint on how to offload that calcuation? I only have rudimentary knowledge about things like asyncio. TL;DR: How to do extensive calculations asychronous on file data before saving them to a model with FileField and returning a response before … -
Django admin displays datetime fields inconsistently in Django admin view and in rendered tables
I have a model that is an activity object to save api JSON data for database queries. The api sends a start date (UTC) and a local start date. I am experiencing an inconsistent treatment of the UTC time value and the local time value. Model class ActivityObject(models.Model): name = models.CharField(max_length=50) distance = models.DecimalField(max_digits=8, decimal_places=2) moving_time = models.DurationField() elapsed_time = models.DurationField() total_elevation_gain = models.DecimalField(max_digits=5, decimal_places=2) type = models.CharField(max_length=15) start_date = models.DateTimeField() start_date_local = models.DateTimeField() average_speed = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) max_speed = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) average_cadence = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) has_heartrate = models.BooleanField(blank=True, null=True) average_heartrate = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) max_heartrate = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) activity_logged_time = models.DateTimeField(default=timezone.now, blank=True) def __str__(self): return 'id %s----name %s----start date %s----start date local %s----logged date %s' % (self.id, self.name, self.start_date, self.start_date_local, self.activity_logged_time) The unexpected behavior is that the field values inside the object are reversed. I get the values from API and convert the JSON to datetime objects. start_date = a_row['start_date'] start_date_pretty = convert_json_to_datetime(start_date) print('start date ', start_date_pretty) start_date_local = a_row['start_date_local'] start_date_local_pretty = convert_json_to_datetime(start_date_local) print('start date local ', start_date_local_pretty) Relevant JSON key and values: "start_date": "2022-11-04T21:01:20Z", "start_date_local": "2022-11-05T08:01:20Z", I have USE_TZ = True -
Django migrations dont work. Have to delete the db and start fresh eveery time
I have a django project which works fine. However, each time there is a change in my models (when I add attributes to my model), the migrations stop working. There is usually some sort of error or the migrations will not execute. The only way for me to make the migrations to work is to drop the database and start fresh. This is a very strange behavior and cannot work in a live/production environment. I recently had to delete the db in the production environment and it was very messy. Is there a way to fix this ? Isnt this strange that Django makes it harder to work with migrations when it claims that migrations make everything easy. Am I doing something wrong ? I dont know where to start from. -
How can I create an API index using multiple DRF routers?
I'm trying to build an API using DRF with the following structure (example): api/ ├── v1/ │ ├── foo/ │ │ ├── bar/ │ │ │ └── urls.py # There's one `rest_framework.routers.DefaultRouter` here │ │ ├── bar2/ │ │ │ └── urls.py # There's one `rest_framework.routers.DefaultRouter` here │ │ ├── __init__.py │ │ └── urls.py │ ├── foo2/ │ │ ├── bar3/ │ │ │ └── urls.py # There's one `rest_framework.routers.DefaultRouter` here │ │ ├── bar4/ │ │ │ └── urls.py # There's one `rest_framework.routers.DefaultRouter` here │ │ ├── __init__.py │ │ └── urls.py │ ├── __init__.py │ └── urls.py ├── __init__.py └── urls.py Intuitively, my endpoints would be https://api.example.com/v1/foo/bar/... https://api.example.com/v1/foo/bar2/... https://api.example.com/v1/foo2/bar3/... https://api.example.com/v1/foo2/bar4/... But I want that Api Root web page to be available from the https://api.example.com/v1 level. For example, when I ran curl https://api.example.com/v1 it would show me {"foo":"https://api.example.com/v1/foo/","foo2":"https://api.example.com/v1/foo2/"} and so on. That being said, I guess that the way to do it was to somehow "merge" those DefaultRouters. I'm aware that I could just router.registry.extend(some_other_router.registry), but that would make it all be at the same level and I explicitly needed it to be multi-level, as shown above. -
Having Trouble Adding Pagination In Class Views ( get_queryset )
Good day everyone, I'm trying to build a product category with pagination using class view (get_queryset). I followed a tutorial that did not actually cover this part that has get_queryset. I find it easier without get_queryset. PLEASE I urgently need help. Below is the class base views (views.py) class CatListView(ListView): template_name = 'category.html' context_object_name = 'catlist' paginate_by 12 def get_queryset(self): content = { 'cat': self.kwargs['category'], 'posts': Post.objects.filter(category__name=self.kwargs['category']).filter(status='published') } return content Template.html <nav aria-label="Page navigation example"> {% if is_paginated %} <ul class="pagination"> {% if page_obj.has_previous %} <li class="page-item" style="color:#000;"> <a class="page-link" href="?page={{page_obj.previous_page_number}}" style="color:#000; background:#98FB98;" >Previous</a> </li> {% else %} <li class="page-item disabled" style="color:#000;"> <a class="page-link" href="#" style="background:#E5E4E2;">Previous</a> </li> {% endif %} {% for i in paginator.page_range %} {% if page_obj.number == i %} <li class="page-item" style="color:#000;"> <a class="page-link active" style="background:#FF5E0E; color:#fff;">{{ i }}</a></li> {% else %} <li class="page-item"> <a class="page-link" href="?page={{ i }}">{{ i }}</a> </li> {% endif %} {% endfor %} {% if page_obj.has_next %} <li class="page-item" style="color:#000;"> <a href="?page={{page_obj.next_page_number}}" class="page-link" style="color:#000; background:#98FB98;" >Next</a> </li> {% else %} <li class="page-item disabled" style="color:#000;"> <a class="page-link" style="background:#E5E4E2;">Next</a> </li> {% endif %} </ul> {% endif %} </nav> Kindly help me implement paginator. I appreciate your time and effort. Thanks a lot -
How to access contents of a SimpleArrayField in Python Django
I am currently working with a form class in Django. I need to be able to access data contained in a SimpleArrayField. class SignUps(forms.Form) people = SimpleArrayField(forms.EmailField(), label="name") Let's say a user fills out the form with the names "John Smith," "Jane Smith", "Mike Smith". I need to be able to access the names. I've tried various methods such as print(people["name"]) or print(people[0]) But I keep getting the error TypeError: 'SimpleArrayField' object is not subscriptable. I've tried to figure out to access fields from a SimpleArrayObject, but I don't see any examples in documentation. How would I go about getting the names from the people object? Is that even possible to do? -
How to add more fields and remove or change the text from django UserCreationForm?
Im building an django web page for a personal proyect with basic login/signUp system. My problem is that i want to add more input fields like name and lastname ando aslo modify the default text, basically to change it to another language. Thx for the help. :c I tried to create an CustomField but didn't work -
Add Javascript string variable INSIDE a django template variable
I have a chart that is populated by django template variables. I have an update chart function that updates the data after certain buttons are clicked. Instead of writing the same js function 7x, can I update the javascript function to call the correct data within a Django template variable? Basically, the btn_id will either be A, B, C, D, E, or F and I want the django template variable to display the correct data based on the btn_id value. var results = {{ all_test_results.A.curve_series.curve_series }}.map(function(val, i) { return val === 'None' ? null : val; }); becomes const btn_id = this.id.slice(-1); # A, B, C, D, etc var results = {{ all_test_results.{{ btn_id }}.curve_series.curve_series }}.map(function(val, i) { return val === 'None' ? null : val; }); I am sure there is a simple way to inject a js string into a Django template variable, right? -
In Django when i passed a query to insert a row, in Oracle Db the row is being inserted twice in the table
@api_view(['PUT']) def updateRule1(request, id): nums15 = 'OK' json_data = json.loads(request.body) # print(json_data) con = None cur = None try: con = cx_Oracle.connect('<server connection details>') cur = con.cursor() except cx_Oracle.DatabaseError as e: print("Problem establishing connection with Oracle DB", e) q = "INSERT INTO XXMSE.RE_PREDICATE (RULE_ID, PREDICATE_ID, INPUT_VALUE_ID1, MATHEMATICAL_VALUE, INPUT_VALUE_ID2, BOOLEAN_OPERATOR) VALUES ('1','2','2000000','equals','30000000','None')" print(q) sql5 = cur.execute(q) cur.execute(sql5) con.commit() if cur: cur.close() if con: con.close() return Response(nums15) DB screenshot 1 1 1 equals 2 AND 1 2 2000000 equals 30000000 None 1 2 2000000 equals 30000000 None I see that there are 2 rows inserted into the DB. Django version is 4.1.1 What would be the reason for duplicate rows? Appreciate your help I used breakpoint() and made sure that api is called getting once.There is no duplicate entries in the backend. -
How to create multiple filters in Django?
I want to create multiple filters in Django. The screen shot below explains it. The user may opt not to select some criteria. If the user does not select Available from, Available till and Advance then I will get the value as None in views.py. If he does not select Category or Capacity then I will get an empty list otherwise I will get a list of Category or Capacity. The problem arises when there is None or empty list. Although I have written the code and it works fine but I want to know if there is a better way to do it? My code may have problems if the complexity increases. forms.py class RoomForm(forms.Form): ROOM_CATEGORIES = ( ('Regular', 'Regular'), ('Executive', 'Executive'), ('Deluxe', 'Deluxe'), ('King', 'King'), ('Queen', 'Queen'), ) category = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=ROOM_CATEGORIES, ) ROOM_CAPACITY = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), ) capacity = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=ROOM_CAPACITY, ) class TimeInput(forms.TimeInput): input_type = 'time' default=datetime.time() available_from = forms.TimeField( required=False, widget=TimeInput(), ) available_till = forms.TimeField( required=False, widget=TimeInput(), ) advance = forms.IntegerField( required=False, ) """Function to ensure that booking is done for future and check out is after check in""" def clean(self): cleaned_data = super().clean() …