Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass a filter from a dropdown into django-import-export view
I understand on how to pass a filter through views that have the return render(request, 'htmlname.html, {}). I don't know how to do it for this case of exporting data through django-import-export export option. I'd like to pass a filter from a dropdown selection for the data to be downloaded. My view def ExportStudentsView(request): dataset = ExportStudentsResource().export(school = request.user.school,klass = ?????????) response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="All students.xls"' return response My resource class ExportStudentsResource(resources.ModelResource): def export(self, queryset = None, *args, **kwargs):#this method helps capture the current user school queryset = Students.objects.filter(school = kwargs['school'],klass = kwargs['klass']) return super(ExportStudentsResource, self).export(queryset, *args, **kwargs) klass__name = fields.Field(attribute = 'klass__name',column_name='class')#Changes column name from school__name to school stream__name = fields.Field(attribute = 'stream__name',column_name='stream') gender__name = fields.Field(attribute = 'gender__name',column_name='gender') class Meta: model = Students fields = ('adm','name','kcpe','klass__name','stream__name','gender__name','notes') export_id_fields = ('adm',) export_order = ('adm','name','kcpe','klass__name','stream__name','gender__name','notes') -
How to validate a column value in a csv file imported, and give validation error if not present in django
Here I'm trying to get the individual column value from the uploaded file and trying to retrieve a validation for a column not present in the csv checking if the file uploaded is a csv or not if not give a error saying unsupported file format, if a csv then check for the column inside and if any of the column is missing give a validation saying " * " column is not present. here is a part of csv file time,amplitude 0,0.73904 0.02441,1.2372 0.04883,1.0019 0.07324,0.50924 0.09766,-0.603 0.12207,-1.6674 0.14648,-1.5332 0.1709,-0.85486 0.19531,0.3971 0.21973,1.3604 0.24414,1.8384 my validation.py file def validate_file(value): ext = os.path.splitext(value.name)[1] valid_extentions = ['.csv'] if ext.lower() in valid_extentions: return value else: raise ValidationError(u'Unsupported file extention. please upload a .csv file. ') csv = pd.read_csv(value, header=0, nrows=0).columns.tolist() first = csv.index('time') second = csv.index('amplitude') if first != 0: raise ValidationError(u'Missing time value data') elif second != 1: raise ValidationError(u'Missing Amplitude value data') else: return value I've used this but not getting any validation even tho I give a csv without a time column value, please be free to ask for any requirements in the question, thank you in advance. -
Django REST API AttributeError - The serializer field might be named incorrectly and not match any attribute or key on the `list` instance
I am getting the following error message - AttributeError at /analysisapis/constituents Got AttributeError when attempting to get a value for field strings on serializer ConstituentNameLists. The serializer field might be named incorrectly and not match any attribute or key on the list instance. Original exception text was: 'list' object has no attribute 'strings'. My Model is as follows - Note - This is common Model used from Django Website as well. from django.db import models, connection from django.urls import reverse from . import queries as queries # Create your models here. class ISMASymbol(models.Manager): ''' Used to Manage the Symbol ''' def __init__(self): ''' Initialize the Class instance ''' self.symbol = 'NIFTY50' self.tablename = 'NIFTY50' self.exists = 2 self.message = 'NIFTY50 exists.' self.close = 0 self.change = 0 self.returns = 0 self.band = 0 self.upperband = 0 self.lowerband = 0 self.lotsize = {0:0, 1:0, 2:0} self.stepvalue = 0 self.weekly_expiry = True self.weekly_future = False self.isIndex = True self.cashstocks = [] self.derivativestocks = [] self.indexlist = [] self.companyname = 'NIFTY 50' self.has_fno = True SOME ADDITIONAL FUNCTIONS def get_symbol_list(self): ''' Creates a Symbol List for all Cash and Derivatives Used to Create Sitemap ''' symbol_query = queries.symbol_list derivative_query = queries.derivative_list index_query = … -
Migrations File Error When Migrate Django Project
I have a Django project created by Django 1.x few years ago and I want migrate to Django 3. When I test the updated project, it show errors in the migration files that the ForeignKey field missing the "on_delete" argument. Since the "on_delete" argument is optional in Django 1 but mandatory in Django 3. Is there any easy way to fix those errors? Should I need to manually remove all ".py" and ".pyc" files in migrations directory of the app? If I remove the files, will it affect the data in database and the migration processes in future? Thanks, Wilson -
Django template only first loop appears
I wanted to add some custom context to a ListView context like this: class WeatherListView(ListView): """ List view of Weather data """ template_name = "frontend/weather_list.html" model = Weather def get_context_data(self, **kwargs): weather_query = Weather.objects.all() temp_list = list(weather_query.values_list('temperature', flat=True)) humidity_list = list(weather_query.values_list('humidity', flat=True)) temp_list_compared = compare_item_to_previous(temp_list) humidity_list_compared = compare_item_to_previous(humidity_list) data = super().get_context_data(**kwargs) context = { "object_list": zip(data["object_list"], temp_list_compared, humidity_list_compared) } print("context ", context) return context My models.py class Weather(models.Model): temperature = models.FloatField( validators=[MaxValueValidator(28), MinValueValidator(19)] ) humidity = models.FloatField( validators=[MaxValueValidator(65), MinValueValidator(35)] ) time_recorded = models.DateTimeField(auto_now_add=True, blank=True) But when I try to loop through them in the template only the first loop works like this: {% for i in object_list %} {{ i.0.temperature }} {{ i.1 }} {% endfor %} {% for i in object_list %} {{ i.0.humidity }} {{ i.2 }} {% endfor %} expected result is 11.0 12.0 13.0 1 2 3 20.0 22.0 23.0 1 2 3 But what I get is this: 11.0 12.0 13.0 1 2 3 if I switched them put the second loop first it will work and the other one won't. -
How to retrieve string data from many to many form field in django
I'm programming using django, and I encountered the following issue. This might be a little complicated, but I would like to make the following while loop work in a form_valid function in my view. First of all, here is the loop: i = 0 while i <= days: days_added = i current_end = class_start_date + datetime.timedelta(days=days_added) str_current_end = str(current_end) current_end_day = calendar.day_name[datetime.datetime.strptime(str(current_end), '%Y-%m-%d').weekday()] if current_end_day == 'Saturday' or current_end_day == 'Sunday': days = days + 1 elif str_current_end == '2021-04-09' or str_current_end == '2021-04-13': days = days + 1 elif all_weekdays[0] != current_end_day or all_weekdays[1] != current_end_day or all_weekdays[2] != current_end_day or all_weekdays[3] != current_end_day or all_weekdays[4] != current_end_day: days = days + 1 i += 1 There are more to the code in the form_valid function to actually make this while loop work, but my problem is only with the last elif statement that contains all_weekdays. You see, I defined all weekdays as all_weekdays = form.instance.weekday.all() before I started the while loop. Here, weekday is a "many to many field" in the form submitted by the user. Basically, the user could select multiple options from Monday to Friday, which will be stored in the weekday. Also, current_end_day is just … -
how can i pass a list to objects.get in Django
I'm working on a small project using Django / Rest Framework I would like to know if there is any way to pass a list like that mycontact = Contact.objects.get(id=[14,26,44,88]) instead of mycontact = Contact.objects.get(id=14) -
Is there a way to build instant messaging inside an existing WSGI django web application?
So I spent all this time building and going through basic tutorials for geolocation and even payment processing. I'm finally at the step where I want the users to be able to contact each other. Is there a way for me to put ASGI within WSGI? -
Filter Django Queryset to return followers of logged in user only
I am trying work out how filter who follows the logged in user/who is followed by the logged in user using Django Rest Framework. However, all I seem to be returning is ALL users who have been followed by any user or are following any user, it is not specific to the logged in user (the front end view (numbers are the user PK), the API view). I make a GET Request with the pk of the logged in user via an AJAX call but can't seem to filter specifically against that. I'd be grateful for any help! Here is my model: class UserConnections(models.Model): follower = models.ForeignKey(User, related_name="following", on_delete=models.CASCADE) followed = models.ForeignKey(User, related_name="followers", on_delete=models.CASCADE) Here are the relevant serializers: class UserConnectionListSerializer(serializers.ModelSerializer): class Meta: model = UserConnections fields = ['follower','followed'] class UserConnectionSerializer(serializers.ModelSerializer): class Meta: model = UserConnections fields = '__all__' depth = 2 Here is the views.py # gets list of who logged in user is following class FollowingViewSet(viewsets.ModelViewSet): serializer_class = serializers.UserConnectionListSerializer queryset = UserConnections.objects.all() def get_serializer_class(self): if self.request.method == 'GET': return serializers.UserConnectionSerializer return self.serializer_class def get_followers(request): if request.method == "GET": user_id = self.request.GET.get('current_user_id', None) return UserConnections.objects.filter(follower__id=user_id) # gets list of followers who follow logged-in user class FollowerViewSet(viewsets.ModelViewSet): serializer_class = serializers.UserConnectionListSerializer … -
OSError: [Errno 9] Bad file descriptor HELP I CANT SOLVE IT
I hope you can help me, I have been working with the raspberry socket, linked together with android studio. I have this code, it is to turn on an LED through the mobile, however, when I run the program it does not throw errors, but when I press the button on the mobile, it throws me the error BUT if I turn off the LED, if I compile again and run the program, I press the button, it throws me the error BUT the LED turns off. I do not know how to solve it, I have read several solutions but it does not work for me import socket, time, RPi.GPIO as GPIO GPIO.setwarnings (False) GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.OUT) #UDP_IP = "192.168.100.15" #ip del socket UDP_PORT = 2000 #Puerto del socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('',UDP_PORT)) sock.listen(5) while True: sock, addr = sock.accept() r = sock.recv(256) print("Conexión de %s" % str(addr), " Recibido %s" % r) if r.decode('utf-8') == 'A': GPIO.output(17,True) if r.decode('utf-8') == 'B': GPIO.output(17,False) sock.close() gpio.cleanup() it gives me this error Conexión de ('192.168.100.3', 37580) Recibido b'B' Traceback (most recent call last): File "/home/pi/Desktop/wifi.py", line 16, in <module> sock, addr = sock.accept() File "/usr/lib/python3.7/socket.py", line 212, in accept fd, … -
view.py got an unexpected keyword argument topic_id #p
I'm trying to fix this view keep getting this error message, ''' Exception Type: TypeError Exception Value: topics() got an unexpected keyword argument 'topic_id' Exception Location: /home/draco/shola/learning_log/lib/python3.8/site-packages/django/core/handlers/base.py, line 181, in _get_response ''' view.py def topics(request): topics = TopicModel.objects.order_by('date_added') context = {'topics' : topics} return render(request, 'learning_logs/topics.html',context) def topic(request, topic_id): topic = TopicModel.objects.get(id=topic_id) entries = topic.entry_set.order_by('date_added') context = {'topic':topic, 'entries': entries} return render(request,'learning_logs/topic.html',context) urls.py url(r'^$', views.index, name='index.html'), url(r'^topics/$',views.topics, name='topics.html'), url(r'^topics/(?P<topic_id>\d+)\$',views.topics,name='topic.html') models.py from django.db import models class Topic(models.Model): text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.text class Entry(models.Model): topic = models.ForeignKey(Topic, on_delete = models.DO_NOTHING) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): if len(self.text) >50: return self.text[:50]+"....." else: return self.text Template <!DOCTYPE html> {% extends "learning_logs/base.html" %} <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% block content%} <p>Topics</p> <ul> {%for topic in topics%} <li> <a href="{% url 'learning_logs:topic.html' topic.id %}">{{topic}}</a> </li> {%empty%} <li>no topic have been added yet</li> {%endfor%} </ul> {%endblock content%} </body> </html> -
[DJANGO]: How to pass a Django form field value to a template form action?
I have a Django form that asks for id number. Hence, when the user clicks on submit, that id number is passed as a parameter to the endpoint. This URL path('verify/nin/', views.post_nin, name='post_nin') contains the form and asks for the id number while I am submitting the data to this URL to path('nin/<str:nin>', views.nin_verification_vw, name="nin_verification") So I expect to be redirected to http://127.0.0.1:8000/api/nin/15374020766 but instead it is redirecting me to http://127.0.0.1:8000/api/nin/%3Cinput%20type=%22text%22%20name=%22nin%22%20required%20id=%22id_nin%22%3E?nin=15374020766&csrfmiddlewaretoken=u5UmwDW4KRUIvYWXAa64J8g1dTPoJ3yDqtoCuKjboIE2TNxI3tPbjPmCK6FztVwW How do I avoid the unnecessary parameters? Here is my forms.py: class NINPostForm(forms.Form): """Form for a user to verify NIN""" nin = forms.CharField(required=True, help_text='e.g. 123xxxxxxxx') # check if the nin is a valid one def clean_nin(self): nin = self.cleaned_data['nin'] regex = re.compile("^[0-9]{11}$") if not regex.match(nin): raise forms.ValidationError("NIN is incorrect.") return nin Here is my views.py: def post_nin(request): submitted = False if request.method == 'POST': form = NINPostForm(request.POST) if form.is_valid(): cd = form.cleaned_data['nin'] return HttpResponseRedirect('/verify/nin?submitted=True') else: form = NINPostForm() context = { 'form': form, # 'cd': cd, } return render(request, 'ninform.html', context) And here is my HTML template: <form action="{% url 'nin_verification' form.nin %}" method="POST"> <table> {{ form.as_table }} <tr> <td><input type="submit" value="Submit"></td> </tr> </table> {% csrf_token %} </form> -
Django unable to load psycopg2 module. Python is also unable to load it, even though I see it when i run pip list
I cloned my personal project from my git repository onto my new laptop (mac, big sur, M1 chip) and I'm having some trouble with psycopg2. I was able to get psycopg2 installed after a decent amount of headache. All my dependencies should be installed. Now, when I type python3 manage.py runserver I am greeted with the following error: Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/jeff/Desktop/Project-BookBuddy/BookBuddy/env/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 25, in <module> import psycopg2 as Database File "/Users/jeff/Desktop/Project-BookBuddy/BookBuddy/env/lib/python3.9/site-packages/psycopg2/__init__.py", line 51, in <module> from psycopg2._psycopg import ( # noqa ImportError: dlopen(/Users/jeff/Desktop/Project-BookBuddy/BookBuddy/env/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so, 2): Symbol not found: _PQbackendPID Referenced from: /Users/jeff/Desktop/Project-BookBuddy/BookBuddy/env/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so Expected in: flat namespace in /Users/jeff/Desktop/Project-BookBuddy/BookBuddy/env/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/Users/jeff/Desktop/Project-BookBuddy/BookBuddy/env/lib/python3.9/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/jeff/Desktop/Project-BookBuddy/BookBuddy/env/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/Users/jeff/Desktop/Project-BookBuddy/BookBuddy/env/lib/python3.9/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/Users/jeff/Desktop/Project-BookBuddy/BookBuddy/env/lib/python3.9/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/Users/jeff/Desktop/Project-BookBuddy/BookBuddy/env/lib/python3.9/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/jeff/Desktop/Project-BookBuddy/BookBuddy/env/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/jeff/Desktop/Project-BookBuddy/BookBuddy/env/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/jeff/Desktop/Project-BookBuddy/BookBuddy/env/lib/python3.9/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in … -
How to add these two elements in my webapp?
I'm doing this django How can I add these two elements in my web app using HTML, CSS, or JavaScript the elements marked in this image below? [1]: https://i.stack.imgur.com/XlIjp.jpg -
Matching array fields containing tags in Django as Trigram only accepts text and not list
Basically I need to match a requested product tag list with other products tag list and prepare the queryset to be reflected as similar products. Models.py title = models.CharField(max_length=300) tags = ArrayField(models.CharField(max_length=100), default=list,null=True,blank=True) Views.py product = Product.objects.all().filter(slug=slug) similar_products = Product.objects.annotate( similarity=TrigramSimilarity('title',product.title),).filter(similarity__gt=0.1).order_by('-similarity') Matching with title field works but as soon as I try to use 'tags' and product.tags to match, it throws error function similarity(character varying[], text[]) does not exist A sample tag list looks like [motor,helmet,bluetooth,speakers] -
how to add a new record to a Many To Many Field
I'm working on a small project using Django / Rest Framework, I have two models ( Contact & List ) I have Many To Many field, in Contact called list. I would like to know how can I add a record to this relation ( Many To Many Field ). from django.db import models # Create your models here. class List(models.Model): name = models.CharField(blank=False, max_length=255) comment = models.CharField(blank=False, max_length=255) private = models.BooleanField(default=False) allowed = models.BooleanField(default=False) def __str__(self): return self.name This is my Contact Model from django.db import models from django.conf import settings from list.models import List # Create your models here. class Contact(models.Model): # field variables language_choices = ( ('french', 'french'), ('english', 'english'), ) """ Relations Between Models """ list = models.ManyToManyField(List) -
Django DRF elastic search dsl, Apply functional boosting based on another field numerical value
I am trying to tune the relevance of my field search result based on another field numerical value (the field is in another model). Looking at the ES documentation it seems that functional boosts is what I need for my usecase. Note that I am using the django-elasticsearch-dsl; package. My use case: I have a search field where users can search for companies based on the company name. I want to return the company names that match the query where sorting (relevance) depends on the company's net asset, where the higher the number, the more relevant (field in another model) Model definition: class Company(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, blank=False, null=False) def __str__(self): return self.name class CompanyNetAsset(models.Model): id = models.AutoField(primary_key=True) assets = models.IntegerField company_id = models.ForeignKey('Company', on_delete=models.PROTECT, blank=True, null=True) def __str__(self): return self.name my es document: ... custom_stop_words = token_filter( 'custom_stopwords', type='stop', ignore_case=True, stopwords=['the', 'and'] ) html_strip = analyzer( 'html_strip', tokenizer="standard", filter=["lowercase", "asciifolding", custom_stop_words], char_filter=["html_strip"], ) @INDEX.doc_type class CompanyDocument(Document): id = fields.IntegerField(attr='id') name = fields.TextField( analyzer=html_strip, fields={ 'raw': fields.TextField(analyzer='keyword'), } ) class Django: model = Company and here is the DocumentViewSet: class CompanyDocumentViewSet(DocumentViewSet): """The Company Document view.""" serializer_class = CompanyDocumentSerializer lookup_field = 'id' document = CompanyDocument filter_backends = [ … -
Multiply three table in DJANGO without raw_sql
I have three models in Django that we could schematize like this : class A(models.Model): b = models.ForeignKey(B, on_delete=models.CASCADE) class B(models.Model): c = models.ForeignKey(C, on_delete=models.CASCADE) class C(models.Model): data = models.IntegerField() My aim is to make a query equivalent to : select * from A, B, C where a.b=b.id and b.c=c.id; My question is : Is there a way to make this query without using raw sql ? -
What is the best practice to architect tasks processing using AWS?
I am wondering about how to configure lambda, sns, and sqs for processing background tasks. There are three ways I thought. Option 1. A function called consumer can execute workers by receiving tasks from the queue. Option 2. Send all tasks to SNS. One worker and one SQS receive and work from SNS. Option 3. Directly forward the task to one SQS and one lambda from the APP. The biggest concern is whether to directly invoke Lambda in the app or use task consumer using SQS or SNS. My paintings will help you understand My idea is from Triggering multiple lambda functions from one SQS trigger -
Django, How to display Bid History made on that listing
How can I display only the history of Bids for each specific listing? Right now my page shows all the Bids history no matter for what listing on the website Models.py class AuctionListing(models.Model): title = models.CharField(max_length=100) description = models.TextField() start_bid = models.IntegerField(null=True) image = models.CharField(max_length=1000, blank=True) category = models.CharField(max_length=100) seller = models.CharField(max_length=100, default="Default_Value") def __str__(self): return f"{self.title} listing | {self.seller}" class Bid(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_bids") listing = models.ForeignKey(AuctionListing, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) bid_time = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.user} put a bid in for {self.price}" Views.py def view_bids(request, product_id): return render(request, "auctions/view_bids.html") view_bids.html {% extends "auctions/layout.html" %} {% block title %} Item Bid History {% endblock %} {% block body %} <div class="col-md-5"> <div class="thumbnail text-center"> <h4>Bid History</h4> {% for user in user.user_bids.all %} <strong> {{user.user}} - {{user.price}}$ - {{user.bid_time}} </strong> <br> {% endfor %} </div> </div> {% endblock %} Thanks for any help :) -
Django REST Implement Custom Authentication for specific API views
My requirement is quite different, i have already implemented Django Rest framework and rest_auth for my my api and the views authenticating with bearer token which generated by django rest framework and rest_auth I have an API for public user, who will subscribe to my application, then will generate API token by their own and it will be used only for a specific API views. For example, aws, google, facebook, has its own API and their end user can delete/generate new token orsecret key by their own to authenticate their particular API. I have the same requirements, I want, user should able generate/delete/disable API key from the web gui by their own. Can anyone please tell me how can i make it possible with django rest framework? -
Can't import python script into another script
I'm trying to import a python script twitter.py into my views.py, whilst working in Django. This file exists in the same directory as my views.py file. Whenever I tried to run python manage.py runserver command from the terminal to open my web page locally, I receive: *ModuleNotFoundError: No module named 'twitter'* Things I've tried: putting twitter.py in a new folder in the directory, and adding __ init __.py (no spaces) to that directory so python reads it as a module The directory both files exist are already in my PYTHONPATH I didn't post any code because this is a fairly trivial issue that I never thought I'd have trouble solving. Thanks -
djqgrid: No module named 'json_helpers'
I'm trying to use JQGrid in a Django web application I've done a pip install of django-jquery==3.1.0 djqgrid==0.2.4 But when I "runserver" I get the following error message:- File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\aabel\PycharmProjects\djangoWithJQGrid\djangoWithJQGrid\urls.py", line 19, in <module> from Accounts.views import account_list_view File "C:\Users\aabel\PycharmProjects\djangoWithJQGrid\Accounts\views.py", line 11, in <module> from djqgrid.columns import TextColumn File "C:\Users\aabel\PycharmProjects\djangoWithJQGrid\venv\lib\site-packages\djqgrid\columns.py", line 4, in <module> from json_helpers import function ModuleNotFoundError: No module named 'json_helpers' In my urls.py I have:- urlpatterns = [ path('', account_list_view, name='home'), ... ] In Accounts.views.py I have:- from djqgrid.columns import TextColumn from djqgrid.grid import Grid class AccountGrid(Grid): model = Account account_id = TextColumn(title='account_id', model_path='account_id') name = TextColumn(title='name', model_path='name', align='right') def account_list_view(request): grid = AccountGrid() return render(request, 'account_list.html', { grid: grid }) I know that 'json_helpers' is part of the djqgrid package (which I installed with pip). So am I missing a reference to it somewhere? Thanks. -
Caching queryset in django rest framwork?
I have a large queryset and I have a Paginator for the generics.ListAPIView. I want to cache that queryset with its all page, but i think it doesn't work that way. I've been trying to figure out how to cache the queryset with the Paginator but I don't seem to find a way to make it work with Django Rest. this is my pagination class: class StandardPagesPagination(PageNumberPagination): page_size = 35 def get_paginated_response(self, data): return Response({ 'links': { 'next': self.get_next_link(), 'previous': self.get_previous_link() }, 'count': self.page.paginator.count, 'total_pages': self.page.paginator.num_pages, 'results': data }) and this is my view: class OyunlarList(generics.ListAPIView): # queryset = Oyunlar.objects.all() filter_backends = [DjangoFilterBackend,filters.SearchFilter,filters.OrderingFilter] search_fields=['title'] filterset_fields=['categories__name','platform','categories__category_id','game_id'] ordering_fields = ['title', 'release_date','click_count','popularite'] pagination_class = StandardPagesPagination serializer_class = OyunlarSerializer def get_queryset(self): queryset=Oyunlar.objects.all().order_by('click_count').prefetch_related('categories') #queryset=Oyunlar.objects.raw("select 'game_id' AS id,'title','base_price','en_ucuz' from oyunlar ") return queryset @method_decorator(cache_page(60 * 3)) def dispatch(self, *args, **kwargs): return super(OyunlarList, self).dispatch(*args, **kwargs) I want to give user a more smooth experience. -
How to only require min in forms.dateinput if the date is changed
I have a form with a dateinput which I would like to only have change the due date in case the user decides to input a new date. here's my form: class TaskCreateForm(forms.ModelForm): class Meta: model = Task fields =["task_name", "assigned_to", "status", "deadline", ] widgets = { 'deadline': forms.DateInput(attrs={'min': timezone.localdate(), 'type':'date'}), } Here's my view: class TaskUpdate(UpdateView): model = Task template_name = "todo_list/task_update.html" form_class = TaskCreateForm success_url = reverse_lazy('tasks') and here's my template: <h1>Update Task</h1> <a href="{% url 'tasks' %}">go back</a> <form method="POST" action=""> {% csrf_token %} {{form.as_p}} <input type="submit" value="Submit"> </form> Any help is much appreciated. Thank you in advance