Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Form Validation And Google Recaptcha Not Working
I have a form that is not validating phone numbers and emails properly even though I am using PhoneNumberField and EmailField. When a user inputs invalid data, no error messages are showing up such as "Enter a valid email address." or "Enter a valid phone number (e.g. +12125552368)." Maybe the validation is not working because I am passing the form class itself and not the instance? Otherwise I have no clue. The form successfully processes when a user inputs valid data though. My Google Recaptcha code is also not working properly because the print statements for result, recaptcha_response, and result_success are not printing. The recaptcha symbol is displaying though at the bottom right of the webpage. Code: https://dpaste.org/KSJY I would appreciate any help with this. -
Add dynamic attribute to serializer
I'd like to add a dynamic attribute to my serializers whenever they are called. Note that I'm talking about an attribute, not a field. Here's the idea: User call the API Viewset calls the serializer with the data I manage to set self.my_key = my_dynamic_value Checks and returns the serializer data (normal process) To set my dynamic value, I need to use self.context meaning I can't override the __init__ method of the serializers (they are called on server start and context is empty) Any idea on how I could do it? -
Django get_or_create not getting data back
i have created a FBV for Modal form (popup) i want to have the same view to handle both create and update, the reason i am using FBV is that am assigning the foreign key through queries rather that passing the id through the URL. Please note the JS script am using to call the Modal and render the form in it. **Models.py:** class Startup ( models.Model ) : author = models.OneToOneField ( User , on_delete = models.CASCADE ) startup_name = models.CharField ( 'Startup Name' , max_length = 32 , null = False , blank = False ) class Startup_About ( models.Model ) : str_about = models.OneToOneField ( Startup , on_delete = models.CASCADE ) about = models.TextField ( 'About Startup' , max_length = 2000 , null = False , blank = False ) problem = models.TextField ( 'Problem/Opportunity' , max_length = 2000 , null = False , blank = False ) business_model = models.TextField ( 'Business Monitization Model' , max_length = 2000 , null = False ,blank = False ) offer = models.TextField ( 'Offer to Investors' , max_length = 2000 , null = False , blank = False ) def __str__(self) : return str(self.str_about) **forms.py:** class startupform(forms.ModelForm): class Meta: … -
The view didn't return an HttpResponse object. It returned None instead, using Django
So, I am trying to display a form into my html using Django, it has to be a form that creates a new page in the database. I am using ModelForm since I've read is the best way to provide the user with the tools to input data in the database. in views.py: from django.shortcuts import redirect, render from django.http import HttpResponse from .models import Pages, PagesForm from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth import login, logout, authenticate from django.contrib import messages from .forms import NewUserForm def homepage(request): return render(request = request, template_name='main/home.html', context = {}) def pages(request): if request.method == "POST": form = PagesForm(request.POST) if form.is_valid(): pass #nada, solo activa la validación else: form = PagesForm() return render(request, template_name='main/pages.html', context = {"Pages":PagesForm.objects.all}) in models.py: from django.db import models from datetime import datetime from django.forms import ModelForm # Create your models here. #Pages son entradas del diario class Pages(models.Model): title = models.CharField(max_length=300) content = models.TextField() author = models.CharField(max_length=50) published_date = models.DateTimeField("Published: ", default=datetime.now()) def __str__(self): return self.title class PagesForm(ModelForm): class Meta: model = Pages fields = '__all__' in pages.html: {% extends "main/header.html" %} {% block content %} <div> {% for page in Pages %} <h2>Display recent pages</h2> <div class="col s12 … -
Python manage.py runserver issuing the no module Error
Trying to runserver but I'm getting this errors Traceback (most recent call last): File "manage.py", line 13, in <module> execute_from_command_line(sys.argv) File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 308, in execute settings.INSTALLED_APPS File "/usr/lib/python2.7/dist-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/usr/lib/python2.7/dist-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/usr/lib/python2.7/dist-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/prezine/Desktop/project/djangopinmgmt/settings.py", line 14, in <module> import dj_database_url ImportError: No module named dj_database_url I'm not sure what to change or how to go this, I've also tried installing dj_database_url, but it seem to not work still pip install dj_database_url -
Django - grabbing an additional field from related table
I have the following models: class User(AbstractBaseUser, PermissionsMixin): SUPERVISOR = 1 REVIEWER = 2 VERIFIER = 3 READ_ONLY = 4 USER_TYPE = [ (SUPERVISOR, 'Supervisor'), (REVIEWER, 'Reviewer'), (VERIFIER, 'Verifier'), (READ_ONLY, 'Read Only'), ] email = models.EmailField(max_length=50, unique=True) name = models.CharField(max_length=100) phone = models.CharField(max_length=50, null=True) role = models.IntegerField( choices=USER_TYPE, default=READ_ONLY ) is_active = models.BooleanField(default=True) class Comment(models.Model): text = models.TextField() user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.PROTECT ) View: class CommentViewSet(BaseCertViewSet): queryset = Comment.objects.all() serializer_class = serializers.CommentSerializer Serializer: class CommentSerializer(serializers.ModelSerializer): user = serializers.SlugRelatedField( read_only=True, slug_field='name' ) class Meta: model = Comment fields = ('id', 'text', 'user') read_only_fields = ('id',) My question: when I hit the comment API endpoint, I'd like it to return the user role from the user model as well. How do I go about doing that? -
How send a request error inside the save function?
I need to validate the video duration before the video is saved,but he only message error i found is the forms.ValidationError. The upload request is getting error 500 because of the raise. def save(self, *args, **kwargs): ... result = subprocess.Popen(["ffprobe", video_path], stdout = subprocess.PIPE, stderr = subprocess.STDOUT) t = [x for x in result.stdout.readlines() if "Duration" in x] if duration > 30: raise forms.ValidationError('The Video must have 30 secs') ... But i need a response instead of raise like: return Response({'detail': 'This video must have 30 secs'}, status=status.HTTP_400_BAD_REQUEST) But i only know how to use Response inside the Views, is there a way to use Response inside the save function? -
How to create my own endpoint in Django with rest_framework_json_api?
I am new to Django and need some help to understand! I have been able to create the Api and it works! But ... how do I create an endPoint to do something specific that I want? For example, validate an email? In other words, with a views.ModelViewSet how to define for example def validate (request): I tell you that I have created the endpoint that mentions them but I have to make some arrangements so that the answer is as I expect it. class SomeViewSet(views.ModelViewSet): allowed_methods = ('GET', 'PATCH', 'POST', 'OPTIONS') queryset = Some.objects.all() serializer_class = SomeSerializer def validate(request): email = request.GET.get("email", None) if email and Some.objects.filter(email=email).exists(): return JsonResponse({'message': 'Email already exists.'}, status=status.HTTP_200_OK) return JsonResponse({'message': 'Email does not exist.'}, status=status.HTTP_400_BAD_REQUEST) rest_framework.response.Response does not work here! Thanks! -
Django raising AppRegistryNotReady after update from to 1.9
I have read many similar posts with the same situation and tried a few things suggested if they were at all related. I just updated to Django 1.9 and I received this traceback: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/opt/django/www/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/opt/django/www/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 302, in execute settings.INSTALLED_APPS File "/opt/django/www/local/lib/python2.7/site-packages/django/conf/__init__.py", line 55, in __getattr__ self._setup(name) File "/opt/django/www/local/lib/python2.7/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/opt/django/www/local/lib/python2.7/site-packages/django/conf/__init__.py", line 99, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/opt/django/www/src/site_aggrigator/__init__.py", line 2, in <module> import management File "/opt/django/www/src/site_aggrigator/management/__init__.py", line 4, in <module> from django.contrib.auth.models import Permission File "/opt/django/www/local/lib/python2.7/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/opt/django/www/local/lib/python2.7/site-packages/django/contrib/auth/base_user.py", line 49, in <module> class AbstractBaseUser(models.Model): File "/opt/django/www/local/lib/python2.7/site-packages/django/db/models/base.py", line 94, in __new__ app_config = apps.get_containing_app_config(module) File "/opt/django/www/local/lib/python2.7/site-packages/django/apps/registry.py", line 239, in get_containing_app_config self.check_apps_ready() File "/opt/django/www/local/lib/python2.7/site-packages/django/apps/registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. All my apps are installed on my virtual env for sure because the app was running fine before I made the update. I also received this right before my update: /opt/django/www/local/lib/python2.7/site-packages/Django-1.8-py2.7.egg/django/contrib/auth/models.py:41: RemovedInDjango19Warning: Model class django.contrib.auth.models.Permission doesn't declare an explicit app_label … -
How can I modify this JS function so that it runs whenever the field is equal a certain length?
I have a function that currently runs whenever the user clicks/tabs out of the employee_number field. I would like it to run whenever the length of the numbers entered is equal to 6, without having to leave the field, since when I try using the tab, it conflicts with loading the next field which is a drop-down that is part of the function ran. I tried by running it using .change and putting the constraint within the function, but it did not work and I don't know what else to try. enter_exit.html {% extends "base.html" %} {% load core_tags staticfiles %} {% block main %} <form id="warehouseForm" action="" method="POST" data-employee-activity-lookup-url="{% url 'operations:employee_activity_search' %}" novalidate > {% csrf_token %} <div> <div> <div id="employee-name" style="margin-bottom: 10px">&nbsp;</div> <label>Employee #</label> {{ form.employee_number }} </div> <div=> <label>Work Area</label> {{ form.work_area }} </div> <div style="display: none" id="my-hidden-div"> <label>Station</label> {{ form.station_number }} </div> </div> <div> <div> <button>Enter Area</button> <button>Exit Area</button> </div> </div> </form> <script> // Grab the employee name and their current active work log (if any) $(document).on('blur', "#{{ form.employee_number.id_for_label }}", function(){ var url = $("#warehouseForm").attr('data-employee-activity-lookup-url'); var employeeId = $(this).val(); # ... more fields ... if (employeeId !== "") { # .. Rest of function ... }) … -
Calculate multiple annotated properties based on 2-layer deep one-to-many relationships in Django
I am looking for a more-optimal way to get annotated values on records of a model when in order to calculate those values I must annotate a set of records on the base model, which needs to use values that IT calculates from a set of records on it. Here is the structure of the models: class Employee(models.Model): first_name = models.CharField() last_name = models.CharField() client = models.ForeignKey("app.Client") class DocumentTemplate(models.Model): name = models.CharField() warning_days = models.IntegerField() client = models.ForeignKey("app.Client") class EmployeeDocument(models.Model): document_template = models.ForeignKey("app.DocumentTemplate") employee = models.ForeignKey("app.Employee") @property def current_document(self): return self.documents.latest("date_added") @property def expiration_date(self): current_document = self.current_document if not current_document: return None return current_document.expiration_date @property def near_expiration_date(self): current_document = self.current_document if not current_document and current_document.expiration_date is not None: return None return currnet_document.expiration_date - timedelta(days=self.documenttemplate.warning_days) class EmployeeDocumentInstance(models.Model): employee_document = models.ForeignKey("app.EmployeeDocument", related_name="documents") date_added = models.DateTimeField(auto_now_add=True) expiration_date = models.DateField(null=True) document_instance_date = models.DateField(null=True) is_a_failure = models.BooleanField(default=False) When I retrieve Employee records, it is very common that I will need to know the following information for each employee records as well: are there any of my EmployeeDocuments that have zero EmployeeDocumentInstance's? how many of my EmployeeDocument.expiration_date values are less than today's date? how many of my EmployeeDocument.near_expiration_date values are less than today's date? I don't … -
"Can't connect to local MySQL Server" using SSH tunnel
Starting an SSH tunnel to MySQL so MySQL Workbench can connect to the remote DB using the following command: ssh -L 3306:localhost:3306 <username>@<domain> -N MySQL Workbench is able to connect without issue doing this. I was also trying to spin up a local copy of the Django application and connect to the remote test DB and I get met with: django.db.utils.OperationalError: (2002, 'Can\'t connect to local MySQL server through socket \'/var/run/mysqld/mysqld.sock\' (2 "No such file or directory")' Looking at the Django settings, everything looks correct. Just seems like Django is ignoring the tunnel despite using the same port. Django is in virtualenv so wonder if something there might be causing it. Any suggestions? -
how to check what port django used on a running server? `manage.py runserver 0.0.0.0:<port>`
I need to troubleshot a django app which already running in a server. I'd like to access the APP URL IP:PORT but I don't know what port former developer used to run it. Eg: manage.py runserver 0.0.0.0:<port> Is there a possibility to check out this used port with something like netstat -ano | grep ... netstat -ano | grep runserver doesn't provide anything. -
Configuring user permissions with django
299/5000 Hi, I wrote an API service with Django. I have authorized the user to list only clients via django admin panel. When I enter the django admin panel with the user name I authorize, there is no problem in the authorization. But when I access the api service, he never sees authority. Can you help me ? api/permissions.py from rest_framework.permissions import BasePermission class IsOwner(BasePermission): def has_permission(self, request, view): return request.user and request.user.is_authenticated message = "you cannot change data that you do not own !" def has_object_permission(self, request, view, obj): return (obj.user == request.user) or request.user.is_superuser views.py class CustomerListAPIView(ListAPIView): serializer_class = CustomerCreateSerializer permission_classes = [IsOwner] filter_backends = [SearchFilter] search_fields = ['customerName', 'customerSurname', 'customerIdentityNo'] def get_queryset(self): queryset = Customer.objects.filter(user=self.request.user) return queryset settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissions' ] } -
How do I prevent a 500 CORS error when attempting to create and download a csv file containing a large data set using python's StreamingHttpResponse?
The function runs and works perfectly fine for a small data set, but for a large data set, the following error is produced: (URL is hidden in the red) A 500 CORS error. As you can see from the code below, I've tried adding multiple response headers to the response (StreamingHttpResponse object) with a focus on extending the amount of time the function can run/execute/query before being timed out. I've also tried adding headers to handle the cross site issue which I don't believe is a problem in the first place because the function works perfectly fine with a small dataset: def create_and_download_csv(self, request): qs = self.filter_queryset(self.get_queryset()) serialized = self.serializer_class(qs, many=True) # mapping csv headers to columns headers = { "column_header": "Column Header", "column_header": "Column Header", "column_header": "Column Header", "column_header": "Column Header", } response = StreamingHttpResponse( renderers.CSVStreamingRenderer().render( serialized.data, renderer_context={'header': headers.keys(), 'labels': headers} ), content_type="text/csv", ) response["Access-control-Allow-Headers"] = "*" response["Connection"] = "keep-alive" response["Content-Disposition"] = 'attachment; filename="status.csv"' response["Access-Control-allow-origin"] = "*" response["Keep-Alive"] = 200 response["Timeout"] = 100 print(response) return response Perhaps I'm placing the headers in the wrong place? Or could it be that the docker container the project runs on is where I should configure the timeout value? Please help if you … -
Django Forms.py Change EmailField Value To Auto Populated value="{{ user.email }}"
I want my Django form's EmailField to auto populate with the user's email. How does this get accomplished? Full Code: https://dpaste.org/4PrR Instead of 'value':'hi' I want 'value':{{ user.email }} Code from forms.py: payment_email = forms.EmailField(widget=forms.TextInput(attrs={'class':'form-control', 'autocomplete':'off', 'type':'email', 'id':'email', 'value':'hi', 'readonly':'readonly'}), required=True) def __init__(self, *args, **kwargs): super(PaymentForm, self).__init__(*args, **kwargs) self.fields['payment_email'].label = "Email:" -
How do I write this Django query with two joins and where clauses?
Considering the following model scheme: class A(models.Model): b = models.ForeignKey(B, on_delete=models.CASCADE) x = models.IntegerField(blank=True, null=True) class B(models.Model): x = models.IntegerField(blank=True, null=True) class C(models.Model): b = models.ForeignKey(B, on_delete=models.DO_NOTHING) y = models.DateTimeField() How do I get the number of C objects from the database limited by a filter by both C.y and A.x? -
Need advice on SaaS project based on Django
I need advice: I want to create a Django App SaaS and Im on the point where I create Database Models. But how can I use a database for each customer without duplicate the code? I read a lot about database routing but nothing I can find passes to my solution. I want to have for each user a database which fits to Customer number example Customer 10001 gets DB 10001 which holds the same standard models plus his articles and configs. Base SQL is a mySQL I think if I just use one database it would out perform and gets slowly. regards Christopher. -
What is the Django query for the below SQL statement?
There is a simple SQL table with 3 columns: id, sku, last_update and a very simple SQL statement: SELECT DISTINCT sku FROM product_data ORDER BY last_update ASC What would be a django view code for the aforesaid SQL statement? This code: q = ProductData.objects.values('sku').distinct().order_by('sku') returns 145 results whereas this statement: q = ProductData.objects.values('sku').distinct().order_by('last_update') returns over 1000 results Why is it so? Can someone, please, help? Thanks a lot in advance! -
UpdateView using FormView
I have a Formview and an UpdateView which are conflicting with each other. They are supposed to work together but not in this way. Whenever I try to use the UpdateView the values get passed through the FormView for saving which causes it to send back form validation errors e.g. 'A video with this Title already exists'. How do I get the UpdateView to not rely on the FormView? Or to work with the FormView? It seems all the UpdateView is doing is pointing to the FormView. FormView: class VideoUploadView(FormView): form_class = VideoUploadForm success_url = '/videos' template_name = 'videos/video_form.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) form.instance.sender = self.request.user if form.is_valid(): form.save() # doing stuff form.save() messages.success(self.request, self.success_message) if request.is_ajax(): return JsonResponse({'success': True, 'url': reverse('videos-home')}) else: return redirect(self.success_url) else: if request.is_ajax(): return JsonResponse({'success': False, 'error': form.errors}) else: return render(request, self.template_name, {'form': form}) UpdateView: class VideoUpdateView(UpdateView): model = Video form_class = VideoUploadForm Urls.py: urlpatterns = [ path('', views.VideoListView.as_view(), name='videos-home'), path('upload/', views.VideoUploadView.as_view(), name='videos-upload'), path('<int:pk>', VideoDetailView.as_view(), name='videos-detail'), path('<int:pk>/delete/', VideoDeleteView.as_view(), name='videos-delete'), path('<int:pk>/viewed/', views.mark_as_viewed, name='mark-as-viewed'), path('<int:pk>/update/', VideoUpdateView.as_view(), name='videos-update'), path('<int:pk>/notify', VideoNotificationView.as_view(), name='videos-notify'), ] -
DJango Error -django.db.utils.DataError: value too long for type character varying(1)
I have been trying to do this data migration and i keep getting this error django.db.utils.DataError: value too long for type character varying(1) My goal is to add a row to the User table here is the migration file I have written, but I cannot find the model that has a max_length of 1 ''' # Generated by Django 2.2.7 on 2019-12-13 14:52 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('shared', '0001_initial'), ] def doit(apps, schema_editor): Tuser = apps.get_model('shared', 'User') nice = Tuser(user_id=True, first_name='Tom', last_name='Beals', membership= 'Di') nice.save() operations = [ migrations.RunPython(doit), ]``` here is my models.py file. (the model I referencing is the last one) # Create your models here. class Games(models.Model): game_id=models.AutoField(primary_key=True) game_name=models.CharField(max_length=15) game_odds=models.DecimalField(max_digits=5, decimal_places=2) class GameAccount(models.Model): game_account_id=models.AutoField(primary_key=True) class Deck(models.Model): image = models.ImageField(upload_to='images/deckOfCards/') suit = models.CharField(max_length=30) rank = models.CharField(max_length=30) worth = models.IntegerField() class Dice(models.Model): image = models.ImageField(upload_to='images/dieFace/') side = models.IntegerField class Rooms(models.Model): BED_CHOICES=[ ('S', 'Single'), ('D', 'Double'), ('Q', 'Queen'), ('K', 'King'), ] FLOOR_CHOICES = [ ('1', 'First'), ('2', 'Second'), ('3', 'Third'), ('4', 'Fourth'), ] room_num=models.AutoField(primary_key=True) room_price=models.DecimalField(max_digits=5, decimal_places=2) room_bed=models.CharField(max_length=30, choices=BED_CHOICES) room_floor=models.CharField(max_length=30, choices=FLOOR_CHOICES) class UserAuth(models.Model): user_auth_id=models.AutoField(primary_key=True) user_username=models.CharField(max_length=30) user_pass=models.CharField(max_length=12) class UserHistory(models.Model): user_history_id=models.AutoField(primary_key=True) previous_account_balance=models.DecimalField(max_digits=5, decimal_places=2) average_user_stay=models.DateTimeField() class UserAccount(models.Model): user_account_id=models.AutoField(primary_key=True) user_account_alias=models.CharField(max_length=30) user_account_balance=models.DecimalField(max_digits=5, decimal_places=2) user_account_image=models.ImageField(upload_to='images/userAccountImage/') class UserResortConfig(models.Model): user_resort_config_id=models.AutoField(primary_key=True) is_return_user=models.BooleanField() class UserResortData(models.Model): user_resort_data_id=models.AutoField(primary_key=True) … -
Django missing 1 required positional argument "username"
My error: create_superuser() missing 1 required positional argument: 'username' def create_superuser(self, email, username, password): user = self.create_user( email = self.normalize_email(email), password=password, username = username, ) user.is_admin = True user.is_superuser = True user.save(using=self._db) return user what is the problem? -
django dynamic custom queryset
I have a table to store view events, that is, if a user views an entity, a record will be stored into that table. This table is represented by a model that has a generic relation, that is, it can be related to any other model. I have defined a mixin ViewTracked that should be extended by any model that can be tracked (i.e. class SomeModel(ViewTracked)). I want to have a custom method for queryset of objects manager called custom_method for example. I know that I can define a custom Manager and override the objects manager with it easily, but the problem is that the tracked model can already have a custom manager that has his own custom queryset, so I can't simply override it and lose the custom queryset that it has. Unfortunately, I couldn't find a proper way of doing this, so I tried to add a metaclass to override the manager's get_queryset and add my custom method to it, but for some reason, when I call SomeModel.objects it always returns None. Here's what I tried: # Meta class class ViewTrackedMeta(ModelBase): def __new__(mcs, class_name, base_classes, attributes_dict): # let ModelBase do its magic new_class = super().__new__(mcs, class_name, base_classes, attributes_dict) … -
Change Django Form Attribute on view
I'm using a Django Form with a DatePicker widget. I have to define the Min and Max date of the datepicker on a class level. I would like to have these two values change when I run my view, otherwise, it keeps the Min and Max date values from the time that I start my django server. from django import forms from bootstrap_datepicker_plus import DatePickerInput import pandas as pd import datetime as dt MIN_DATE = dt.datetime.today().strftime('%m-%d-%Y') MAX_DATE = (dt.datetime.today() + dt.timedelta(days=92)).strftime('%m-%d-%Y') class TableEdit(forms.Form): Account = forms.CharField(label='Account', max_length=10) Hedge = forms.CharField(label='Hedge', max_length=10) Date = forms.DateField(widget=DatePickerInput( options={ 'format': 'MM/DD/YYYY', 'minDate': MIN_DATE, 'maxDate': MAX_DATE })) How can I modify my MIN_DATE and MAX_DATE form attributes everytime that I call my form from a view? Thank you -
Python - Is there a way to memoize calculations after serialization?
Is there a way to memoize or cache some calculations after serializing a queryset using Django REST? I need to group array of objects by some property. This calculation happens every request, but the serialized data is not dynamic at all, it changes every 1-2 days, so I want to cache it somehow. class ServiceViewSet(viewsets.ModelViewSet): queryset = Service.objects.all() serializer_class = ServiceSerializer def list(self, request, *args, **kwargs): service_list = self.serializer_class(self.queryset, many=True).data # I want to memoize calculations below groupped_services = defaultdict(list) for service in service_list: category_model = service.get('category_m', None) if category_model: groupper = category_model.get('category_title') groupped_services[groupper].append(service) return Response(groupped_services) Maybe it would be even more useful to memoize serialization as well? But I don't know how to do that.