Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django's ModelMultipleChoiceField failing to add foreing keys ids
I'm trying to save a model from the Django's admin using forms: Here are the models.py: class Availability(models.Model): """Model for the availability table.""" availability_id = models.AutoField(primary_key=True) schedule = models.ForeignKey( AdventureSchedule, on_delete=models.CASCADE ) available_guests = models.PositiveIntegerField(null=True, blank=True) date = models.DateField(auto_now=False, auto_now_add=False) price = models.DecimalField(max_digits=6, decimal_places=2, null=True) discount = models.DecimalField(max_digits=6, decimal_places=2) status = models.CharField(max_length=50, default='Available') created = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) class Meta: """Availability model Meta.""" verbose_name_plural = "2.3 - Availability" def __str__(self): return self.date.strftime("%B %d, %Y") class Reservations(models.Model): """Model for the reservations table.""" reservation_id = models.AutoField(primary_key=True) availability = models.ManyToManyField(Availability) user = models.ForeignKey(BaseUser, on_delete=models.PROTECT) num_guests = models.IntegerField() num_military = models.IntegerField() num_youth = models.IntegerField() price = models.FloatField() status = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) class Meta: """Reservations model Meta.""" verbose_name_plural = "Reservations" The forms.py: class ReservationsAdminForm(forms.ModelForm): """ModelForm for the reservations model.""" class Meta: model = Reservations exclude = [] availability = forms.ModelMultipleChoiceField( queryset=Availability.objects.all(), required=False, widget=FilteredSelectMultiple('availability', False) ) def __init__(self, *args, **kwargs): # Do the normal form initialisation. super(ReservationsAdminForm, self).__init__(*args, **kwargs) # If it is an existing reservation (saved objects have a pk). if self.instance.pk: # Populate the availability field with the current reservation. self.fields['availability'].initial = self.instance.availability_set.all() def save_m2m(self): # Add the availability to the reservation. self.instance.availability_set.set(self.cleaned_data['available_dates_select']) def save(self, *args, **kwargs): # … -
How to get the response of Firebase Messaging in django (FCM-DJANGO)
I'am trying to get the response errors from Firebase_Admin in my django application, because some users are not reciving the notifications, but when I use the code below I only recive a FirebaseResponseDict() with a batchResponse, the registration_ids_sent and deactivated_registration_ids inside for example: FirebaseResponseDict(response=<firebase_admin.messaging.BatchResponse object at 0x053E124>, registration_ids_sent=['...','...','...'],deactivated_registration_ids=[] I need the error detail to know why some users are not reciving push notifications I need the error detail to know why some users are not reciving push notifications This is my Code: ` devices.send_message(Message(webpush=WebpushConfig(notification=WebpushNotification(title=noticia.titulo, body=noticia.resumo, image=noticia.capa.url, icon=icone), fcm_options=WebpushFCMOptions(link='https://site/'+str(id))))) ` any help will be helpfull -
How to save history from django-simple-history in different database?
i'm new with django and currently i'm trying to implement django-simple-history in my project, but i found a problem, i want to save my object in the default database and the history in a different database, i found that i can indicate the history model to not use the main database like this: history = HistoricalRecords(use_base_model_db=False) But i can't find any information about how to achive that I know that I can save the object in a specific database like this: obj.save("database_name") or select which database to use: poll = Poll.objects.using('other').create(question='Question 1') I know that only calling save() will store the object in the default database but i don't know how to save only the historical object in a different database. Anyone can help me with this? -
Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))
I want to see that some data will come from an array through the checkbox. But when I select such an error is showing! {groupList && groupList.length > 0 && ( <div className="form-check form-check-inline"> {groupList.map((group) => ( <div> <input className="form-check-input" type="checkbox" id={group.id} value={group.id} onChange={(e) => { setGroups( Array.from( e.target.options, (item) => item.value ) ); }} /> <label className="form-check-label" htmlFor={group.id}> {group.name} </label> </div> ))} </div> )} How to solve? Thanks in advance. -
How to translate this dataframe using Pandas [duplicate]
I have a panda DataFrame that looks like this: Name Time Court 0 Smith 08:00 AM 1 1 Smith 08:30 AM 1 2 Smith 09:00 AM 1 3 Smith 09:30 AM 1 4 Smith 10:00 AM 1 5 Smith 10:30 AM 1 6 Smith 08:00 AM 2 7 Smith 10:30 AM 2 8 Kissinger 12:00 PM 3 9 Kissinger 09:30 AM 4 10 Kissinger 10:00 AM 5 11 Kissinger 09:30 AM 6 etc I want it to look like this, where the Court# is the header and times are the index: 1 2 3 4 5 6 08:00 AM Smith Smith 08:30 AM Smith 09:00 AM Smith 09:30 AM Smith Kissinger Kissinger 10:00 AM Smith Kissinger 10:30 AM Smith Smith 11:00 AM 11:30 AM 12:00 PM Kissinger 12:30 PM etc I've tried many things but this is beyond my knowledge level. Thanks for your help in solving this problem! -
Regex for URL with specified Domain or a signed URL
I want to match a url to replace it on demand in Python. the url looks like: https://storage.googleapis.com/icontent/media/2022-12-21%2.jpg?Expires=16344&AccessId=icontent-web.gservice.com&Signature=[alplanumeric characters] anyother url that isnt this way should not match. For now, I'm using a general url regex and filtering based on the domain name. regex I'm using is : https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*) i want to replace this inside the src attributes and update the expired url on demand. Any help would be appreciated. Thanks . -
Celery beat PeriodicTask max executions
Im trying to put max executions to my PeriodicTask with IntervalSchedule. I know total_run_count but, ¿how can use it to put max executions to my PeriodicTask? @receiver(post_save, sender=AutoTask) def create_periodic_task(sender, instance, **kwargs): interval = IntervalSchedule.objects.get_or_create(every=instance.every, period=instance.periodicity)[0] PeriodicTask.objects.create(name=instance.title, task="create_autotask", start_time=instance.creation_date, total_run_count=instance.repetitions, interval=interval) I coded this, but, in this case, I can configure the interval (example : each 2 days ), but... how can I limitate the repetitions? Ty -
Getting a django.utils.datastructures.MultiValueDictKeyError using ajax
I am trying to use the ajax post function to post data from my contact form in one of my templates. However, I am getting a 'django.utils.datastructures.MultiValueDictKeyError' when I make the request. The error is a server error and it is displayed as shown django.utils.datastructures.MultiValueDictKeyError: 'name' It is being triggered in the view.py folder on the line with the code name = request.POST['name'] Here is my model for the message: class Message(models.Model): name = models.CharField(max_length=255) email = models.CharField(max_length=255) content = models.TextField(max_length=10000) created_at = models.DateTimeField(auto_now_add=True) This is my view.py: def save_message(request): if request.method=='POST': name = request.POST['name'] email = request.POST['email'] content = request.POST['content'] Message.objects.create( content = content, name = name, email = email ) messages.success(request, f'Your message has been sent. Expect a response soon!') return JsonResponse({'bool':True}) This is the form in the index template {% csrf_token %} <form class="contactForm" id="contactForm"> <div class="form-floating"> <input class="form-control" class="message-name" id="name" type="text" placeholder="Enter your name..." /> </div> <div class="form-floating"> <input class="form-control" class="message-email" id="email" type="email" placeholder="Enter your email..." /> </div> <div class="form-floating"> <textarea class="form-control" id="message" class="message-text" placeholder="Enter your message here..."></textarea> </div> <br /> <button class="btn btn-primary text-uppercase save-message" id="submitButton" type="submit">Send</button> </form> And this is my ajax: {% block script %} <script> $(document).ready(function(){ // This is for the post … -
How to save Mapbox routes in Django Model
I have an html page with a form and Mapbox. Below is a picture of what it looks like. I want the user to fill out a form and then plot a route on the map (see screenshot). Both the data of this form and the route itself were saved to the database. When filling out the form on the left, everything is successfully saved to the database. But I have a question, how to save the routes that I build on the Mapbox map. I checked through the Network in the browser inspector, and the API itself creates the Mapbox request. But here's how to save it to my table... For example I have a table Route and the columns are id, latitude and longitude. Perhaps tell me in which direction to think, tk. I broke my head that how to pull this data. Maybe some project code will help you. django views.py: def getForm(request): form = RouteForm() if request.method == 'POST': form = RouteForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('home') return render(request, 'routes_form/route_form.html', {'form': form}) This question is rather for those who have worked with Mapbox or know something about it. P.S. I'm still just learning and I just … -
How to specify postgres DB parameters during Github Action Python build for Azure?
I have a Django web application I'm trying to deploy to Azure. I'm following this tutorial on how to set up the project. During the build I'm trying to run migrations on the DB, with the following command: jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python version uses: actions/setup-python@v1 with: python-version: '3.10' - name: Create and start virtual environment run: | python -m venv venv source venv/bin/activate - name: Install dependencies run: pip install -r requirements.txt - name: Make migrations and run migrations run: python ./appname/manage.py migrate However, this step fails with the following error: django.db.utils.OperationalError: could not translate host name "$.***.database.azure.com" to address: Name or service not known I have inserted the DBNAME, DBHOST, etc. values shown on the screenshot as app secrets into github, so I'm really not sure why it is not finding them. Can anyone point out please what am I missing here? -
WebSocket connection error when creating a chat application with Django
I am working on a chat application which is like a whatsapp web clone. I have been stuck dealing with websocket connection as it cannot connect to the specified address. I am getting the error WebSocket connection to 'ws://127.0.0.1:8000/ws/2/' failed:. The url specified is because I am using the user id to create a room name in the consumers.py file. Here is part of the consumers.py file: class PersonalChatConsumer(AsyncWebsocketConsumer): async def connect(self): my_id = self.scope['user'].id other_user_id = self.scope['url_route']['kwargs']['id'] if int(my_id) > int(other_user_id): self.room_name = f'{my_id}-{other_user_id}' else: self.room_name = f'{other_user_id}-{my_id}' self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) Also here is part of the javascript file handling the websocket connection: const id = JSON.parse(document.getElementById('json-username').textContent); const message_username = JSON.parse(document.getElementById('json-message-username').textContent); const socket = new WebSocket( 'ws://' + window.location.host + '/ws/' + id + '/' ); The error message in the console of VsCode states Not Found: /ws/2/. Also here is the urls file: urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include(('accounts.urls', 'accounts'), namespace='accounts')), path('', index, name='home'), path('<str:username>/', chatPage, name='chat'), ] Any help will be highly appreciated. Thanks -
Django upload csv to DB via template with function
I made a function with "runscript" on Django. I wanna know how can I upload a CSV file via a template with my function. this is my function: def run(): df = pd.read_csv("scripts/Combination.csv", dtype=str) df = df[pd.isnull(df["id"])] def sub_budget_owner_found(v_BO, v_SBO): try: Employee.objects.get_or_create(name=v_BO) v_BO_obj = Employee.objects.get(name=v_BO) except: v_BO_obj = Employee.objects.get(name="99999 No Budget Owner") try: Employee.objects.get_or_create(name=v_SBO) v_SBO_obj = Employee.objects.get(name=v_SBO) except: v_SBO_obj = Employee.objects.get(name="99998 No Sub Budget Owner") return SubBudgetOwner.objects.get_or_create( budget_owner=v_BO_obj, sub_budget_owner=v_SBO_obj ) for i, row in df.iterrows(): v_subsidiary = row["Subsidiary"] v_department = row["Department"] v_account = row["Account"] v_sub_budget = row["Sub Budget"] v_budget_owner = row["Budget Owner"] v_sub_budget_owner = row["Sub Budget Owner"] Combination.objects.get_or_create( subsidiary=Subsidiary.objects.get_or_create(name=str(v_subsidiary))[0], department=Department.objects.get_or_create(name=str(v_department))[0], account=Account.objects.get_or_create(name=str(v_account))[0], sub_budget=SubBudget.objects.get_or_create(name=str(v_sub_budget))[0], budget_owner=sub_budget_owner_found(v_budget_owner, v_sub_budget_owner)[0], ) print(i, row) I use Django view classes. The purpose is to upload new data via CSV file in the GUI. Thanks a lot -
Issue with django, react and nginx server with docker
I am new with nginx and trying to understand how its works. I build and dockerize a website using react for the frontend and django for backend and serving both react and django api with nginx. But when I reach localhost which should serve react app, everything works well. The problem appear when I want to access for example localhost/docs or localhost/admin which should be serve by gunicorn and django. I always obtain bad request (400) In my settings.py I have ALLOWED_HOSTS = [] ALLOWED_HOSTS.extend( filter( None, os.environ.get('ALLOWED_HOSTS', '').split(' '), ) ) STATIC_URL = '/static/static/' MEDIA_URL = '/static/media/' MEDIA_ROOT = '/vol/web/mediafiles' STATIC_ROOT = '/vol/web/staticfiles' my .env file DB_NAME=dbname DB_USER=rootuser DB_PASS=dbpassword DJANGO_SECRET_KEY=secretkey_for_production_environment DJANGO_ALLOWED_HOSTS=localhost Here is docker-compose-prod.yml file version: "3.9" services: db: image: postgres:13-alpine container_name: db-prod-c restart: always volumes: - db-prod:/var/lib/postgresql/data environment: - POSTGRES_DB=${DB_NAME} - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASS} backend: build: context: ./backend dockerfile: Dockerfile.prod #restart: always image: api-prod-i:django-prod container_name: api-prod-c user: root volumes: - mediafiles:/vol/web/mediafiles - staticfiles:/vol/web/staticfiles environment: - DB_HOST=db - DB_NAME=${DB_NAME} - DB_USER=${DB_USER} - DB_PASS=${DB_PASS} - SECRET_KEY=${DJANGO_SECRET_KEY} - ALLOWED_HOSTS=${DJANGO_ALLOWED_HOSTS} expose: - 8000 depends_on: - db # networks: # - django-network frontend: build: context: ./frontend dockerfile: Dockerfile #restart: always image: client-prod-i:django-prod container_name: client-prod-c volumes: - react-build:/frontend/build depends_on: - backend proxy: build: context: … -
Cannot upload images to S3 from Django backend and Nextjs frontend vercel
I have an e-commerce site built with Django and nextjs. Previously it was hosted on hostinger but recently I moved the API backend to AWS Lambda and the frontend to vercel. I'm storing the product images in S3. The problem I;m facing is after the migration, I'm not able to upload the images from my nextjs frontend. I have tried uploading the images from postman and Django admin panel and it worked. It just not works from the nextjs frontend. Here is the error: An error occurred (400) when calling the HeadObject operation: Bad Request I'm using django-storages to upload my images to S3. I'm using FormData to send images from frontend to backend. frontend submit function: function submit() { setIsLoading(true); var myHeaders = new Headers(); myHeaders.append("Authorization", `Bearer ${session?.token?.access}`); myHeaders.append("Cookie", "django_language=en"); var formdata = new FormData(); formdata.append("name", name); formdata.append("desc", desc); formdata.append("length", length); formdata.append("height", height); formdata.append("width", width); formdata.append("measure", measurements); formdata.append("origin", origin); formdata.append("signed", signed); formdata.append("reproduce", reproduce); formdata.append("reproduce_days", reproduce_days); formdata.append("image", img); formdata.append("reg_price", price); formdata.append("cat", category); formdata.append("year", year); formdata.append("newcat", otherCategory); formdata.append("newsubcat", otherSubCategory); formdata.append("newmedium", otherMedium); formdata.append("subcat", subCategory); formdata.append("medium", medium); formdata.append("orientation", orientation); formdata.append("stock_quantity", quantity); var requestOptions = { method: "POST", headers: myHeaders, body: formdata, redirect: "follow", }; fetch( `${API_URL}/profile/vendor/${session?.token?.user?.id}/add-product/?curr=INR`, requestOptions ) .then((response) => response.text()) .then((result) => … -
How i save multiple request.POST.get() in form.save()
I wanna get data with request.POST.get() and then save in form.save(). How i can solve that? def example(request): form = addform() if (request.method == 'POST'): form = addform(request.POST) question = request.POST.get('question') answer = request.POST.get('answer') explain = request.POST.get('explain') if (form.is_valid()): form.save() # i wann save all (question + answer + explain) here in form. context = {'form': form} return render(request, 'Example_fragenkatalog.html', context) I hope someone can help me! Thank you! -
Django bulk_create() with models' fields having custom validators
In my Django application, I am using bulk_create(). For one of the fields in a target model I have assigned a set of validators to restrict the allowed value to uppercase letters (alphabets) and to a fixed length of "3", as shown below: class Plant(models.Model): plant = models.CharField(primary_key=True, max_length=4, ... plant_name = models.CharField(max_length=75, ... plant_short_name = models.CharField(max_length=3, validators=[... # rest of the fields ... I am restricting field plant_short_name to something like CHT for say, Plant Charlotte. Using the source file (.csv) I am able to successfully create new instances using bulk_create, however I find that the data get saved even with field plant_short_name's value being different. For example, if I use the source as: plant,plant_name,plant_short_name 9999,XYZ Plant,XY the new instance still gets created although the length of (string) value of field plant_short_name is only 2 (instead of 3 as defined in the validators). If I am to use an online create function (say, Django CreateView), the validators work as expected. How do I control / rstrict the creation of model instance when a field value of incorrect length is used in the source file? -
deference between request.meta and request.headers In django
what is the deference between these ? I see in the django doc that we can get content-length in meta and header atrebute in HttpResponse class. so what is the difference between request.meta and request.headers? -
forward and backward in ajax
I have a page with products that are filtered through ajax. Also the url changes via pushState. But when you click the backward and forward buttons in the browser, nothing happens, only the url changes. How to handle the clicks of these buttons? -
How to extract two values from list in python?
I'm using python3 and and i have data set. That contains the following data. I'm trying to get the desire value from this data list. I have tried many ways but unable to figure out how to do that. slots_data = [ { "id":551, "user_id":1, "time":"199322002", "expire":"199322002" }, { "id":552, "user_id":1, "time":"199322002", "expire":"199322002" }, { "id":525, "user_id":3, "time":"199322002", "expire":"199322002" }, { "id":524, "user_id":3, "time":"199322002", "expire":"199322002" }, { "id":553, "user_id":1, "time":"199322002", "expire":"199322002" }, { "id":550, "user_id":2, "time":"199322002", "expire":"199322002" } ] # Desired output # [ # {"user_id":1,"slots_ids":[551,552,553]} # {"user_id":2,"slots_ids":[550]} # {"user_id":3,"slots_ids":[524,525]} # ] I have tried in the following way and obviously this is not correct. I couldn't figure out the solution of this problem : final_list = [] for item in slots_data: obj = obj.dict() obj = { "user_id":item["user_id"], "slot_ids":item["id"] } final_list.append(obj) print(set(final_list)) -
Access Foreign Key count in Django Template
I have two models: Farm and Animal with a ForeignKey relation. Each Farm contains x animals. I'm doing a table in the frontend with a for loop of each farm. How can I show the number of animals in each farm? models: class Farm(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, default=None) square_meter = models.IntegerField(blank=True, null=True) friendly_name = models.CharField(max_length=24, blank=True) kml = models.FileField(upload_to=user_directory_path_kml, null=True, blank=True) class Animal(models.Model): class Meta: verbose_name_plural = "Animals" farm = models.ForeignKey(Farm, on_delete=models.CASCADE, blank=True, null=True, default=None) name = models.CharField(max_length=24, blank=True) datetime = models.DateTimeField(blank=True, null=True, default=datetime.now) tracking = models.BooleanField(default=False) kg = models.IntegerField(blank=True, null=True) template: {% for farm in farms %} <tr> <th scope="row">{{forloop.counter}}</th> <td>{{farm.friendly_name}}</td> <td>{{farm.square_meter}}</td> <td>{{farm. }}</td> # Here I want animal count </tr> {% endfor %} -
How to call HTML page as a popup from another HTML page using Django
I am working on Django project where i need pop up the HTML when i click the button. Let me explain, when ever user click the button it should open another HTML as a popup there user can upload the files and download the sample files. Could you please help me on the issue Here is my code below, HTML Button - <button data-href='{% url "employeeBulkUpload" companydetail.id %}' id="uploadEmployees" title="Upload Employees" class="btn btn-blue mr-2 px-3 d-block w-100 text-95 radius-round border-2 brc-black-tp10"><i class="fa fa-upload"></i></button> $(document).ready(function () { $('#uploadEmployees').initDialog({'url': '{% url "employeeBulkUpload" companydetail.id %}', 'title': 'Upload Employees'}); }); -
How to display related One to Many Instances in ListView?
I want to display all belonging Instances of model Report referenced to model Module referenced to model Course. Therefore I implemented three Models related via Foreignkey. class Course(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=200, blank=True, null=True) class Module(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=200, blank=True, null=True) course_id = models.ForeignKey( Course, null=True, on_delete=models.SET_NULL, related_name="modules", default=uuid.uuid4, ) class Report(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=200, blank=True, null=True) module_id = models.ForeignKey( Module, null=True, on_delete=models.SET_NULL, related_name="reports", default=uuid.uuid4, ) I want to display model Module referenced to model Course in CourseDetailView(DetailView): Here is what I implemented: class CourseDetailView(DetailView): model = Course context_object_name = "course" template_name = "course/course_detail.html" fields = ["title", "description"] def get_context_data(self, **kwargs): context = super(CourseDetailView, self).get_context_data(**kwargs) context["courses"] = Course.objects.filter(pk=self.kwargs.get("pk")) return context and I get the instance belonging to itsself. If I change the context to: context["modules"] = Module.objects.all() and iterate over modules in course_detail.html: {{ course.description|safe }} {% for module in modules %} <div> <h2><a href="{{ module.get_absolute_url }}">{{ modules.title }}</a></h2> </div> {% endfor %} I'll get all instances of Module but I want only the ones related to the specific Course. I know I have to filter context["modules"] but I don't know how to do it. Due … -
Creating Integer Range from multiple string math expressions in python
I have a problem in a project and I've searched the internet high and low with no clear answer. How can i convert math expressions As 3x + 5y >= 100 And x,y < 500 Into a range of x and range of y to be used as ristriction in a math problem, Ex: f = x^2+4y The end result is to find the largest answer using genetic algorithms where x and y are ristricted in value. Tried sympy and eval with no luck Searched every and found only a few helpful but not enough resources I need just to translate the user input to the code for the genetic algorithm to use. -
Django admin upload multiple images in 1 form
I dont want to use inlines so I figured I want to upload a bunch of images at the same time. Now I've been struggling for an entire day to get it working but it doesn't for some reason. My first code: Model class LaptopInfoImages(models.Model): laptop_info = models.ForeignKey(LaptopInfo, on_delete=models.CASCADE) image = models.ImageField(upload_to=images_directory) admin class LaptopInfoImagesForm(forms.ModelForm): image = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = LaptopInfoImages fields = '__all__' def save(self, commit=True): instance = super().save(commit=False) for image in self.cleaned_data['image']: image_obj = LaptopInfoImages(laptop_info=instance.laptop_info, image=image) image_obj.save() if commit: instance.save() return instance This gives me the error: AttributeError: 'bytes' object has no attribute '_committed' So I changed the code to: admin class LaptopInfoImagesForm(forms.ModelForm): image = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = LaptopInfoImages fields = '__all__' def save(self, commit=True): instance = super().save(commit=False) for image in self.cleaned_data['image']: # Convert the image to a BytesIO object bytes_io = BytesIO(image) # Create an InMemoryUploadedFile from the BytesIO object in_memory_file = InMemoryUploadedFile( bytes_io, None, 'image.jpg', 'image/jpeg', len(image), None ) # Save the image to the LaptopInfoImages model image_obj = LaptopInfoImages(laptop_info=instance.laptop_info, image=in_memory_file) image_obj.save() if commit: instance.save() return instance It doesnt give me any errors but it is uploading 9332 laptop info imagess and the images don't work. -
How to clean and save multiple instances one after one in Django using clean and save methods?
I noticed that when using Django admin and whenever select/change multiple instances and click on save button (for example see the below image, it's not directly related to the code below), Django will clean/validate all instances and then save them one by one. is this how things are working in Django or the process should be clean and then save the instance before repeat same process with the next instance? because when trying to set is_active value to be true for multiple instances, it passing the clean method condition without shown the error message that tells should only one instance be selected as true and that's correct cause no one of the instances have is_active as true in the database yet But if I click the save button again will show the error message. models.py: class SupplierAddress(models.Model): """Model to create supplier's address instances""" class Meta: """Customize django default way to plural the class name""" verbose_name = 'Supplier Address' verbose_name_plural = 'Supplier Addresses' constraints = [ models.UniqueConstraint( fields=['supplier', 'address'], name='supplier_address_unique_appversion' ) ] # Define model fields. supplier = models.ForeignKey( 'Supplier', on_delete=models.CASCADE, related_name='supplier_addresses_supplier' ) address = models.ForeignKey( 'Address', on_delete=models.CASCADE, related_name='supplier_addresses_address' ) is_active = models.BooleanField(default=False) def clean(self): """Restrict the add/change to model fields""" …