Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django UUID Field does not autocreate with new entry
I just added a new model where I want to use a UUID for the first time. I run django 3.1.3 on python 3.8.10. Found some questions about this and I am quite certain I did it according to those suggestions. However, when I add an entry to that model (in phpmyadmin web-surface) the UUID is not being added, it just stays empty. However when I create an other one I get the error, that the UUID Field is not allowed to be the same as somewhere else (both empty) wich means at least the unique=True does work. Another thing to mention is, when I create the field using VSCode, normally those fieldnames are being auto-completed, however it is not the case with this one. Thought this might give you a hint what is going on. My model looks like this: from django.db import models import uuid class MQTTTable(models.Model): uuid = models.UUIDField(primary_key = True, default = uuid.uuid4, editable = False, unique = True) description = models.CharField(max_length= 100, default = None) clientID = models.CharField(max_length = 50, default = None) mastertopic = models.CharField(max_length = 200, default = None) -
Django form fields not rendering when grouping fields
I am using Django 4.0.3 with a bootstrap webinterface. For layout reasons I want my fields in a ModelForm to be grouped and I'm doing it with: class UserForm(ModelForm): template_name = "container/form.html" field_groups = [["email", "company"], ["last_name", "first_name"]] grouped_fields = [] class Meta: model = MyUser fields = ["email", "company", "first_name", "last_name"] __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) def group_fields(self): for group in self._field_groups: group_entry = [] for entry in group: group_entry.append(self.fields[entry]) self.grouped_fields.append(group_entry) in the view I initialize my form and the regroup the fields: def user_form(request): form = UserForm() form.group_fields() render(request, "page.html, {"form", form}) The page.html looks like this: <body> <div id="form-wrapper"> {{ form }} </div> </body> and the form.html looks like this: <form action="" method="POST">{% csrf_token %} {% for field_group in form.grouped_fields %} <div class="row"> {% for field in field_group %} <div class="col"> <label>{{ field.label }}</label> {{ field }} </div> {% endfor %} </div> {% endfor %} However the rendered fields are displayed as string representations of the field objects: Email <django.forms.fields.EmailField object at 0x7f98c00e03a0> Company <django.forms.fields.CharField object at 0x7f98c00e0250> Last name <django.forms.fields.CharField object at 0x7f98c00e0790> First name <django.forms.fields.CharField object at 0x7f98c00e10c0> Whereas a common call renders as expected a form with input fields, but not with the … -
How to filter queryset with mutiple m2m values?
I'm tryna filter Seo model here. I want to get objects that has the brand dependency and the model dependency. Code class SeoListView(generics.ListAPIView): serializer_class = SeoListSerializer def get_queryset(self) -> QuerySet: queryset = Seo.objects.all() dependencies = self.request.query_params.get('dependencies') if dependencies is not None: dependencies = [str(dep).strip() for dep in dependencies.split(',')] print(dependencies) # for dep in dependencies: # query.add(Q(dependencies__dependency__exact=dep), Q.AND) query = reduce(lambda q, dep: q & Q(dependencies__dependency__exact=dep), dependencies, Q()) queryset = queryset.filter(query) return queryset class Dependency(models.Model): dependency = models.SlugField( 'Зависимость', unique=True, help_text='Перечислите зависимости через нижнее подчеркивание. Пример: brand_model' ) def __str__(self) -> str: return f'Зависимость {self.dependency}' class Meta: verbose_name = 'Зависимость' verbose_name_plural = 'Зависимости' class Seo(models.Model): statuses = ( (1, 'Дефолтная'), (2, 'Дополнительная') ) _delimiter = SEOService().delimiter _help_text = ( f'Если вы ввели Купить {_delimiter}, а зависимость - car,' f' то после сохранения получится Купить car машину. ' f'Все {_delimiter} заменяются на соотв. им зависимости.' ) dependencies = models.ManyToManyField( Dependency, verbose_name='Зависимости', blank=True, help_text='Оставьте пустым, если это дефолтный шаблон.' ) h1 = models.CharField( 'Заголовок(h1)', max_length=200, help_text=_help_text ) title = models.CharField( 'Заголовок(title)', max_length=200, help_text=_help_text ) description = models.CharField( 'Описание', max_length=200, help_text=_help_text ) keywords = models.TextField( 'Ключевые слова', help_text=_help_text ) status = models.IntegerField('Статус', choices=statuses, blank=True, help_text='Не трогать руками', null=True) def __str__(self) -> str: return f'Настройка … -
trying to use web scrapper in my application [closed]
DevTools listening on ws://127.0.0.1:1731/devtools/browser/ffe6022f-8d1b-41a0-8ab8-b2bd80fdf8b1 [16224:17484:0517/085953.922:ERROR:device_event_log_impl.cc(214)] [08:59:53.926] USB: usb_device_handle_win.cc:1049 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F) Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\Razer\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__ return self.func(*args) File "C:\Users\Razer\Downloads\WEb scrapper\mysite\polls\views.py", line 245, in start wait.until(EC.presence_of_all_elements_located( File "C:\Users\Razer\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\support\wait.py", line 89, in until raise TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message: [9564:3800:0517/090149.183:ERROR:gpu_init.cc(481)] Passthrough is not supported, GL is disabled, ANGLE is [16224:17484:0517/085953.922:ERROR:device_event_log_impl.cc(214)] [08:59:53.926] USB: usb_device_handle_win.cc:1049 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F) Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\Razer\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__ return self.func(*args) File "C:\Users\Razer\Downloads\WEb scrapper\mysite\polls\views.py", line 245, in start wait.until(EC.presence_of_all_elements_located( File "C:\Users\Razer\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\support\wait.py", line 89, in until raise TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message: -
EntityChoiceWidget is missing a QuerySet. django-select2
I'm getting this error when using django-select2: EntityChoiceWidget is missing a QuerySet. Define EntityChoiceWidget.model, EntityChoiceWidget.queryset, or override EntityChoiceWidget.get_queryset(). and I don't know what does it mean. {% for field in form %} <div class="form-group{% if field.errors %} has-error{% endif %}"> {{ field|label_with_class:"col-sm-2 control-label" }} <div class="col-xs-4"> X {{ field|input_with_class:"form-control" }} {% for e in field.errors %}<span class="help-block">{{ e }}</span>{% endfor %} </div> </div> {% endfor %} The whole stacktrace points to the site-packages/ directory, so there might be something wrong with my package. I'm using Django 1.11 and django-select2 5.9.0. I tried upgrading django-select2 to the newest version I could use with Django 1.11 (6.3.1) and I'm still getting this error. Why can this error be happening and how can I fix it? -
How to query User model by 'custom' fields? (django.db.models.fields.related_descriptors.ReverseOneToOneDescriptor)
I extended the User model using my account app. Model Account app: from django.db import models from django.contrib.auth.models import User from departments.models import Department class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to='profile_pics', blank=True) department = models.ForeignKey( Department, on_delete=models.SET_NULL, null=True, related_name='department') def __str__(self): return self.user.username Now I need to send the count of users from the same department to my template... View: from django.contrib.auth.models import User @login_required def home(request): context = { 'title': 'Dashboard', 'department_members': 'department_members': User.objects.filter(department=request.user.account.department).count(), } return render(request, 'app/dashboard.html', context)\ department_members is always 1 even though I have more users on the same department. I figure that the problem is that User don't have department field by default, so I can't say User.account.objects.filter(department=request.user.account.department) I've tried a lot of queries and looked into django docs but I could't find the proper manner on how to retrieve this info. Anyone have the same problem? Any tips on how I can debug/create my query in a better way? Thanks to all in advance! -
Django product update / inline formsets updating a model
I am creating an E-commerce website, I'm having a problem when I'm updating images of the product, I can update the form `but I can't update the images. can you guys tell what am I doing wrong ? this is my code: views.py class ProductEditView(UpdateView): model = Product form = ProductUpdateForm fields='__all__' product_metas = ProductUpdateMetaForm template_name = 'products/update_product.html' product_meta_formset = ProductMetaInlineFormset() meta = product_metas ProductMetaInlineFormset = inlineformset_factory(Product,Image,form = ProductUpdateMetaForm ,extra=5) def form_valid(self, form): response = super(ProductEditView, self).form_valid(form) if self.request.method == 'POST': product_meta_formset = self.ProductMetaInlineFormset(self.request.POST, self.request.FILES, instance=self.object) product_meta_formset.save() return response def get_context_data(self, **kwargs): context = super(ProductEditView, self).get_context_data(**kwargs) context['product_meta_formset'] = self.ProductMetaInlineFormset(instance=self.object) return context forms.py class ProductUpdateMetaForm(forms.ModelForm): class Meta: model = Image fields = ['image', 'is_feature', ] ProductMetaInlineFormset = inlineformset_factory(Product,Image,form = ProductUpdateMetaForm ,extra=5,) update_product.html <div class="container mt-4"> <form enctype="multipart/form-data" action= "." method="POST" class="ui form"> {% csrf_token %} <div class="card"> <div class="card-body"> {{ form.non_form_errors }} {{ form.as_p }} {{ product_meta_formset.non_form_errors }} {{ product_meta_formset.management_form}} {% for form in product_meta_formset %} <div class="d-flex py-1 inline {{ product_meta_formset.prefix }}"> <div>{{form.image.label}}: {{ form.image }}</div> <div class="ml-4">{{form.is_feature.label}}: {{ form.is_feature }}</div> {% if product_meta_formset.can_delete %} <div class="ml-4">{{ form.DELETE }} {{ form.DELETE.label }}</div> {% endif %} </div> {% endfor %} </div> </div> <button type='submit' class = 'ui positive button mtop'>Update product</button> … -
Django convert model objects to dictionary in large volumes results in server timeout
I have been having a problem where a Django server takes forever to return a response. When running with gunicorn in Heroku I get a timeout, so can't receive the response. If I run locally, it takes a while, but after some time it correctly shows the site. Basically I have two models: class Entry(models.Model): #Some stuff charFields, foreignKey, TextField and ManyToMany fields #Eg of m2m field: tags = models.ManyToManyField(Tag, blank=True) def getTags(self): ret = [] for tag in self.tags.all(): ret.append(getattr(tag, "name")) return ret def convertToDict(self): #for the many to many field I run the getter return {'id': self.id, 'tags' : self.getTags(), ... all the other fields ... } class EntryState(models.Model): entry = models.ForeignKey(Entry, on_delete=models.CASCADE) def convertToDict(self): temp = self.entry.convertToDict() temp['field1'] = self.field1 temp['field2'] = self.field1 + self.field3 return temp Then I have a view: def myView(request): entries = list(EntryState.objects.filter(field1 < 10)) dictData = {'entries' : []} for entry in entries: dictData['entries'].append(entry.convertToDict()) context = {'dictData': dictData} return render(request, 'my_template.html', context) The way it was done, the dictData contains the information for all the entries that must be shown in the site. Then, this variable gets loaded into a javascript that will decide how to display the information. The view gets … -
What is the proper documentation for using django channels on azure app services?
I am trying to deploy a web app on azure app service All the http request work just fine as one would expect there just one problem none of the websockets work I am using in memory channels version 2.4.0 and django version 2.2.15 The problem is azure just can not show me proper logs that django shows when running on local server -
django: Query regarding radio buttons
The requirement is that I have a set of questions, and I want the responses to be provided by selecting a value which is rendered using radio buttons. The issue here is, say, we have: Question 1: o option 1 x option 2 o option 3 Question 2: o option 1 o option 2 o option 3 where 'o' represents un-selected options and 'x' - represents an option that has been selected. Now, when trying to check option3 under question 2 it unselects the response to the previous question i.e., Question1. Question 1: o option 1 o option 2 o option 3 Question 2: o option 1 o option 2 x option 3 How do we decouple the radio button responses for each field?? Any help would be appreciated. Thanks!! -
How to force insert custom value in datetimefield(auto_now_add=True) while object creation in Django?
I have a model Test in service A class Test(models.Model): some_field = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) I am migrating data from a different service B's model to this model (using APIs). Exposed an API in service A which reads from POST data sent from the B, and saves the data in this Test model. Sample data coming from service B data = { 'some_field': 5, 'created_at': '2013-06-26 00:14:27.260524', } Now when I save this data in the db using: obj = Test( some_field=request.POST.get('some_field'), created_at=request.POST.get('created_at'), ) obj.save() The created_at values of saved object is the current time. Not the created_at coming from the API. How to bypass this current time saving in this scenario and save the timestamp coming from the API while creating the object? -
Can I render and extract assets (3D) in browser?
I have a simple app created in Django and my problem is that I need to extract 3D assets from engine (like Unity), this are just files that contains 3D game characters and I need to render them in the browser, is there a Python library that can be integrated under a django web project and no other external web framework library like three.js? -
Image Update is happening in Django
I had used code to update the image in Django, but it doesn't resulted as expected. if request.method == "POST": data = ImageModel.objects.get(pk=id) pid = customer.objects.get(pk=id) fm = CustomerRegisteration(request.POST, request.FILES, instance=pid) if fm.is_valid(): data.image_document.delete() fm.save() This code doesn't work -
file cannot be uploaded and gone (not move to local storage) - DJANGO FORMS
i don't use models form but only form. so when i clicked button upload, the file just gone and not uploaded to my local storage. i don't know why. please help me. this is my code : def homepage(request): if request.method == "POST": form = Audio_store(request.POST, request.FILES) # form = AudioForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['record']) return render(request, "homepage.html", {'form': form}) else: return render(request, "homepage.html") def handle_uploaded_file(f): with open('mp3', 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) forms.py : from django import forms class Audio_store(forms.Form): record=forms.FileField() urls.py : urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^decode/$', views.decode), path("", views.homepage, name="upload") ] if settings.DEBUG: #add this urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) terminal my folder: -
How to render specific template if two app have same template name?
How can I render a specific template in Django? I have created three apps for my project. Each app contains a templates folder. The project structure is as follows: ├───Project ├───app1 │ ├───templates ├───app2 │ ├───templates ├───app3 │ ├───templates In my app2 and app3, I have templates with the same name. I want to render the template from app3 but the template is rendering from app2. I am using the following code. In app3.views.py return render(request, "template_name.html") -
Django System in another Project that is not web application [closed]
I am new to using Django, and I like it. I was working before with python on another project connected to Database and used CURD Methods and JSON format. My Question now can I use Django System (Models and Serializer) in this project? I think it will be better than cursor() and execute() -
how to add second page reportlab in django
my goal is to write the data in the models to a pdf file so that if it doesn't fit on the first page, it will automatically continue on to the second page. is writing me a card again and again on a sheet of code pls help me from django.shortcuts import render from django.http import HttpResponse,HttpResponseRedirect # Create your views here. from .forms import VenueForm from .models import * from django.http import FileResponse import io from reportlab.platypus import PageBreak from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import inch from reportlab.lib.pagesizes import letter def venue_pdf(request): buf = io.BytesIO() c = canvas.Canvas(buf,pagesize=letter,bottomup=0) textob=c.beginText() textob.setTextOrigin(inch,inch) textob.setFont("Helvetica",14) venues = Venue.objects.all() l = [] for i in venues: l.append(i.lname) l.append(i.fname) l.append(i.fan) l.append(i.address) l.append(i.phone) l.append(" ===================================================== ") l.append(" ") for j in range(len(l)//36+1): c.drawText(textob) c.showPage() c.save() buf.seek(0) return FileResponse(buf,as_attachment=True,filena me='east_ariza.pdf') -
Retrieve specific objects from prefetch_related query
I'm working on twitter like app and I have home view which displays tweets and retweets by current user and users who follow that user. I want to show info who retweeted this tweet for all retweets. In retweeted_by column I receive user id. Queryset for this view: def get_queryset(self): user = self.request.user tweets = Tweet.objects.filter(Q(user=user) | Q(user__in=user.followees.all())). \ annotate(action_time=F('pub_date'), retweeted_by=Value(0, output_field=BigIntegerField())). \ select_related('user').prefetch_related('likes', 'retweets', 'children', 'mentioned_users') retweets = Tweet.objects.filter(Q(tweetretweet__user=user) | Q(tweetretweet__user__in=user.followees.all())). \ annotate(action_time=F('tweetretweet__timestamp'), retweeted_by=F('tweetretweet__user')). \ select_related('user').prefetch_related('likes', 'retweets', 'children', 'mentioned_users') return tweets.union(retweets).order_by('-action_time') Template for this view renders all tweets in queryset with inclusion tag: @register.inclusion_tag('tweets/short_tweet_snippet.html', takes_context=True) def render_short_tweet(context, tweet): var_dict = { 'request': context['view'].request, 'tweet': tweet, } # Check if queryset has retweeted_by column # (i have a lot of views which display tweets, but only some show retweet info) try: retweeted_by = tweet.retweeted_by except AttributeError: return var_dict # If retweeted_by value not equal 0 if retweeted_by: # user = tweet.retweets.filter(pk=retweeted_by).get() (hits the db) # user = tweet.retweets.get(pk=retweeted_by) (hits the db) # Doesn't hits the db, but not optimized solution for user in tweet.retweets.all(): if user.pk == retweeted_by: retweeted_user = user var_dict.update(retweeted_user=retweeted_user) return var_dict The problem is when i want to get user object who retweeted specific tweet django makes … -
Django Postgresql annotate group_by (annotate) not working?
I want to query for product with details but currently i am not getting results as I want. class Product(models.Model): . . . price = models.DecimalField() url = models.URLField(max_length=255, null=True, unique=True) merchant = models.ForeignKey(Merchant, on_delete=models.DO_NOTHING) class ProductVariant(models.Model): sku = models.CharField(max_length=255) product = models.ForeignKey(Product, on_delete=models.DO_NOTHING) Query: class Detail(DetailView): model = ProductVariant template_name = "products/cpus_detail.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['cpu'] = CPU.objects.filter( model__iexact=context['object'].sku).first() merchant_products = ProductVariant.objects.filter(sku__iregex=rf"\y{context['object'].sku}\y").values('product__merchant').annotate(merchant=Count('product__merchant')) Output of the above query is: <QuerySet [{'product__merchant': 1, 'merchant': 1}, {'product__merchant': 2, 'merchant': 2}]> in above query product is grouped by merchant. And if I want to include other fields of product model: <QuerySet [{'product__merchant': 1, 'product__url': 'some url 1', 'merchant': 1}, {'product__merchant': 2, 'product__url': 'some url 2', 'merchant': 1}, {'product__merchant': 2, 'product__url': 'some url 3', 'merchant': 1}]> now in above query product is no longer grouped by merchant (3 records are returned instead of 2, even though 2 records have product__merchant: 2) what i want is: query that returns grouped records based on merchant (with product fields) -
How to get the related models first objects in a single query in Django?
class Product(models.Model): category = models.ForeignKey(Category, related_name="products_category", null=True, on_delete=models.CASCADE) sku = models.CharField(max_length=200, blank=True, null=True) class ProductVariants(DateTimeModel): name = models.CharField(max_length=200, blank=True, null=True) product = models.ForeignKey(Product, related_name="products_variants", null=True, on_delete=models.CASCADE) products = Product.objects.select_related().all() how to get all the parent model objects with their related model's first object in a single query. [0] and first() is not working. how to fetch that? -
Makemigrations/migrate in django
Could anyone help me solve this problem? I want to add data and time models in Django, but after makemigration, I got this. **You are trying to add a non-nullable field 'MeterReading_DateTime' to mdm_api without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit, and let me add a default in models.py Select an option:** -
How to export data from front Web to CSV files using jquery?
I'm practiced Python+Django edited Web, followed sample trying to export from db data into front Web and I want download CSV file. Here is my whole function. Its download a file, but it shows the for the title and not any data out. Thanks all. Views: sid search funtion def search_by_sid(request,pk=1): sdepartments = Department.objects.all() cdepartments = CDepartment.objects.all() ssid = CourseData.objects.all() if request.method == "POST": sid = request.POST.get("sid").strip() if "," in sid: course = CourseData.objects.filter(sid="NA") sids = sid.split(",") for n in sids: courses = CourseData.objects.filter(sid = n.strip()) course =course | courses else: course = CourseData.objects.filter(sid=sid).order_by("teacher") num = len(course) return render(request, "list.html") return redirect("/") donwload file function: def down_file(request): sdepartments = Department.objects.all() cdepartments = CDepartment.objects.all() ssid = CourseData.objects.all() if request.method == "POST": sid = request.POST.get("sid") dfs = CourseData.objects.filter(sid__in=['sid']).values_list("sid","name","phone","email","sdept") response = HttpResponse(content_type="text/csv") response.write(codecs.BOM_UTF8) response['Content-Disposition'] = 'attachment; filename = "Report.csv"' writer = csv.writer(response) print(writer) writer.writerow(["sid","name","phone","email","sdept"]) for sop in dfs: writer.writerow(sop) return response Templates: button function <form id="sid" action="/bysid/" method="post"> {% csrf_token %} Search:<input name="sid" size="50" placeholder="Search"> <input type="submit" value="Go Search"> <input id="btnType" type="" value="Search"> <button type="button" id="down_file" >Download Files</button> </form> js funtion: $(document).ready(function(){ $("#down_file").click(function(){ $("#btnType").val('accpeted'); <!--Why Null ?!--> $("#sid").submit(); }); }); -
How to get count of more than one field from a table using Django queryset
here is my queryset queryset = (PrathamTeamMembers.objects. select_related('state', 'district', 'block', 'personnel_type'). filter(is_active=1). annotate(total_state=Count('state', distinct=True), total_district=Count('district', distinct=True))) I am expecting result similar to { "total_state": 10 "total_district": 60 } But it is not aggregating instead it is grouping by table PrathamTeamMembers primary key. which I want to avoid. Since it is grouping on table primary key so my queryset giving result simlary to .. [{ "total_state": 1, "total_district": 1 }, { "total_state": 1, "total_district": 1 }, { "total_state": 1, "total_district": 1 } ] -
JSON field sometimes contains string, sometimes object
I'm using Django rest framework to validate JSON received from a banking API (webhook) that sends financial transactions. The serializer has been working for a few years now. The merchant field in the JSON would always contain the merchant as a nested object with the merchant's ID, name etc. But now I am sometimes receiving just the merchant's ID as a string and the JSON now fails validation. How do I set up my serializer to allow eith string or object in the merchant field? serializers.py class MerchantSerializer(serializers.Serializer): id = serializers.CharField(required=True, max_length=50) name = serializers.CharField(required=True, max_length=100) atm = serializers.BooleanField(required=False, allow_null=True) address = AddressSerializer(required=False, allow_null=True) logo = serializers.URLField(required=False, allow_null=True, max_length=500, min_length=None, allow_blank=True) class DataSerializer(serializers.Serializer): account_id = serializers.CharField(required=True, max_length=50) amount = serializers.IntegerField(required=True) created = serializers.DateTimeField() currency = serializers.CharField(required=True, max_length=3) description = serializers.CharField(required=True, max_length=250) id = serializers.CharField(required=True, max_length=50) category = serializers.CharField(required=True, max_length=100) decline_reason = serializers.CharField(required=False, allow_null=True, allow_blank=True, max_length=100) merchant = MerchantSerializer(required=False, allow_null=True) counterparty = CounterpartySerializer(required=False, allow_null=True) metadata = MetadataSerializer(required=False, allow_null=True) -
Handling upload of many files in django
Im trying to upload many image files at once to my django website. The images are put into an html form and the post request is sent with all these images (thousands). My problem is that once the images reach my server, the app crashes because too many files are open. I'm not sure how to correctly handle the post request - I'm thinking there must be a way to iterate through all the images and save and close them instead of having them all open at one time. Here is my upload method in views.py: def upload(request): if request.method == 'POST': username = request.user dataset_access = DatasetAccess.objects.get(user=username) dataset_name = request.POST['dataset_name'] if '-' in dataset_name: messages.error(request, 'Invalid Character: \' - \' ') return redirect('upload') if Dataset.objects.all().filter(title=dataset_name): messages.error(request, 'A Dataset by this name already exists!') return redirect('upload') else: notes = request.POST.get("notes") dataset = Dataset.objects.create( title = dataset_name, num_datapoints = 0, owner = username, notes = notes, ) dataset_access.dataset.add(dataset) dataset_access.save() images = request.FILES.getlist('images') dataset.create_datapoints(images,xmls,jsons,username) messages.success(request, "Dataset uploaded successfully!") return redirect('manage', dataset.title) return render(request, 'datasets/upload.html')