Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Table is not creating after migration
I want to add new functionality to my Django project on DigitalOcean server using Postgres database. The problem is that, everything works finely on local server, but on production server new table for new model is not creating. I've deleted all migration files, made migrations again, but again can't see new table on database. Please, help me to fix that problem. My exact error: relation "documents_app_employee" does not exist LINE 1: INSERT INTO "documents_app_employee" ("fin", "name", "surnam... Here are my codes: models.py: class Employee(models.Model): fin = models.CharField(max_length=10, blank=True, null=True) name = models.CharField(max_length=20) surname = models.CharField(max_length=20) def __str__(self): return self.name + " " + self.surname forms.py: class CreateEmployeeForm(ModelForm): def save(self, commit=False): employee = super(CreateEmployeeForm, self).save(commit=False) Employee.objects.create( fin = employee.fin, name = employee.name, surname = employee.surname, ) class Meta: model = Employee fields = '__all__' scripts for deleting and undo migration: find . -path "*/migrations/*.py" -not -name "__init__.py" -delete find . -path "*/migrations/*.pyc" -delete pip3 uninstall django pip3 install -r requirements.txt python3 manage.py makemigrations python3 manage.py migrate But again getting: ProgrammingError at /employee_document relation "documents_app_employee" does not exist LINE 1: INSERT INTO "documents_app_employee" ("fin", "name", "surnam... -
Django map model data to external data
I want to map data from the https://developer.microsoft.com/en-us/graph/graph-explorer api as a data source to have the additional required data on the model. Using a computed property on the model does not work as it is going to query for each instance in the set and is too time consuming. I could not find anything on this topic, besides maybe abusing the from_db() method as an override, if this even works. TLDR; I want data from an external API on my local model -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe4 in position 1: invalid continuation byte in Django
This is very possibly a duplicate, since I saw a certain amount of similar questions but I can't seem to find a solution. My problem is as stated in the description. I am working on a Django project on python 3.8.5. My professor wanted me to program a website and use PostgreSQL as db. I did use it but I always got the following error when I used python manage.py runserver. UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe4 in position 1: invalid continuation byte I uninstalled PostgreSQL and tryed to start a older project of mine that uses sqlite3, but it did not work and threw the same error. Following the stack trace. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Startklar\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Startklar\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Startklar\PycharmProject\Modul133_Movie\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Startklar\PycharmProject\Modul133_Movie\venv\lib\site-packages\django\core\management\commands\runserver.py", line 139, in inner_run run(self.addr, int(self.port), handler, File "C:\Users\Startklar\PycharmProject\Modul133_Movie\venv\lib\site-packages\django\core\servers\basehttp.py", line 206, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) File "C:\Users\Startklar\PycharmProject\Modul133_Movie\venv\lib\site-packages\django\core\servers\basehttp.py", line 67, in __init__ super().__init__(*args, **kwargs) File "C:\Users\Startklar\AppData\Local\Programs\Python\Python38\lib\socketserver.py", line 452, in __init__ self.server_bind() File "C:\Users\Startklar\AppData\Local\Programs\Python\Python38\lib\wsgiref\simple_server.py", line 50, in server_bind HTTPServer.server_bind(self) File "C:\Users\Startklar\AppData\Local\Programs\Python\Python38\lib\http\server.py", line 140, in server_bind self.server_name = socket.getfqdn(host) File "C:\Users\Startklar\AppData\Local\Programs\Python\Python38\lib\socket.py", line 756, … -
Facial Recognition using django
I am using django to access client webcam so that facial recognition process can be done. Right now I am using django channels to transfer the frame to the server and then return the annotated frame back to the same page. const FPS = 3; chatSocket.onopen = () => { console.log(`Connected to socket`); setInterval(() => { chatSocket.send(JSON.stringify({ 'message': getFrame() })); }, 1000 / FPS); } this message is then decoded and converted to a frame so as to use Opencv and facial detection, once the predictions are made, the data is returned back to the same page using the same websocket. This process is working fine, but the final page lags way too much , is there any other option to transfer the data in real-time? -
How to convert a Django Rest Framework Request object with data to a Django HttpRequest object?
I'm new to Django world and I'm trying to build a Django application with 2 function based views wherein one function/view should be able to call the other view. The reason I'm trying to do this is to reduce avoid writing the logic again which is available in my other API. @api_view(['POST']) def PerformActionOne(request): result_one = PerformActionTwo(request) result_two = DoSomethingElse(result_one) return Response(result_two) @api_view(['POST']) def PerformActionTwo(request): # Performs some calculation and returns rest_framework.response Response with some data in it # result is a dictionary result = Calculate() return Response(result) In the above code I'm getting an error in this line result_one = PerformActionTwo(request) Error: Exception Type: AssertionError Exception Value: The request argument must be an instance of django.http.HttpRequest, not rest_framework.request.Request. I tried to look it up online and read documentation but I couldn't get a solution to this. I apologize if this is a duplicate question. Any leads on this will be greatly appreciated. -
Django cors headers error because of recent documentation update
I'm trying to use django-cors-headers to add CORs to my server, but when I load the page I receive this error on the server. i think the documentation is recently updated now should we still use : CORS_ALLOWED_ORIGINS=True or the should we leave it to default? PS C:\Users\Ganesh Akshaya\Desktop\lcodev\ecom> python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\ganesh akshaya\appdata\local\programs\python\python37\lib\threading.py", line 926, in _bootstrap_inner self.run() File "c:\users\ganesh akshaya\appdata\local\programs\python\python37\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\core\management\base.py", line 441, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (corsheaders.E006) CORS_ALLOWED_ORIGINS should be a sequence of strings. System check identified 1 issue (0 silenced). and my settings.py file contains: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] CORS_ALLOWED_ORIGINS=True -
How to move mail to specified folder in Outlook using Django and imaplib?
Im trying to move mail to a specific folder say "Tickets". Im unable to achieve that. Trying to achieve it using imaplib with Django. This issue im facing while accessing outlook mail. For Gmail im able to add label using +X-GM-LABELS adding code snippet below. Mails are getting deleted. Thanks for any help in advance for uid in id_list: imap.store(uid,'+FLAGS', '(Tickets)') imap.store(uid,'+FLAGS', '\Deleted') -
How to solve Django Axios Ajax Bad Request Error
Have two issues First: I get the following error in the terminal when i post comment Bad Request: /post/comment/ "POST /post/comment/ HTTP/1.1" 400 37 Second: body:formData returns empty JSON(i resolved this by directly assigning the JavaScript variable that stores form body content body:content) Just want to know why formData returns empty Here is the code for my project Model: class Comment(models.Model): body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(get_user_model(),on_delete=models.CASCADE) post = models.ForeignKey('Post',related_name="post_comment",on_delete=models.CASCADE) class Meta: ordering =['-created_on'] Form class PostCommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body',) View class PostComment(LoginRequiredMixin,FormView): form_class = PostCommentForm def form_invalid(self,form): if self.request.headers.get('x-requested-with') == 'XMLHttpRequest': return JsonResponse({"error": form.errors}, status=400) else: return JsonResponse({"error": "Invalid form and request"}, status=400) def form_valid(self,form): if self.request.headers.get('x-requested-with') == 'XMLHttpRequest': form.instance.author = self.request.user post = Post.objects.get(pk=self.kwargs['pk']) form.instance.post = post comment_instance = form.save() ser_comment = serializers.serialize("json", [comment_instance, ]) return JsonResponse({"new_comment": ser_comment}, status=200) else: return JsonResponse({"error": "Error occured during request"}, status=400) Url path('post/comment/', views.PostComment.as_view(), name='post-cmt'), JavaScript Ajax using Axios.js <script type="text/javascript"> axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'X-CSRFToken'; function createComment(formData) { console.log("Posting Comment"); axios.post("{% url 'post-cmt' %}", { body: content }).then(function(response) { console.log(response) }).catch(function(error){ console.error("Error", error); }); } const content = document.getElementById("id_body").value const cform = document.getElementById("comment-form"); cform.addEventListener('submit', function(e){ e.preventDefault(); if(content){ let formData = new FormData(cform); … -
'WSGIRequest' object has no attribute 'owner'
I am getting this error and I can't seem to figure it out. I tried changing the middleware, but that didn't seem to work. This is the error: The serializer field might be named incorrectly and not match any attribute or key on the WSGIRequest instance. Original exception text was: 'WSGIRequest' object has no attribute 'owner'. views.py import json from django.http import JsonResponse from rest_framework import viewsets, serializers from .models import * from django.views.decorators.csrf import csrf_exempt class CreateTodoRequest(serializers.Serializer): owner = serializers.IntegerField() title = serializers.CharField() class CreateTodoResponse(serializers.Serializer): id = serializers.IntegerField() owner = serializers.IntegerField() title = serializers.CharField() @csrf_exempt def create_todo_list(request): data = CreateTodoRequest(request) params = {'owner': data['owner'], 'title': data['title']} todo = models.List.objects.create(**params) serial = CreateTodoResponse(todo) return JsonResponse(todo.data, status=200) class UpdateListRequest(CreateTodoRequest): id = serializers.IntegerField() class UpdateListResponse(UpdateListRequest): """ """ @csrf_exempt def update_todo_list(request): data = UpdateListRequest(request) params = {'owner': data['user_id'], 'title': data['title']} rows_affected = models.List.objects.filter(id=data['id']).update(**params) todo_list = models.List.objects.get(id=data['id']) serial = UpdateListResponse(todo_list) return JsonResponse(serial.data, status=200) class DeleteListRequest(serializers.Serializer): id = serializers.IntegerField() @csrf_exempt def delete_todo_list(request): data = DeleteListRequest(request) models.List.objects.filter(id=data['id']).delete() return JsonResponse(True, status=200, safe=False) class CreateTaskRequest(serializers.Serializer): title = serializers.CharField() task_list = serializers.CharField() completed = serializers.BooleanField() due_date = serializers.DateTimeField() class CreateTaskResponse(CreateTaskRequest): """ """ def create_task(request): data = CreateTaskRequest(request) params = {'title': data['title'], 'task_list': data['task_list_id'], 'completed' : data['completed'], 'due_date' : data['due_date']} … -
Having "permission denied" when I try to upload image to /media/ dir, DJANGO
I setup django framework into apache server, normally there is no problem when I try to insert record to DB. But if I try to upload something into media dir, permission problem occurs. I already give the chmod -R 755 to /var/www/ project's parent folder. But still having the problem. settings.py STATIC_URL = '/static/' MEDIA_URL = "/media/" STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, "media") and .conf settings are below. <VirtualHost *:8001> ServerName example.com DocumentRoot /var/www/ Alias /static /var/www/example.com/src/static <Directory "/var/www/example.com/src/static"> Options FollowSymLinks Order allow,deny Allow from all Require all granted </Directory> Alias /media /var/www/example.com/media <Directory "/var/www/example.com/media"> Options FollowSymLinks Order allow,deny Allow from all Require all granted </Directory> ErrorLog /var/www/example.com/logs/apis_error.log CustomLog /var/www/example.com/logs/apis_access.log combined WSGIPassAuthorization On WSGIDaemonProcess example.com python-path=/var/www/example.com:/var/www/venv36/lib/python3.6/site-packages WSGIProcessGroup example.com WSGIScriptAlias / /var/www/example.com/src/wsgi.py <Directory /var/www/example.com/src> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> Any idea what is the problem here? -
How do you query a model for an aggregate of a ForeignKey computed field
How do you query a model for an aggregate of a ForeignKey 'computed' (Autofield?) field I have two models: class Job(models.Model): name = models.CharField(…) class LineItem(models.Model): job = models.ForeignKey(Job, …) metric_1 = models.DecimalField(…) metric_2 = models.DecimalField(…) metric_3 = models.DecimalField(…) # Making this a @property, @cached_property, or the like makes no difference def metric_total(self): return (self.metric_1 + self.metric_2 * self.metric_3) In the view: class StackoverflowView(ListView, …): model = Job def get_queryset(self): return Job.objects .select_related(…) .prefetch_related('lineitem_set') .filter(…).order_by(…) def get_context_data(self, **kwargs): context_data = super(StackoverflowView, self).get_context_data(**kwargs) context_data['qs_aggregate'] = self.get_queryset() \ .annotate( # Do I need to Annotate the model? ).aggregate( # This works for any of the fields that have a model field type metric1Total=Sum('lineitem__metric_1'), metric2Total=Sum('lineitem__metric_2'), # This will error : # Unsupported lookup 'metric_total' for AutoField or join on the field not permitted. # How do I aggregate the computed model field 'metric_total'? metricTotal=Sum('lineitem__metric_total'), ) return context_data When I try to aggregate the computed field, I get the error: Unsupported lookup 'metric_total' for AutoField or join on the field not permitted.. How do I aggregate these special fields? -
Django Annotations
So I'm working on a website, and I want to have some kind of a summary page to display the data that I have. Let's say I have these models: class IceCream(TimeStampedModel): name = models.CharField() color = models.CharField() class Cupcake(TimeStampedModel): name = models.CharField() icing = models.CharField() So on this page, users will be able to input a date range for the summary. I'm using DRF to serialize the data and to display them on the view actions. After I receive the filter dates, I will filter out the IceCream objects and Cupcake objects using the created field from TimeStampedModel. @action(detail=False, methods=['get']) def dessert_summary(self, request, **kwargs): start_date = self.request.query_params.get('start_date') end_date = self.request.query_params.get('end_date') cupcakes = Cupcake.objects.filter(created__date__range=[start_date, end_date]) ice_creams = IceCream.objects.filter(created__date__range=[start_date, end_date]) After filtering, I want to count the total cupcakes and the total ice creams that is created within that period of time. But I also want to group them by the dates, and display the total count for both ice creams and cupcakes based on that date. So I tried to annotate the querysets like this: cupcakes = cupcakes.annotate(date=TruncDate('created')) cupcakes = cupcakes.values('date') cupcakes = cupcakes.annotate(total_cupcakes=Count('id')) ice_creams = ice_creams.annotate(date=TruncDate('created')) ice_creams = ice_creams.values('date') ice_creams = ice_creams.annotate(total_ice_creams=Count('id')) So I want the result to be … -
Django migrations.RunSQL visibility to other connections during tests
I am creating a postgresql function in a migrations.RunSQL, and it gets created just fine. I have the default connection and another connection ('userdata') that, in this case, actually point to the same DB. The problem is that during tests, the function created in RunSQL is not visible to the 'userdata' connection. Is is visible to the default connection (which I'm guessing runs the RunSQL). Fine, I say, it's just in tests so I will close and reopen after migrations are run (by overriding setup_databases in my DiscoverRunner, for example) and then the 'userdata' connection will also see the new function. Alas, the ONLY place that the connections['userdata'].connect() call seems to actually have the desired effect is calling it actually in the test method (or in the classes being tested of course). The new function remains invisible if I do a connect() in the setup_databases or setUp for the TestCase. The same is true of connections.close_all(), which also only works in the test method. There seems to be some magic going on, with different connections being returned at different times. Is there a way to tell Django to reopen all stale connections that will work in tests? -
Field Serializers Django
I have a serializer with some custom fields and those fields depends on a specific query. The problem is that each time the serializer tries to get the value for this field It must perform the query to the DB. What about if the serializer is a many=True serializer?. class ExampleSerializer(serializers.ModelSerializer): field_one = serializers.SerializerMethodField() field_two = serializers.SerializerMethodField() field_three = serializers.SerializerMethodField() . . . def get_field_one(self, obj): try: # This is where i do the query query_result = obj.objects.filter(filter=self.context.get("filter").first() if query_result: # Do field one stuff except Exception: # Do exception stuff def get_field_two(self, obj): try: # This is where i do the query query_result = obj.objects.filter(filter=self.context.get("filter").first() if query_result: # Do field two stuff except Exception: # Do exception stuff def get_field_three(self, obj): try: # This is where i do the query query_result = obj.objects.filter(filter=self.context.get("filter").first() if query_result: # Do field three stuff except Exception: # Do exception stuff Is there a way to store that result inside a property in the serializer? Also, if I set a value in one of the serializer field, how do I retrieve and do some maths on another field in the same serializer? -
Integrate the JSON file via an API-Rest in MongoDB database
I generated a JSON file from Django to integrate it via an API-Rest in a MongoDB database. Generate a JSON file from Django: with open("fichier.json", "w") as out: data = serializers.serialize("json", User.objects.all()) out.write(data) data2 = serializers.serialize("json", Categories.objects.all() ) out.write(data2) the second step about integrating the JSON file via an API-Rest in a MongoDB database? I don't have any idea about doing it! Thanks for your help. -
Set field update in address url json django rest framework
I need update the field 'plan': The view @api_view(['GET','PUT']) def set_plan(request, nr_acc, nr_plan): plan = Plan.objects.get(pk=nr_plan) acc = Account.objects.get(pk=nr_acc) #return Response(plan.id) if request.method == 'PUT': #acc.plan.id = plan.id #acc.save() serializer = AccountSerializer(acc, data=request.data) if serializer.is_valid(): serializer.data['plan'] = request['plan'].id serializer.save() serializer_dict = serializer.data serializer_dict['message'] = "Consegui fazer o update do plano." return JsonResponse({'Conta':acc.id,'Novo plano': acc.plan.id}, status=200) else: return JsonResponse({'Conta':acc.id,'Novo plano': acc.plan.id}, status=200) return JsonResponse({'Conta':acc.id,'Novo plano': acc.plan.id}, status=200) In browser (http://127.0.0.1:8000/account/set-plan/1/1) I cant set update, the plan are with id 2, when i access the address http://127.0.0.1:8000/account/set-plan/1/1 dont update -
Function based view - dependent dropdown list
<script> $("#id_category").change(function () { var url = $("#newrequestForm").attr("data-sector-url"); // get the url of the load_cities view var categoryId = $(this).val(); // get the selected country ID from the HTML input $.ajax({ // initialize an AJAX request url: url, // set the url of the request (= localhost:8000/hr/ajax/load-cities/) data: { 'scholar_category': categoryId // add the country id to the GET parameters }, success: function (data) { // `data` is the return of the `load_cities` view function $("#id_sector").html(data); // replace the contents of the city input with the data that came from the server } }); }); -
Is there a way to update an app config based on an overridden setting in a Django TestCase?
For example, if given a method that relies on the app config: def foo(): if apps.get_app_config('some_app').bar: return True Where some_app.bar is False by default, but I want to test it when it's True: class TestFoo(TestCase): @override_settings(BAR=True) def test_foo_enabled(self): # Fails because the app config isn't updated when using override_settings self.assertTrue(foo()) Is there a way to update the app config with the new setting from override_settings? Ideally, I want to avoid duplicating the app config setting in foo(): def foo(): if getattr(settings, BAR, False): return True -
How can I divide and set 2 decimal place in Django template?
I'm trying to do something like this: divide the product.sell_price by 3 and then use 2 decimal places. My code in Django template: {% widthratio product.sell_price 3 1 | floatformat:'2' %} If I only {% widthratio product.sell_price 3 1 %} everything goes OK but I need to insert 2 decimal places. Any help? Thank you! -
How to assert a IntegrityError properly in django?
folks. I'm trying to create a unit test to pass when an IntegrityError is raised. I tried to do this but it tells me that IntegrityError is not iterable: def test_create_company_with_duplicate_cnpj(self): with self.assertRaises(IntegrityError) as context: Company.objects.create(name=self.company.name, cnpj=self.company.cnpj) self.assertTrue('UNIQUE constraint failed' in context.exception) I did the "workaround" below and it passed. But is it correct or is there a different solution without using pytest? def test_create_company_with_duplicate_cnpj(self): with self.assertRaises(IntegrityError): Company.objects.create(name=self.company.name, cnpj=self.company.cnpj) -
GeoDjango with PostGIS - distance calculation is wrong
I'm trying to use GeoDjango with PostGIS in order to measure distances but the results I'm getting are off by 20%. For testing I chose 2 random points in the ocean: (40.607532, -72.829369) and (40.366040, -73.556856). To get the expected result I used 2 different methods: The google maps "measure distance" feature. My own python code using the great arc distance calculation. Both give me the same result of 41.71 miles. Django gives me 50.49. Here is my code: # models.py from django.contrib.gis.db import models class Location(models.Model): point = models.PointField(null=True) Then from the django shell: >>> from loc.models import Location >>> from django.contrib.gis.geos import Point >>> from django.contrib.gis.db.models.functions import Distance >>> loc = Location(point=Point(40.366040, -73.556856, srid=4326)) >>> loc.save() >>> pnt = Point(40.607532, -72.829369, srid=4326) >>> qs = Location.objects.annotate(distance=Distance('point', pnt)) >>> qs[0].distance.mi 50.4954671273202 -
Django - Using get_readonly_fields but getting 'NoneType' object is not iterable' when adding new record
here's the thing, if the X field (non required) has a value then none of the others fields can be edited (when editing). However, if this values is empty then all the other fields should go back to normal. I did that using this inside the app's admin.py def get_readonly_fields(self, request, obj=None): if obj: lb = obj.X if lb: return ['v','p','e'] else: return [] This works when you enter existing objects, however when adding a new instance I get the yellow page with the 'NoneType' object is not iterable' error. I'm aware this because the OBJ is null, when looking up for similar problems I found this is a django bug with get read only fields, apparently. Searched for solutions but they make that the created object can't be edited anymore (at least the ones I found). Is there a workaround or another method I can use? Thanks. -
How to count users if they have a product within a date range using Django ORM?
So let's say I have these 2 models: class User(models.Model): name = models.CharField() dob = models.DateField() class Product(models.Model): user = ForeignKey(User) created = models.DateTimeField() name = models.CharField() amount = models.DecimalField() Users can create a product, and it will save when that product is created. What I want to ask is, is it possible to count the number of users that have a product within a range of time? I'm using GenericViewSet for the views and created actions inside it to return the data. I want the views to return a data that looks like this: { 'data': [{ 'date': "2020-01-01", 'total_users': 10 }, { 'date': "2020-01-02", 'total_users': 17 }] } I understand that I can filter the products using a date range like this to get the products: Product.objects.filter(created__range=["2020-01-01", "2020-02-01"]) But how do I calculate the total users that have a product within that range? Is it possible to do annotations for this? Thanks in advance for your help! -
My django web app is holding on to old image data in memory. How can I clear it after every submit?
I have built a django app that asks for user input, then uses numpy and matplotlib.pyplot to generate graphs and display them in my web page. I'm not saving the data to disk, but rather saving it to memory using io and base64, which may be part of the problem. On first submit, I get something like this, which is exactly what I want, but then on subsequent submits, I never get rid of the old graphs and end up with something like this and this. Here is my views.py file: from django.shortcuts import render from .forms import NNInput import numexpr as ne import numpy as np import matplotlib.pyplot as plt import io import base64 from PIL import Image from .FeedForwardNN import FFNN # Create your views here. def ffnn(request): if request.method == 'POST': form = NNInput(request.POST) if form.is_valid(): cd = form.cleaned_data net = FFNN(1, 1, [cd['n'] for i in range(cd['m'])]) x = np.arange(-1, 1, .001) x.shape = (x.shape[0], 1) untrained = net.evaluate(x) fig_untrained = plt.figure(1) plt.xlabel('x- axis') plt.ylabel('y-axis') plt.title('Pre-Training NN (green) vs function') y = ne.evaluate(cd['func']) plt.plot(x, y, 'r', x, untrained, 'g') buf = io.BytesIO() fig_untrained.savefig(buf, format='png') im = Image.open(buf) buf2 = io.BytesIO() im.save(buf2, format='png') im_str = base64.b64encode(buf2.getvalue()).decode() data_uri … -
How to create a personalized tags in Django?
I have a value that I need to replace for example, the string is "https://www.test.com" and I want to change it into "https://test.com".