Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django template count of second order relationship
I am using a relational database via Django Models and have the following classes: class EventSite(models.Model): name = models.CharField(....etc.) class Artist(models.Model): jobsite = models.ForeignKey(JobSite, related_name="jobsite", null=True....etc.) is_british = models.BooleanField(default=False) class Concert(models.Model): event = models.ForeignKey(EventSite, related_name="event_concert", null=True....etc.) artists = models.ManyToManyField(Artist, related_name="artist_conerts", null=True....etc.) So each Concert is related to an Event Site and can have several Artists. Inside of my html template, I need to get a total count of the count of the number of Artists on each Concert related to an Event. (See the pic) So the html I tried looks something like: {% for site in event_sites %} {{site.event_concert.all.artists.count}}, {% endfor %} So for my scenario, I'm hoping that will display to the user: 12,3,0 but it's just returning an empty string right now. I cannot seem to find a solution, which I suspect is because I don't have the right terminology to describe what I'm trying to get. In some scenarios, I'll also have to count only the artists that are british. Any help would be greatly appreciated! -
Multiple instances of views.py in django with gunicorn threads
I am running a Django, Gunicorn and Nginx web application. The Gunicorn wsgi was configured with three worker threads. In one of my apps, I have a view.py file that has a global variable, which represents the states of some of my pins on my raspberry pi. If multiple web requests come in, and gunicorn uses different threads, will there be different versions of that global variable in my view.py file? from gpiozero import LED led = LED(17) #led for the gpio pin 17 led.off() def home(request): led.on() ... -
Is there a way to dynamically specify a queryset for nested relationship (nested serializer class) in django rest framework
Suppose we have two models: class Chapter(models.Model): title = models.CharField(max_length=128) owner = models.ForeignKey(User, on_delete=models.CASCADE) class Post(models.Model): title = models.CharField(max_length=128) body = models.TextField() is_archived = models.BooleanField(default=False) chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE) And default ModelViewSet viewset for Chapter model: class ChapterViewSet(viewsets.ModelViewSet): queryset = Chapter.objects.all() serializer_class = ChapterSerializer The key thing is that ChapterSerializer performs nested serialization using PostSerializer to provide a post_set key in the response. class PostSerializer(serializers.HyperlinkedModelSerializer): detail_url = HyperlinkedIdentityField(view_name='post-detail', read_only=True) class Meta: fields = ['id', 'title', 'is_archived', 'detail_url'] model = Post class ChapterSerializer(serializers.ModelSerializer): post_set = PostSerializer(read_only=True, many=True) class Meta: model = Chapter fields = ['id', 'title', 'owner', 'post_set'] The question is how I can dynamically specify a queryset for this nested PostSerializer. For example, when user makes GET request I only want to include the posts that are not archived (is_archived field is set to False) if user, who has done a request, is not an owner of a Chapter (request.user != current_chapter.owner). Is there any way to achive it? -
two ajax submit form makes crush - Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
I'm trying to submit my forms via ajax request , but now it makes crush and raise this error since i created my second ajax submition form : Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') here is my first and second ajax submition form #first const create_city_form = document.getElementById('create-city') create_city_form.addEventListener("submit",submitCityHandler); function submitCityHandler(e) { e.preventDefault(); $.ajax({ type: 'POST', url: '/forms/cities', data : $('#create-city').serialize(), dataType: 'json', success: successCityFunction, error:errorCityFunction, }); } function successCityFunction(data,xhr) { if (data.success==true) { create_city_form.reset(); alertify.success('added') } } function errorCityFunction(data,xhr){ for(var key in data.responseJSON['error_msg']){ if(key == 'city'){ document.getElementById('city_name_error').removeAttribute('hidden') document.getElementById('city_name_error').innerHTML = data.responseJSON['error_msg'][key][0] } } } #second const create_com_form = document.getElementById('create-com') create_com_form.addEventListener("submit",submitCusComHandler); function submitCusComHandler(e) { e.preventDefault(); $.ajax({ type: 'POST', url: '/forms/companies', data : $('#create-com').serialize(), dataType: 'json', success: successComFunction, error:errorComFunction, }); } function successComFunction(data,xhr) { if (data.success==true) { create_com_form.reset(); alertify.success('added') } } function errorComFunction(data,xhr){ for(var key in data.responseJSON['error_msg']){ if(key == 'name'){ document.getElementById('com_name_error').removeAttribute('hidden') document.getElementById('com_name_error').innerHTML = data.responseJSON['error_msg'][key][0] } } } first form <form action="" method="POST" id="create-city">{% csrf_token %} <div class="row"> <div class="col-md-6"> <div class="form-group"> <label>city name</label> {{form.city}} </div> <p class="text-danger text-center" hidden id="city_name_error"></p> </div> </div> <button type="submit" class="btn btn-success btn-lg">save</button> </form> second form <form action="" method="POST" id="create-com">{% csrf_token %} <div class="row"> <div class="col-md-6"> <div class="form-group"> <i class="fas fa-user-tag"></i> <label>company name</label> {{ form.name … -
How to get ManyToMany Field values in with selecte_related
I'm new to django. I'm using a ManyToMany field in my Profile model with Membership Model. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) picture = models.ImageField(blank=True) membership = models.ManyToManyField(MemberShip, null=True) What I want to do is I want to get all the users who has specific membership(from membership model) For example I want the list of all the users who has the Red Membership. I researched and found out that select_related() or prefetch_related can help in some way. but I can't understand how can I use these methods to get what I want. -
Adding markers google maps using sql db in django
How can I add multiple markers to my Google map using data from database? My js code: function initMap() { const myLatLng = { lat: -25.363, lng: 131.044 }; const map = new google.maps.Map(document.getElementById("map"), { zoom: 4, center: myLatLng, }); new google.maps.Marker({ position: myLatLng, map, title: "Hello World!", }); } // Adds a marker to the map and push to the array. function addMarker(position) { marker_f = Markers.objects.all() const marker = new google.maps.Marker({ Markers from models, map, }); markers.push(marker); } My models.py code: from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator # Create your models here. class Markers(models.Model): area = models.CharField(max_length=100) latitude = models.FloatField( validators=[MinValueValidator(-90), MaxValueValidator(90)], ) longitude = models.FloatField( validators=[MinValueValidator(-180), MaxValueValidator(180)], ) Tutorials used for generating this code: https://developers.google.com/maps/documentation/javascript/examples/marker-remove https://developers.google.com/maps/documentation/javascript/examples/marker-simple I don't want to hardcode my coords in js like in the example below, I would like to add them via my admin page in django with models.py variable to show markers on my map in html https://developers.google.com/maps/documentation/javascript/examples/icon-complex -
Plotly - Plot not rendering in Django
I have created 2 functions to generate plots in my projects, essentially the view call these functions to create the plots, however, the problem I have is that one of the plots is not shown, but the code is exactly the same as the other plot (the exception is the column names) views.py @login_required def dashboard(request): c = Profile.objects.get(user=request.user) leads = Leads.objects.filter(agent_id = c) deals = Deal.objects.filter(agent_id=c) #Data for plot qs_leads = Leads.objects.filter( agent_id=c, status='Open') qs_deals = Deal.objects.filter( agent_id=c) df = read_frame(qs_leads) #Creates Plots plot_div_leads = plot_leads_data(qs_leads) plot_div_deals = plot_deals_data(qs_deals) if len(leads) == 0: context = {'leads': len(leads), 'deals': len(deals), } else: if len(deals) == 0: context = {'leads':leads, 'deals': len(deals), 'pot_div_leads':plot_div_leads} else: context = {'leads':leads, 'deals':deals, 'pot_div_leads':plot_div_leads, 'plot_div_deals':plot_div_deals} return render(request, 'account/dashboard.html', context) Dashboard.html {% extends "base.html" %} {% load static %} {% block title %}Dashboard{% endblock %} <meta name="viewport" content="width=device-width, initial-scale=1"> {% block content %} <h1>Dashboard</h1> <p>Welcome to your dashboard.</p> <h1> Add Data </h1> <a href="{% url 'add_company' %}" class="buttons">Add Company</a> <a href="{% url 'add_client' %}" class="buttons">Add Client</a> <a href="{% url 'add_lead' %}" class="buttons">Add Lead</a> <a href="{% url 'add_call' %}" class="buttons">Add Call Report</a> <p></p> <h1>Your Data </h1> <p>Click on the buttons inside the tabbed menu:</p> <div class="tab"> <button class="tablinks" … -
how Convert .ajax() to fetch()
I'm trying to use JavaScript's fetch library to make a form submission to my Django application. However no matter what I do it still complains about CSRF validation. my code fetch don't work ajax function myidLikeCom(params) { $.ajax({ type: 'POST', url: '{% url "boards:likeComment" %}', data: { postid: params, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success: function (json) { document.querySelector(`#myidLikeCom${params}`).innerText = "json['result']"; }, error: function (xhr, errmsg, err) { } }); } fetch function myidLikeCom(params) { let data= { postid: params, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), } fetch('{% url "boards:likeComment" %}', { method: 'POST', body: data, }) } -
form tag not working with django and heroku
When I deployed my website with heroku it works fine but when I go to the contact page it give me error (500) but when I put it to Debug = True its says Exception Type: TemplateDoesNotExist and Exception Value: games\contact_page.html here is my views.py file its seems fine: error = False def contact_page(request): global error try: if request.method == 'POST': message_name = request.POST['message-name'] message_email = request.POST['message-email'] message = request.POST['message'] if '@' and '.com' not in message_email: error = True raise Exception("Enter True email") elif '@' not in message_email or '.com' not in message_email: error = True raise Exception("Enter True email") else: error = False with open(os.path.join("staticfiles/txtfiles/messages.txt"), "a") as file: file.writelines(f'{message_name} :: {message_email} :: {message} :: {time.ctime()}\n\n') messages.success(request, ('Your email is sent! We will reply as soon as possilbe')) return redirect('home') except: messages.success(request, ('Oops there is an error!! Enter the information correctly')) return render(request, 'games\contact_page.html', { 'error': error }) else: return render(request, 'games\contact_page.html', { }) contact_page.html file: <!DOCTYPE html> {% extends 'games/base.html' %} {% block content %} <form method="POST"> {% csrf_token %} <div class="row"> <div class="col-lg-6" style="margin: 50px 0px 25px 0px"> <input type="text" name="message-name" class="form-control mb-30" placeholder="Your name"/> </div> <div class="col-lg-6" style="margin: 50px 0px 25px 0px"> <input type="text" name="message-email" class="form-control … -
Count number of Tests
I wanted to know that is there any way I can have a test for number of tests that got run in my Django manage.py test command? My Project CI runs my test but when I comment out some tests for local testing and forget to undo them before commiting, my CI will not run all my test so more bugs may happen in production -
How to create new model using pk
I am trying to make user join the room ( so creating a new RoomMember) but this is the error that I get : "Cannot assign "room_name": "RoomMember.room" must be a "Room" instance." (thanks in advance) * Views.py: def join_room(request, pk): RoomMember.objects.create(room=pk, user=request.user).save() return redirect('room_detail') Urls.py: path("join/<int:pk>/room/", views.join_room, name="join_room"), Models.py: class Room(models.Model): name = models.CharField(max_length=100) about = models.TextField(max_length=500, null=True, blank=True) creator = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='room_creator') members = models.ManyToManyField(User, through="RoomMember") class RoomMember(models.Model): approved = models.BooleanField(default=False, blank=False) room = models.ForeignKey(Room, related_name='memberships', on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='user_groups', on_delete=models.CASCADE) class Messages(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False) text = models.CharField(max_length=10000, blank=False, null=False) date = models.DateTimeField(default=datetime.now) room = models.ForeignKey(Room, null=True, blank=False, on_delete=models.CASCADE) Html: <a class="btn btn-dark" href="{% url 'join_room' pk=room.pk %}">Join</a>* -
Products/Items are not being added in the Cart in Django. How do I fix it?
I am new to Django and working on an ecommerce app. I have defined the products and users things. But I am stuck at the cart. I have basically two apps in my project viz. index and cart. I have defined TwoPieceSuits() as a products' model in index.models.py and I have defined Cart() & CartManager() (just to manage cart properly if an anonymous user logs in the web, after adding the products in cart) in cart.models.py. I have defined two_piece_suits, an attribute in cart.models.Cart as a ManyToManyField referenced to index.models.TwoPieceSuit. Now it basically works all the way, until I want to add up the price(s) of TwoPieceSuit() instances and save the result in total of Cart(), it does not add up the prices. Despite of Cart() instance having many (because of ManyToManyField) instances of TwoPieceSuit() containing the values in price attribute, it does not add up the prices when I call them to be added in my cart.models.py. My index.models.py is: import os from django.db import models from django.utils.text import slugify def get_file_ext(filepath): base_name = os.path.basename(filepath) name, ext = os.path.splitext(base_name) return name, ext def upload_image_path(instance, filepath): name, ext = get_file_ext(filepath) filename = instance.fabric + '-' + instance.lining + '-' + … -
Finding outliers with django
So i trying to detect some price outliers in a query, but didn't fully understand. How it cant be done. So how i trying to do this: I got one model class History(models.Model): id = models.CharField(...) price = models.FloatField(...) retailer = models.CharField(...) in view i got query like so price_query = History.objects \ .filter(id__in=product) \ .filter(price_query) \ .annotate(dt=Trunc('StartDate', frequency)) \ .values('dt') \ .annotate(F('Price')\ .order_by('dt') # so i can access price outliers = np.array(price_query) filtered_price = outliers[(outliers>np.quantile(price_query, 0.1)) & (outliers<np.quantile(price_query, 0.99))] but in this case a can associate any filtered_price with any id in History model, any suggestions how i can do right? Sorry, haven't slept for a long time, nothing comes to my mind -
serving react and django with nginx without having to delete and rebuild docker
I am trying to serve Django and react via Nginx separately. Part of my Nginx folder is: upstream react_frontend { server react:3000; } location /static/ { alias /usr/src/app/react_files/static/; } location / { proxy_pass http://react_frontend; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } Part of my docker-compose is react: container_name: frontend build: context: ./frontend dockerfile: Dockerfile args: - API_SERVER=http://127.0.0.1 volumes: - react_static_volume:/usr/src/app/build/static expose: - 3000 env_file: - ./frontend/react_app/.env command: serve -s build -l 3000 depends_on: - web On the frontend the error I get is localhost/:1 GET http://localhost/static/css/main.e7ed58af.chunk.css net::ERR_ABORTED 404 (Not Found) localhost/:1 GET http://localhost/static/js/2.23f5dba1.chunk.js 404 (Not Found) localhost/:1 GET http://localhost/static/js/main.11478e07.chunk.js net::ERR_ABORTED 404 (Not Found) localhost/:1 GET http://localhost/static/js/2.23f5dba1.chunk.js net::ERR_ABORTED 404 (Not Found) localhost/:1 GET http://localhost/static/js/main.11478e07.chunk.js net::ERR_ABORTED 404 (Not Found) However when I delete the docker container + volume + images, then those errors go away. Is there a faster way than deleting all the containers and building it again? -
Django: How do I check for duplicates before bulk_create (when defining the object)?
I would like to define an object and check if it is a duplicate before creating it,as shown below. if data['title'] in videos: I'm hoping I can determine it this way. How can I determine duplicates? videos = [] throughs = [] for datas in files: for data in datas: tags = data["tags"].split() tag_pks = list( set([Tag.objects.get_or_create(name=tag)[0].pk for tag in tags]) ) #Around here, we want to make sure that the list called videos already contains data['title']. video = Video( title=data["title"], thumbnail_url=data["thumbnail_url"], preview_url=data["preview_url"], embed_url=data["embed_url"], embed_source=data["embed_source"], duration=data["duration"], published_at=data["published_at"], ) for tag_pk in tag_pks: throughs.append( Video.tags.through(video_id=video.pk, tag_id=tag_pk) ) videos.append(video) Video.objects.bulk_create(videos) Video.tags.through.objects.bulk_create(throughs) -
django redirect to other page and auto login to that page
Is there a way to redirect to other page and automatically log into that page? So it's like I make django webpage with login and create link to facebook. When user clicks to facebook link, it should automatically login to his facebook page. Of course, I will have his facebook username and password on db I used to create the website. Is this possible? Basically, I am trying to create interface page on django with link to several different webpage and make user access to his page by simply logon to this interface page alone. -
Can't access fields on abstracted user model in Django
I have an abstracted user model like so: class MyAccountManager(BaseUserManager): """ Class to adjust the base user manager """ def create_user(self, email, username, password=None): if not email: raise ValueError("Users must have an email address") user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), username=username, password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.is_active = True user.company = None user.cashpool = None user.save(using=self._db) return user class User(AbstractBaseUser): """ Main User model, inherits from AbstractBaseUser """ # Meta email = models.EmailField(verbose_name='email', max_length=60, unique=True) username = models.CharField(max_length=40, unique=True) # equals to email date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) # Relations company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True) cashpool = models.ForeignKey(Cashpool, on_delete=models.CASCADE, null=True) # Booleans is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) # Manager objects = MyAccountManager() # Use Email as login USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True def get_full_name(self): return f'{self.username}' Now in a view I can't access the company field for instance: def test(request): company = request.user.company .. # settings.py # Custom User Model AUTH_USER_MODEL = "user.User" … -
Django call related object's function
I have the following models class Customer(models.Model): created_at = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=255) def as_dic(self): return {"id": self.id, "name": self.name } class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.PROTECT) quantity = models.PositiveSmallIntegerField() def as_dic(self): return {"id": self.id, "quantity": self.quantity, "customer": self.customer.as_dic() } then orders = Order.objects.select_related('customer').all() orders_list = [obj.as_dict() for obj in orders] the error message says 'Customer' object has no attribute 'as_dic' -
I am trying to use soaplib for python third version and getting some errors
I am migrating code from python2.7 to python3.6 where I am using soaplib and it is compatible with python 3.6 is there any other lib like this? -
How do I fix pagination when there is a GET filter from the URL?
In the main product browse page (www.url.com/works), pagination works well (displays 10 items at a time) and the URL becomes www.url.com/works/?page=2 In the same view, the works can be filtered by category (i.e. www.url.com/works/?collection=Drawing). Since it using the same view, it is still paginating by 10, but if I click other pages, it loses the /?collection=Drawing and just goes back to being www.url.com/works/?page=2. How do I combine them to be something like www.url.com/works/?collection=Drawing&page=2 ? Thank you! views.py class ProductListView(ListView): model = Product template_name = "products/product_all.html" paginate_by = 10 def get_queryset(self, *args, **kwargs): sold = ProductPurchase.objects.filter( refunded=False ).values_list('product_id') qs = super(ProductListView, self).get_queryset(**kwargs) qs = qs.filter(for_sale=True, test_check=False).exclude(id__in=sold).order_by('-timestamp') categoryfilter = self.request.GET.get("collection") if categoryfilter: qs = qs.filter( Q(category__name__icontains=categoryfilter) ) query = self.request.GET.get("q") if query: tags = Tag.objects.filter( slug=query ).values_list('products') qs = qs.filter( Q(title__icontains=query) | Q(description__icontains=query) | Q(material__icontains=query) | Q(id__in=tags) ).order_by("title") return MyFilterSet(data=self.request.GET, queryset=qs).filter() -
how to configure Postgres to work with pytest
I am using django for my backend and pytest to handle my tests. I switched my project db from sqlite3 to postgres, everything works just fine except for the tests, for some reason all of my them are failing. before switching I was able to access my db during my tests with the following line: pytestmark = pytest.mark.django_db but now after using Postgres as my db I get this error on all of my tests UndefinedTable The above exception was the direct cause of the following exception: request = <SubRequest '_django_db_marker' for <Function test_logged_user_saved_recipes_url_reverse>> @pytest.fixture(autouse=True) def _django_db_marker(request): """Implement the django_db marker, internal to pytest-django. This will dynamically request the ``db``, ``transactional_db`` or ``django_db_reset_sequences`` fixtures as required by the django_db marker. """ marker = request.node.get_closest_marker("django_db") if marker: transaction, reset_sequences = validate_django_db(marker) if reset_sequences: request.getfixturevalue("django_db_reset_sequences") elif transaction: request.getfixturevalue("transactional_db") else: > request.getfixturevalue("db") does anyone knows the right way to access Postgres db while using pytest? or maybe there is a way to switch to sqlite3 db only when testing? thanks in advance -
Use of serializer class in other frameworks
Why isn't there a serializer class just like in DRF Djnago in node, express , laravel or RoR?? Is it just on python we need serialization? In every other framework, are data saved as json in database? I dont think so. Can someone explain this? For eg in DRF we have something like this: class Leadserializer(serializers.ModelSerializer): class Meta: model = Lead fields = '__all__' Here this serializer class serializes all the fields of Lead model while calling a get api. It brings out the complex queryset to json format in api response. Shouldnt the same thing be happening in all other frameworks as well?? -
How to Save a Query Set of Objects in a Single Transaction without using a for loop in Django ORM
Just a quick question, for ex, posts variable has n objects, and i need to save the post id in a post_tag model, how can i achieve without using a for loop, and just with the a single transaction using Django ORM. Here is a small snippet what i want to achieve: posts = Post_Tag.objects.filter(tag_id = subcat).values_list('post_id', flat = True) for post in posts: post_home_feed = Post_Home_Feed.objects.create(post_id = post.post_id, user_id = user_id.id) Any leads much appreciated, Thanks in advance. -
when i try to create a blog post is shows not null constraint failed: blog_blog.id
when i try to create a blog post is shows not null constraint failed: blog_blog.id and i have tried everything possible to fix this and it still not working i dont know if i should add and id field in my models.py let me show my code models.py # some field are commented out because i was trying them to see if it would work class Blog(models.Model): id = models.UUIDField(primary_key=True, editable=False) title = models.CharField(max_length=10000, null=True, blank=True, verbose_name="Title") content = models.TextField(verbose_name="Post Content") # slug = models.SlugField(unique=True) image = models.ImageField(upload_to="blog-images/%Y/%m/%d/", verbose_name="Post Thumbnail") category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, verbose_name="Category", null=True) tags = models.ManyToManyField(Tag, related_name='tags', verbose_name="Tag") status = models.CharField(choices=STATUS_CHOICE, default="published", max_length=150, verbose_name='Status') creator = models.ForeignKey(User, on_delete=models.DO_NOTHING, verbose_name="Creator", null=True) created = models.DateTimeField(auto_now_add=True ,verbose_name="Created", null=True) def get_absolute_url(self): # return reverse('blog:blog-details', args=[self.slug]) return reverse('blog:blog-details', kwargs={'pk': self.pk}) class Meta: verbose_name = "Blog Post" verbose_name_plural = "Blog Posts" def __str__(self): return self.title views.py def blogpost(request): if request.method == "POST": form = BlogPostForm(request.POST, request.FILES) if form.is_valid(): form = form.save(commit=False) form.creator = request.user form.save() messages.success(request, f'Hi, Your Post have been sent for review and would be live soon!') return redirect('blog:home') else: form = BlogPostForm() context = { "form": form } return render(request, 'blog/AddPost.html', context) urls.py path('', views.blog_list, name="home"), path('post/<int:pk>', views.blog_detail, name="blog-details"), path('post/categories/<slug:category_slug>', … -
Using Django/Postgres to store binary data in a memory efficient manor
Context I have a Django project, and inside of this project, I have a database model with a field of type models.BinaryField(max_length=50000000, default=b'0') Problem When the server is requested to query for this binary data, even though there are never more than 1-2 concurrent requests, I am reaching the ram limits of my server using io.BytesIO, along with stream.seek({index}), and stream.close()(I use the term stream very loosely, as I am simply referring to seeking and closing a stream of bytes here). Question Is it possible that I need to implement the way I am storing this binary data differently? Solutions that I have tried that didn't work Would splitting it up into chunks of smaller sizes be computationally more efficient for the RAM of the server? When I attempted this, I discovered that chunking up the file into smaller chunks and relating them with a many-to-one relationship was extremely taxing as far as overhead on the database.