Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i want to get all product of specific merchant in html here is my code
i want to get all product of specific merchant in html here is my code so these should i write in html to get the products that merchant uploaded class ProductList(ListView): model=Product template_name="merchant/product_list.html" paginate_by=3 def get_queryset(self): filter_val=self.request.GET.get("filter","") order_by=self.request.GET.get("orderby","id") if filter_val!="": products=Product.objects.filter(Q(added_by_merchant__contains=filter_val) | Q(product_description__contains=filter_val)).order_by(order_by) else: products=Product.objects.all().order_by(order_by) # Product.MerchantUser.objects.all(user=MerchantUser) product_list=[] for product in products: product_media=ProductMedia.objects.filter(product_id=product.id,media_type=1,is_active=1).first() product_list.append({"product":product,"media":product_media}) return product_list def get_context_data(self,**kwargs): context=super(ProductList,self).get_context_data(**kwargs) context["filter"]=self.request.GET.get("filter","") context["orderby"]=self.request.GET.get("orderby","id") context["all_table_fields"]=Product._meta.get_fields() return context -
How to create multiple model instances with Django Rest Framework using generics?
I would like to save and update multiple instances using the Django Rest Framework with one API call, using generics. I have tried the solutions proposed for the following links, but I would very much appreciate some help. Create several objects at once with Django Framework Generic Views How to save multiple objects with Django Rest Framework Django Rest Framework Doc for serializing multiple objects # serializers.py class AssetSerializer(serializers.ModelSerializer): class Meta: model = Asset fields = '__all__' #fields = ('id', 'name', 'amount') # views.py class CreateAssetView(generics.CreateAPIView): serializer_class = AssetSerializer(many=True) def perform_create(self, serializer): serializer.save(user=self.request.user) # urls.py urlpatterns = [ ... path('create_asset', CreateAssetView.as_view()), ] -
Auto-submit django form without causing infinite loop
I have an issue on my app that I can't work out the best way to approach the solution. I'm learning Django and have little to no experience in Javascript so any help will be appreciated. This may be a design flaw, so am open to other ideas. Problem When a user reaches their dashboard page for the first time, they would need to select the currency rate on a form they want to view their data in e.g USD, AUD, GBP etc. Once they submit their currency, their dashboard will become active and viewable. I would like this selection to remain submitted on refresh/load or auto submit on refresh/load. Hence, that currency will remain, unless the user submits another currency. See before/after images for context (ignore values as they are inaccurate): Attempted solution I have tried using Javascript to auto submit on load which causes and infinite loop. I have read to use action to redirect to another page but i need it to stay on the same page. Unless this can be configured to only submit once after refresh/load I don't think this will work <script type="text/javascript"> $(document).ready(function() { window.document.forms['currency_choice'].submit(); }); </script> <div class="container"> <div> <span> <h1>My Dashboard</h1> … -
Django QuerySet exists() returns True for empty set?
Something curious I found recently is that exists() evaluates to True for an empty QuerySet: In [1]: MyModel.objects.all() Out [1]: <QuerySet []> In [2]: MyModel.objects.all().exists() Out [2]: True When used with filter(), I get the expected result: In [3]: MyModel.objects.filter(id=1).exists() Out [3]: False This is behaving contrary to how I would expect as the empty QuerySet returned by the filter() is equivalent to MyModel.objects.all() which is empty. Why does this happen? It seems inconsistent. -
how do I add an item to the cart without the page reloading?
So I wanna add an item to the cart without the page reloading every time, I've used ajax in a previous project and the response time wasn't pretty, so is there a better way to go about this, that won't be slow? if so, how would I fix this? also not the best with javascript so if u can explain stuff a bit, I would really appreciate your help, thx! link to the rest main code: https://gist.github.com/StackingUser/34b682b6da9f918c29b85d6b09216352 template: {% load static %} <link rel="stylesheet" href="{% static 'store/css/shop.css' %}" type="text/css"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script type="text/javascript"> var user = '{{request.user}}' function getToken(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getToken('csrftoken'); function getCookie(name) { // Split cookie string and get all individual name=value pairs in an array var cookieArr = document.cookie.split(";"); // Loop through the array elements for(var i = 0; i < … -
Toggle Switch Button using HTMX
is there any method to use Toggle Switch Button with HTMX? if there, I need to pass a value to another button like my previous question. the Toggle Button is named 'Toggle' and have two (on/off) values and I need to pass them as: <button class="btn btn-primary" hx-get="{% url 'plotlybar' %}" hx-include="[name='fields'],[name='Toggle']" hx-target="#plotlybar"> Plot the bar Well Serv </button> My previous question So how to get this Button with HTMX All my best -
How to add serializer for Django with ManyToManyField with through
models.py looks like this from django.db import models class Sauce(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Sandwich(models.Model): name = models.CharField(max_length=100) sauces = models.ManyToManyField(Sauce, through='SauceQuantity') def __str__(self): return self.name class SauceQuantity(models.Model): sauce = models.ForeignKey(Sauce, on_delete=models.CASCADE) sandwich = models.ForeignKey(Sandwich, on_delete=models.CASCADE) extra_sauce = models.BooleanField(default=False) def __str__(self): return "{}_{}".format(self.sandwich.__str__(), self.sauce.__str__()) How would I create a serializer for SauceQuantity so I can add and read SauceQuantity? I looked through the docs but I am still confused. Thanks! -
Django: How to run a celery task only on start up?
I have a django app that uses celery to run tasks. Sometimes, I have a "hard shutdown" and a bunch of models aren't cleaned up. I created a task called clean_up that I want to run on start up. Here is the tasks.py from my_app.core import utils from celery import shared_task @shared_task def clean_up(): f_name = clean_up.__name__ utils.clean_up() Here is what celery.py looks like: import os from celery import Celery from celery.schedules import crontab from datetime import timedelta os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_app.settings") app = Celery("proj") app.config_from_object("django.conf:settings", namespace="CELERY") # Load task modules from all registered Django apps. app.autodiscover_tasks() app.conf.beat_schedule = { "runs-on-startup": { "task": "my_app.core.tasks.clean_up", "schedule": timedelta(days=1000), }, } @app.task(bind=True) def debug_task(self): print(f"Request: {self.request!r}") How can I change celery.py to run clean_up only on start up? Extra info: this is in a docker compose, so by "hard shutdown" I mean docker compose down By "on start up" I mean docker compose up -
I am getting the error NoReverseMatch at /blog/view/None/
I am makeing a blog with Django. When I try to go to a specific blog post I get this error NoReverseMatch at /blog/view/None/ Reverse for 'blog_like' not found. 'blog_like' is not a valid view function or pattern name. I don't know what is causing this issue at all. Any help would be appreciated full error: File "C:\Users\sekoc\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\template\loader_tags.py", line 62, in render result = block.nodelist.render(context) File "C:\Users\sekoc\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\sekoc\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\sekoc\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\template\defaulttags.py", line 446, in render url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) File "C:\Users\sekoc\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\urls\base.py", line 86, in reverse return resolver._reverse_with_prefix(view, prefix, *args, **kwargs) File "C:\Users\sekoc\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\urls\resolvers.py", line 694, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'blog_like' not found. 'blog_like' is not a valid view function or pattern name. [24/Apr/2022 17:30:28] "GET /blog/view/None/ HTTP/1.1" 500 155689 views.py from django.shortcuts import render, reverse from django.http import HttpResponseRedirect from django.views import generic from . import models from django.contrib.auth import get_user_model User = get_user_model() from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin # Create your views here. class create_blog_post(generic.CreateView, LoginRequiredMixin): model = models.Blog_Post template_name = 'blog_app/creat_post.html' fields = ('post_title', 'blog_content') success_url = reverse_lazy('blog_app:all') class view_blog_post(generic.ListView): model = models.Blog_Post template_name = 'blog_app/view_post.html' class delet_blog_post(generic.DeleteView, … -
DJANGO : TypeError: view must be a callable or a list/tuple in the case of include()
i am getting below error in django: File "C:\Users\USER\Desktop\Python\CarRentalSystem\system\urls.py", line 6, in url(r'^$', 'system.views.home', name = "home"), File "C:\Users\USER\Desktop\Python\lib\site-packages\django\conf\urls_init_.py", line 13, in url return re_path(regex, view, kwargs, name) File "C:\Users\USER\Desktop\Python\lib\site-packages\django\urls\conf.py", line 73, in _path raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view must be a callable or a list/tuple in the case of include(). -
How to disable Preselection from List_display Django Admin
Hi I want to disable the preselection from django admin, here is my code model.py from django.contrib import admin from django.db import models class Person(models.Model): option4 = models.CharField(max_length=50) option5 = models.CharField(max_length=50) option6 = models.CharField(max_length=50) option7 = models.CharField(max_length=50) admin.py class PersonAdmin(admin.ModelAdmin): list_display = ('option4', 'option5','option6','option') In this picture you can see the preselected the options by default , i do not want to that,how to disable preselction. enter image description here -
How to build a docker image (without docker compose) of a django app and use an existing mysql container
I have a "point of sales" application in Django that uses a mysql database. I followed this Docker guide: Python getting started guide In order to setup the mysql container I created a couple of volumes and its network: docker volume create mysql docker volume create mysql_config docker network create mysqlnet My Dockerfile looks like this: (I don't want to use docker-compose yet becouse I want to learn the bases) Dockerfile # syntax=docker/dockerfile:1 FROM python:3.8-slim-buster RUN apt update RUN apt upgrade -y RUN apt dist-upgrade RUN apt-get install procps -y RUN apt install curl -y RUN apt install net-tools -y WORKDIR /home/pos COPY requirements.txt ./. RUN pip3 install -r requirements.txt COPY ./src ./src CMD ["python", "./src/manage.py", "runserver", "0.0.0.0:8000"] And in the Django project my database settings and requirements looks like: settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'point-of-sales', 'USER': 'root', 'PASSWORD': 'r00t', 'HOST': 'localhost', 'PORT': '3307' } } requirements.txt # Django django>=3.1,<3.2 # DRF djangorestframework>=3.12,<3.13 # Databases mysqlclient What I want is to build an image of the Django application that I could run and attach to the mysql network. The problem is that I can't build the image of my django app becouse it throws the following … -
Azure python library return web app configurations
I am trying to deep dive into azure python sdk to retrieve and control all my resources in azure, but I am having hard time to find any valid documentation on the following issue. using this code: resource_client = ResourceManagementClient(credentials, subscription_id) web_client = WebSiteManagementClient(credential=credentials, subscription_id=subscription_id) rg_subscription = resource_client.resource_groups.list() web_apps_test = [] for rg in list(rg_subscription): for site in web_client.web_apps.list_by_resource_group(rg.name): print(site) I am able to return all my azure web app service. Which is great, but what I would like to have more is to be able for each web app, to return its configurations so I can extract specific values from it. I have been looking around since yesterday but I am having some problems to find the right documentation, code or GitHub project to achieve this. Just to give a practical example of what I am looking for, is this: Using azure cli, I can run the command az webapp config show --name <webapp-name> -g <resource-group-name> and I will get all the configurations for the specific web app. I was wondering if there is any python library to achieve this using python. Can anyone help to solve this please?any help would be much appreciated. And please if my question … -
Django Allauth - allow to sign up again if email is unverified
Suppose, user A tries to sign up with an email not of their own (user's B email). He fails to verify it and hence fails to sign in. Some time later user B encounters the site and tries to sign up, but they fail as well with a message "A user is already registered with this e-mail address." From what I see in admin site, it is true, the user instance is actually created, even though the email is unverified. Is there a way to easily allow user B to sign up (i.e. overwrite the unverified user instance)? Or what is the standard way of dealing with this situation? -
change password in django rest framework
I am working on change password function for an API. My code runs fine locally. The problem is that when testing in postman I have to connect it using the login token. But in login, I have two passwords refresh and access. How should I configure Postman to give me access? I was advised to use Bearer and accept allow_classes = [permissions.IsAuthenticated] but when doing so, the login stops working and still cannot give access to password change. -
Retrieve stripe session id at success page
I am using stripe with django and I want to pass some information I received from the checkout session to success page. After reading the documentation https://stripe.com/docs/payments/checkout/custom-success-page#modify-success-url I modified success url to MY_DOMAIN = 'http://127.0.0.1:8000/orders' success_url=MY_DOMAIN + '/success?session_id={CHECKOUT_SESSION_ID}', cancel_url=YOUR_DOMAIN + '/cancel/', metadata={ "price_id": price_id, } ) def Success(request): session = stripe.checkout.Session.retrieve('session_id') return render(request, 'orders/success.html') But this gives me an error: Invalid checkout.session id: session_id If I manually put instead of "session_id" the actual id that is printed in the url everything works fine. So my question is what should I write instead of 'session_id' in order to retrieve the session? -
Accessing UserProfile data from foreign key related Post
I am currently working on a little django app, the app is like a social media app. User can post, like and comment. I recently created the User Profiles. Which I can now see the user for that user profile in my view, but I cant seem to dig into the Posts that may be related to the UserProfile. what I am trying to do is in my view of HTML, I want to be able to get the post from the userprofile and the comment, and likes. But I have tried everything and nothing works. Currently in my HTML view I have rendered {{ profile.user }} and it displays the users name, but If I try profile.user.post or profile.user.comments I get nothing. Here is some code to show where I am at. Any help would be much appreciated. Profile View. def profile(request): profile = get_object_or_404(UserProfile, user=request.user) template = 'profiles/profile.html' context = { 'profile': profile, # 'posts': posts } return render(request, template, context) Profile Model from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class UserProfile(models.Model): """ A user profile model to link posts and likes """ user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") def … -
Django: EmailMessage encode the subject in base64 when translated and contains non US-ASCII characters
The usual behavior of the EmailMessage class regarding its subject is to keep it as it is if i contains only US-ASCII characters and to encode it as quoted-printable if it contains non US-ASCII characters. That works well and avoid our emails to be considered as pishing by antispam from email servers But in the specific context of translations there is a bug -> if the subject of an email is translated into another language (through the built-in django translations tools) and contains non US-ASCII characters, by an mechanism I didn't catch, the subject is encoded as base64 and not quoted-printable. This results in being considered as spam by the email servers (tested on Gandi and Gmail)... I submitted a ticket on https://code.djangoproject.com/ Do you have any idea of the mechanism that leads to this encoding in base64 instead of quoted-printable when we translate the subject of a mail ? -
I am getting this IntegrityError at /registration/ NOT NULL constraint failed: bankapp_registration.date_of_birth error
models.py from django.db import models # Create your models here. class Registration(models.Model): bank_ac = models.CharField(max_length=64) first_name = models.CharField(max_length=64) last_name = models.CharField(max_length=64) user_name = models.CharField(max_length=64) mobile_number = models.CharField(max_length=10) email = models.EmailField() password = models.CharField(max_length=18) date_of_birth = models.DateField(max_length=64) address = models.CharField(max_length=160) pin_code = models.IntegerField() views.py from django.shortcuts import render from bankapp.forms import RegistrationForm, LoginForm from bankapp.models import Registration from django.http import HttpResponse # Create your views here. def Home(request): return render(request, 'home.html') def RegistrationView(request): if request.method == 'POST': rform = RegistrationForm(request.POST) if rform.is_valid(): bac = request.POST.get('bank_ac') fname = request.POST.get('first_name') lname = request.POST.get('last_name') uname = request.POST.get('user_name') mnumber = request.POST.get('mobile_number') email = request.POST.get('email') password = request.POST.get('password') dob = request.POST.get('date_of_birth') address = request.POST.get('address') pin_code = request.POST.get('pin_code') data = Registration( bank_ac = bac, first_name = fname, last_name = lname, user_name = uname, mobile_number = mnumber, email = email, password = password, date_of_birth = dob, address = address, pin_code = pin_code ) data.save() rform = RegistrationForm() return render(request,'Registration.html', {'rform':rform}) else: return HttpResponse('User Entered invalid data') else: rform = RegistrationForm() return render(request,'Registration.html', {'rform':rform}) def LoginView(request): sform = LoginForm() if request.method == "POST": sform = LoginForm(request.POST) if sform.is_valid(): uname = request.POST.get('user_name') pwd = request.POST.get('password') print(uname) print(pwd) user1 = Registration.objects.filter(user_name=uname) password1 = Registration.objects.filter(password=pwd) if user1 and password1: return redirect('/') else: … -
Django datatable server side processing tutorial
I am using Django and there are lots of data in my table which takes times to load. Therefore, i would like to utilize enable server side processing. Is there a tutorial i can follow you may suggest. I tried to employ the datatable serverside and rest framework POST option as mentioned here. However, i could not utilize it because i am missing an intuitive understanding of the concept. If there would be any tutorial for me to follow i would like to know. Thanks for your attention. -
HTML Input Tage Values not saving in SQLite Database - Django
I am trying to save data from HTML Form to SQLite database. My database is connected to my app and project. I am able to enter from Django Admin, but my values from Input tag are not going in database. Views.py def add_record(request): if request.method == 'POST': ref_no = request.POST.get('ref_no') token_no = request.POST.get('token_no') agent_name = request.POST.get('agent_name') trip_no = request.POST.get('trip_no') date = request.POST.get('date') vehicle_no = request.POST.get('vehicle_no') bora = request.POST.get('bora') katta = request.POST.get('katta') plastic = request.POST.get('plastic') farmer_name = request.POST.get('farmer_name') farmer_address = request.POST.get('farmer_address') farmer_mob = request.POST.get('farmer_mob') gross_weight = request.POST.get('gross_weight') tier_weight = request.POST.get('tier_weight') net_weight = request.POST.get('net_weight') bora_weight = request.POST.get('bora_weight') suddh_weight = request.POST.get('suddh_weight') loading = request.POST.get('loading') unloading = request.POST.get('unloading') unloading_point = request.POST.get('unloading_point') dharamkanta_man = request.POST.get('daramkanta_man') rate = request.POST.get('rate') bardana = request.POST.get('rate') gross_total = request.POST.get('gross_total') deduction = request.POST.get('deduction') kanta = request.POST.get('kanta') hemali = request.POST.get('hemali') our_vehicle_rent = request.POST.get('our_vehicle_rent') agent_commission = request.POST.get('agent_commission') other_amt = request.POST.get('other_amt') other_remarks = request.POST.get('other_remarks') advance = request.POST.get('advance') net_total = request.POST.get('net_total') var_datasave = paddy_purchase(ref_no=ref_no, token_no=token_no, agent_name=agent_name, trip_no=trip_no, date=date, vehicle_no=vehicle_no, bora=bora, katta=katta, plastic=plastic, farmer_name=farmer_name, farmer_address=farmer_address, farm_mob=farmer_mob, gross_weight=gross_weight, tier_weight=tier_weight, net_weight=net_weight, bora_weight=bora_weight, suddh_weight=suddh_weight, loading=loading, unloading=unloading, unloading_point=unloading_point, dharamkanta_man=dharamkanta_man, rate=rate, bardana=bardana, gross_total=gross_total, deduction=deduction, kanta=kanta, hemali=hemali, our_vehicle_rent=our_vehicle_rent, agent_commission=agent_commission, other_amt=other_amt, other_remarks=other_remarks, advance=advance, net_total=net_total ) var_datasave.save() messages.success(request, 'Record saved successfully.') return redirect('index') return render(request, 'add.html') Models.py class paddy_purchase(models.Model): ref_no = models.IntegerField(primary_key='true') token_no = … -
django View - 'Comment' object has no attribute 'comments'
I'm trying to get my comments to be deleted but when I run the code the following error shows up: my comment_delete views: class CommentDelete(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Comment template_name = 'comment_delete.html' success_url = reverse_lazy('article_list') def test_func(self): obj = self.get_object() return obj.comments == self.request.user models.py Comment model: class Comment(models.Model): article = models.ForeignKey( Article, on_delete=models.CASCADE, related_name='comments', ) name = models.CharField(max_length=140) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('article_list') -
broken django production webpage
I cannot figure out why only one webpage in django production server is broken. The same webpage renders as expected on the development server. Django renders the webpage partially. The script files are executed partially. This is very confusing and I don't know where to look. All the webpages render and execute script files as expected, except for one. Please help static settings: STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = 'media/' TEMP_ROOT = os.path.join(BASE_DIR, 'temp/') TEMP_URL = 'temp/' -
Django How to do I search for a model data in HTML?
I have the following classes in my models.py file. class Resident(models.Model): house_number = models.CharField(max_length=100,unique=True,primary_key=True) name = models.CharField(max_length=100) contact_number = PhoneNumberField() def __str__(self): return self.house_number + " : " + self.name class Balance(models.Model): residents = models.OneToOneField(Resident, on_delete=models.CASCADE, primary_key=True) date = models.DateTimeField(default=timezone.now) previous_balance = models.DecimalField(max_digits=1000, decimal_places=2 , null=True) transaction = models.DecimalField(max_digits=1000, decimal_places=2, null=True) final_balance = models.DecimalField(max_digits=1000, decimal_places=2, null=True, editable=False) def save(self, *args, **kwargs): self.final_balance = self.previous_balance + self.transaction return super().save(*args, **kwargs) def __str__(self): return self.residents.name + " : " + str(self.final_balance) class Transaction(models.Model): transaction_id = models.UUIDField(primary_key=True,default=uuid.uuid4(), editable=False,unique=True) residents = models.ForeignKey(Resident, on_delete=models.CASCADE) created = models.DateTimeField(blank=True) transaction_Amount = models.DecimalField(max_digits=1000, decimal_places=2) date = models.DateTimeField() category_choices = ( ('Monthly-Bill', 'Monthly-Bill'), ('Cash', 'Cash'), ('Transfer', 'Transfer'), ('EFT', 'EFT'), ) category = models.CharField(max_length = 13 ,choices = category_choices, default = 'Monthly-Bill') def save(self, *args, **kwargs): if self.transaction_id == "": self.transaction_id = generate_code() if self.created is None: self.created = timezone.now() try: last_bal = Balance.objects.filter(pk = self.residents).get() except Balance.DoesNotExist: Balance.objects.create(residents = self.residents, date=self.date, previous_balance=Decimal.from_float(0.00), transaction=self.transaction_Amount) else: last_bal.date = date=self.date last_bal.previous_balance = last_bal.final_balance last_bal.transaction = self.transaction_Amount last_bal.save() return super().save(*args, **kwargs) def __str__(self): return str(self.transaction_id) + " : " + self.residents.name I would like to know how can I create a dropdownlist using the Resident.name to search/filter for a particular Transaction in html? … -
django: populate multiple image upload with initial data
I have an image form field that accepts multiple images like so: images = forms.ImageField(widget=forms.ClearableFileInput(attrs={'class': 'form-control', 'multiple': True}), required=False) Now when you use a ClearableFileInput with an ImageField that accepts one image and populate it with initial data, it renders as something like this: I am wondering if it is possible to achieve a similar result with an ImageField that accepts multiple files? I.e. is it possible to populate the above field with initial data?