Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save all related data using django signals post_save
I just want that if the admin select Course(ABM) and Education Level (Grade 11) it will save all related data in subjectsectionteacher(second picture) and it will automatic save to student enrolled subject(third picture) my problem is only one data save. this is my code in models.py class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE, null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True,null=True) class SubjectSectionTeacher(models.Model): School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Sections = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Employee_Users = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True) class StudentsEnrolledSubject(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE, null=True) Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE, null=True,blank=True) @receiver(post_save, sender=StudentsEnrollmentRecord) def create(sender, instance, created, **kwargs): teachers = SubjectSectionTeacher.objects.all().filter(Sections=instance.Section,Education_Levels=instance.Education_Levels) if created and teachers.exists(): StudentsEnrolledSubject.objects.update_or_create( # This should be the instance not instance.Student_Users Students_Enrollment_Records=instance, # The below is also not an instance of SubjectSectionTeacher Subject_Section_Teacher=teachers.first()) -
best method to mock http request without use of url in django
I have 2 class like below I don't have url path for class A what is the best method to test process_get? I tried mocking a http request with request in rest_framework.request but they don't let me set query_params witch i need to set class A(APIView): def process_get(self, request, form): pass class B(A): def get(self,request) pass -
Use jinja2 with some django apps but not others?
I cannot seem to get Django to use its default Templates engine for the admin app and use Jinja2 everywhere else. It seems that no matter what I do, I can only ever get one of the two to work at any one time. I've tried reordering whether the Jinja or DjangoTemplates block goes first, adding/removing stuff from the DIRS field, and setting APP_DIRS to False. I either break it all (either with a TemplateNotFound or wrong syntax when the wrong backend tries to render) or only get one of the two functioning. I'm using the django-jinja pip package, which lets me leave my templates in the templates folder instead of moving them to a jinja2 directory. TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, }, { "BACKEND": "django_jinja.backend.Jinja2", "DIRS": [os.path.join(BASE_DIR, "templates")], "APP_DIRS": True, "OPTIONS": { "match_extension": ".html", "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", "django.contrib.auth.context_processors.auth", "django.template.context_processors.i18n", "django.template.context_processors.media", "django.template.context_processors.static", "django.template.context_processors.tz", ], "match_regex": r"^(?!admin/).*", }, }, ]``` (OK, I think I can get rid of a bunch of those processors that I'm pretty sure I'm not using, but that's a separate issue) -
form is not getting updating after submitting like button
When submitting the button after clicking like it is creating the object successufuly but like field is updating with null value and django is getting error 302. Can somebody please help me with this. models.py Codes in models.py class VoteManager(models.Manager): def get_vote_or_unsaved_blank_vote(self,song,user): try: return Vote.objects.get(song=song,user=user) except ObjectDoesNotExist: return Vote(song=song,user=user) class Vote(models.Model): UP = 1 DOWN = -1 VALUE_CHOICE = ((UP, "👍️"),(DOWN, "👎️"),) like = models.SmallIntegerField(null=True, blank=True, choices=VALUE_CHOICE) user = models.ForeignKey(User,on_delete=models.CASCADE) song = models.ForeignKey(Song, on_delete=models.CASCADE) voted_on = models.DateTimeField(auto_now=True) objects = VoteManager() class Meta: unique_together = ('user', 'song') views.py Codes in views.py class SongDetailView(DetailView): model = Song template_name = 'song/song_detail.html' def get_context_data(self,**kwargs): ctx = super().get_context_data(**kwargs) if self.request.user.is_authenticated: vote = Vote.objects.get_vote_or_unsaved_blank_vote(song=self.object, user = self.request.user) if vote.id: vote_url = reverse('music:song_vote_update', kwargs={'song_id':vote.song.id,'pk':vote.id}) #'pk':vote.id else: vote_url = reverse('music:song_vote_create', kwargs={'song_id':vote.song.id}) vote_form = SongVoteForm(instance=vote) ctx['vote_form'] = vote_form ctx['vote_url'] = vote_url return ctx class SongVoteCreateView(CreateView): form_class = SongVoteForm model = Vote def get_success_url(self,**kwargs): song_id = self.kwargs.get('song_id') return reverse('music:song_detail', kwargs={'pk':song_id}) def form_valid(self, form): user = self.request.user song_obj = Song.objects.get(pk=self.kwargs['song_id']) vote_obj, created = Vote.objects.get_or_create(song = song_obj, user = user) form.instance = vote_obj return super(SongVoteCreateView).form_valid(form) class SongUpdateView(UpdateView): form_class = SongVoteForm model = Vote def form_valid(self, form): user = self.request.user song_obj = Song.objects.get(pk=self.kwargs['song_id']) vote_obj, created = Vote.objects.get_or_create(song = song_obj, user = user) form.instance … -
I have created custom button in Django admin and when we click on it it should call views.py function and put some static value on admin form
from hellogymapp.admin import BillingAdmin,TechAdmin def get_changeform_initial_data(self, request): return { 'tickets_open': 145, 'tickets_closed' :123 } -
How to post request to my backend server with long string argument by Graphql
I wanna post a request from my website to back-end (django) by GraphQL. Here is my GraphQL request. Probably because the argument is too long, the request cannot reach my server but there is no error threw by Graphql which still show the status "200". How can I solve this problem? { sendMail(mailList: "abv@gmail.com abv@gmail.com abv@gmail.com abv@gmail.com ........... (1000 mail here )", content: "testing") { data { counter } ok } } -
One model for multiple raw query
I have multiple raw query. eg => raw query 1 : select field1,field2 from employee raw query 2 : select field3,field4 from employee Of course, the actual query will more complex than this and Now I have to create multiple models for each of raw queries. model1 : field1,field2 model2 : field3,field4 I just want to know can I create one big model like that => bigmodel : field1,field2,field3,field4 and for query 1, It will return field 1 and field 2 with values and field 3 and field 4 with null. for query 2, It will return field 3 and field 4 with values and field 1 and field 2 with null. It's possible? otherwise, I have to create a lot of models for each query. -
Are HStoreFields the only way to store key:value pairs using Django models?
I am looking to track user views of specific objects. e.g. if a user watches a specific video 3x I want to be able to see how many times that user has watched that specific video. One way of doing this would be tracking user history on every page through the use of GenericForeignKeys and ContentTypes but I read in TSoD that it is best to avoid GenericForeignKeys whenever possible - and for good reason. The other way to do this would be to store key:value pairs in the database and increment the value each time a user visits the page. To do this you would use an HStoreField. The issue with this is that it is PostgreSQL specific while I am still on the SQLite db Django starts off with. This isn't much of an issue because I planned to switch to PostgreSQL anyways but the whole scenario has me wondering: is there another way to accomplish this task that I am not seeing in all my research? Much thanks for any input in advance! -
Python functions are called too soon in Django
Even if I assign it to a variable, the API call triggers too soon. I've implemented a few ideas, as shown in the examples (not the actual code, but same principles). """ Example #1 """ fruit = 'banana' def search_engine(fruit): engine = { 'apple': google.search(Time="10 hours ago"), 'banana': yahoo.searchNow(Time="12 min ago"), 'pear': bing.searchNow(Time="13h ago"), } print(engine[fruit]) search_engine(fruit) """ Example #2 """ fruit = 'banana' def search_engine(fruit): GS = google.search(Time="10 hours ago") YS = yahoo.searchNow(Time="12 min ago") BS = bing.searchNow(Time="13h ago") engine = { 'apple': GS, 'banana': YS, 'pear': BS, } print(engine[fruit]) Let's assume that Time is an improper value, and will throw an exception regardless. in Example #1, however, "apple" is called first and throws an exception, when "banana" should be called instead. In Example #2, it throws an exception at "GS = google.search(Time....", instead of doing it for "YS = yahoo.searchNow..." I've only had this issue since trying to integrate my Python project into Django. -
Access-Control-Allow-Origin is set, but I'm still getting CORS Error
I'm trying to connect my a React Application to a Django Server. The React application is running on http://127.0.0.1:3000/ The response headers has Access-Control-Allow-Origin: http://127.0.0.1:3000 set, yet I am still seeing the error. I am currently using Django's corsheaders package as recommended everywhere. Decent example of the recommendation How can I enable CORS on Django REST Framework. But I have also tried custom middleware at this point. My Django Settings.py file contains the following MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] Django is on 8000, React on 3000 CORS_ORIGIN_WHITELIST = [ 'http://127.0.0.1:3000', 'http://localhost:3000', 'http://127.0.0.1:8000', 'http://localhost:8000', ] My request in react looks like this. (It works when I run it directly, not through the browser) const fetch = require('node-fetch') const response = await fetch( url, { json: true, method: 'GET', headers: { 'Access-Control-Allow-Origin': '*', Accept: '*/*', 'Content-Type': 'application/json' } } ) Again, it is so strange that I am making the request from http://127.0.0.1:3000 and the response headers has Access-Control-Allow-Origin: http://127.0.0.1:3000 but for some reason it is still failing. Oh the error message in the browsers console is Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/query/?date=2019-10-25. (Reason: missing token ‘access-control-allow-origin’ in CORS header ‘Access-Control-Allow-Headers’ … -
Trying to display output from the user input onto the same html screen
I'm sure this is not difficult, I'm just new to Django and would really appreciate some help. I've been trying to take two inputs ('sentence' variable, and 'word' variable) as CharFields. Then take those two inputs and create a new output with them. I can get this to print on the console but not to display it on the html page. Thank you. Here is what I got. --> form.html <div class="main"> <div class="container"> <div class="row"> <form class="content" method="post"> {% csrf_token %} {{ form }} {% if output %} <h3>{{ output }}</h3> {% endif %} <input type="submit" name="submit_cmd" value=Run /> </form> </div> </div> </div> --> views.py from django.shortcuts import render from django.http import HttpResponse from .forms import ContactForm import subprocess as sp import nltk from nltk.corpus import wordnet nltk.download('wordnet') def contact(request): syn = set() output = "" form = ContactForm() if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): sentence = form.cleaned_data['sentence'] word = form.cleaned_data['word'] for synonym in wordnet.synsets(word): for l in synonym.lemmas(): if l.name() != word: syn.add(l.name().lower()) for new_wrd in list(syn): print(sentence.replace(word, new_wrd)) output += sentence.replace(word, new_wrd) return render(request, 'pk_app/form.html', {'form': form}) --> forms.py from django import forms class ContactForm(forms.Form): sentence = forms.CharField(required=True) word = forms.CharField(required=True) -
Django - CSS file not linking with template correctly
In my project, I attempt to link my html template to a CSS file that I have in my static folder. I have added STATIC_ROOT, STATIC_URL and STATICFILES_DIRS to my settings.py. In my static folder, I have a folder called styles, and within that, I have a file named signup.css . I have also ran python manage.py collectstatic. In my template I attempt to reference that CSS file to change the colour of my h1, however no change occurs. Template: {% load static %} <head> <link rel="stylesheet" href="{% static 'styles/signup.css' %}"> </head> <h1>YO</h1> <div id="signupformdiv"> <form class="signupform" action="{% url 'signup' %}"> </form> </div> signup.css: h1 { color: red; } The colour of my h1 remains black. Does anybody know the issue? Thank you. -
Queried Results from Database Disappear on Pagination: Django
I am new to using the Django framework. I am creating a form to take in User input to query a database. I want to display the queried results on the same page, below the from fields. I am able to do the same. However, upon implementing Pagination, and clicking the 'next' link, or trying to sort the results using 'order_by', the queried results disappear from the webpage. How can this be resolved? Below are my code files:\ views.py: def get(self, request, *args, **kwargs): paginated_objects = [] order_by = None form = QueryForm(request.GET) button_state = True if form.is_valid(): max_traj_len = form.data["traj_len_user"] print(form.data["submit"]) print(max_traj_len) order_by = request.GET.get('order_by', 'traj_len') ##default order_by is set here backtrack_flag = form.data["backtrack_user"] print(backtrack_flag) queried_objects = list(collection.find({'traj_len':{'$lte':int(max_traj_len)}})) paginator = Paginator(queried_objects, 25) page = request.GET.get('page') paginated_objects = paginator.get_page(page) button_state = request.GET.get('submit') return render(request, self.template_name, {'form': form,'object_list': paginated_objects, 'order_by': order_by, 'button_state': button_state}) template.html: {% extends 'base.html' %} {% block content %} <form action='' method='get'> {% csrf_token %} <table>{{ form.as_table }}</table> <input type="submit" name="submit" value="Query"> </form> {% if button_state == 'Query' %} <table id="studata"> <thead> <th><a href="?order_by=traj_id">Traj ID</a></th> <th><a href="?order_by=traj_path">Traj Path</a></th> <th><a href="?order_by=traj_len">Traj Length</a></th> <th><a href="?order_by=interpolated_id">Interpolated_ID</a></th> <th><a href="?order_by=inter_path">Interpolated Path</a></th> <th><a href="?order_by=inter_path_len">Interpolated Path Length</a></th> <th><a href="?order_by=backtrack">Backtrack</a></th> <th><a href="?order_by=reached_goal">Reached Goal</a></th> </thead> {% for … -
Psycopg2 failed with exit status of 1120 on Windows 10
I have a venv with Python 3.8 installed, updated computer from windows 7 to 10 and now I can't install Psycopg2 nor Psycopg2-binary. It is giving me the following error: I have tried: Installing from github with pip install git+https://github.com/nwcell/psycopg2-windows.git@win32-py25#egg=psycopg2. It still says Psycopg2 is not installed: Any suggestions? Thank you very much. -
Not able to display in Template the foreign key using ListView
I'm trying to display a photographic session with all of it photos, so I have the session name in one model and I have the pictures in another model linked by a foreign key. I'm not able to display it in the HTML I'm not sure if I'm using the ListView get_context_data correctly and I'm certainly sure the the html code is not correct but I have not found how to do it. views.py class SessionPictures(generic.ListView): model = PostSession template_name = 'photoadmin/gallery.html' def get_context_data(self, **kwargs): context = super(SessionPictures, self).get_context_data(**kwargs) context['picture'] = Images.objects.all() return context models.py class PostSession(models.Model): session_name = models.CharField(max_length=25) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.session_name) class Images(models.Model): name = models.ForeignKey( PostSession, related_name='images', on_delete=models.CASCADE, null=True, blank=True) picture = models.ImageField(upload_to='pictures') html {% extends 'base.html' %} {% load static %} {% block content %} <h2>Images</h2> <ul> {% for session in object_list %} <li>{{ session.session_name }}</li> <ul> <li>{{session.picture_set.all.url}}</li> </ul> {% endfor %} </ul> {% endblock %} I'm expecting this: Woods picture1.url picture2.url picture3.url Beach Picture4.url picture5.rul -
Bullet points in Django
Is there a model field to create a list of bullet points in Django? Like you would do for specifications of a product? If not how would I do this? Example Specifications: - feature - feature - feature - feature I don't have any code to show as I don't know where to start. I haven't found anything online of what I'm looking for. -
Getting the class from a model instance in Django
I have a model where I want to get the class name and create a queryset from the instance of the model as it is being saved. Right now, Im doing it like this: class MyModel(models.Model): .... def my_method(self): if self.__class__.__name__.objects.filter(...).exists(): # Do something This does not really work as it says that a string object does not have the objects property, but hopefully, it makes it clear what I want to do. This is for a base abstract class where the method can be re-used for all the child classes with different names. Anyway, is there a way to do this in Django? -
How to use update_fields in django signals post_save
I hope my title is enough to understant what i am trying to say if not then sorry in advance. I dont have problem on inserting data, but how about when the admin update the section of student were the student have already record?, I just want to update the current data not add another data this is my code in my model.py(post_save).. @receiver(post_save, sender=StudentsEnrollmentRecord) def create(sender, instance, created, **kwargs): teachers = SubjectSectionTeacher.objects.filter(Courses=instance.Courses, Sections=instance.Section) if created and teachers.exists(): StudentsEnrolledSubject.objects.create( # This should be the instance not instance.Student_Users Students_Enrollment_Records=instance, # The below is also not an instance of SubjectSectionTeacher Subject_Section_Teacher=teachers.first()) -
Django/Bootstrap 4: How to align elements inside of multiple parent divs
So I am developing a website and for the life of me I cant figure out how to align the description, price, stock and add cart button in multiple versions of the same div. I know it is to do with the size of the image I am using but I'm not sure how to fix this. Here is a diagram of how I want it to look: But when I apply a 'h-100' class to the card div this is what happens: I want the images to keep their positions but for the descriptions, add cart button and price/stock to all be horizontally aligned, as well as the height of the overall cards to be the same. Here is my Django template code: {% extends 'base.html' %} {% block content %} <div class="container-fluid"> <div class="jumbotron"> <h2>Welcome to MyTea</h4> <p>Here we have teas of all varieties from all around the globe</p> </div> <div class="row"> <div class="col-sm-3"> <h4>Categories</h4> <ul class="list-group"> <a href="{% url 'products' %}" class="list-group-item">All Categories</a> {% for c in countcat %} <a href="{{ c.get_absolute_url }}" class="list-group-item catheight">{{c.name}} <span class="badge badge-light">{{c.num_products}}</span> </a> {% endfor %} </ul> </div> <div class="col-sm-9"> {% for product in products %} {% if forloop.first %}<div class="row">{% … -
Wrong column sizes in latex generated pdf when running pdflatex via subprozess in django
I'm generating a Latex document on my Django page with pdflatex. When i compile my tex-file from the Terminal or with subprocess in python it has the right col widths but when I compile it with subprocess in my django site the columns have wrong widths. e.g.: wrong - https://docdro.id/gsHMoQX right - https://docdro.id/HLIQAEE .tex content: \documentclass{article}% \usepackage[T1]{fontenc}% \usepackage[utf8]{inputenc}% \usepackage{lmodern}% \usepackage{textcomp}% \usepackage[margin=0.5in]{geometry}% \usepackage{longtable}% \usepackage{graphicx}% % \usepackage{colortbl}% % \begin{document}% \pagestyle{empty}% \normalsize% \begin{Large}% 1 MAK {-} 4AHWII% \end{Large}% \begin{longtable}{l | l | >{\columncolor[rgb]{1, 0.6, 0.42}}l | >{\columncolor[rgb]{1, 1, 0.6}}l | >{\columncolor[rgb]{1, 0.6, 0.6}}l}% \textbf{Nachname}&\textbf{Vorname}&\textbf{{\rotatebox{ 90 }{ Gesamt (None) } }}&\textbf{{\rotatebox{ 90 }{ Prozent } }}&\textbf{{\rotatebox{ 90 }{ Note } }}\\% \hline% \endhead% Musterschüler&Max&0&0\%&5\\% Siegele&Noah&0&0\%&5\\% Widerin&Alexander&0&0\%&5\\% Hilber&Georg&0&0\%&5\\% \end{longtable}% \begin{figure}[b]% \centering% \includegraphics[width=240px]{/tmp/fig.png}% \end{figure} % \end{document} -
How to serve protected video file on Django production?? Nginx help needed
I need a serve a protected video file on production in a super quick easy way, but it's not working. No models are required. I only need to upload ONE video, have it display on a django template page, and that's it. So no true password with salting / hashing is required (which I know how). With my current setup the video serves fine from static, but not as a protected file because it's easy to copy/paste from the source html. Every article I've checked only shows how to download a specific file as a forced download, but I need some clarity on what's happening... This and this are the best articles I've found. Everything else is either wrong, or not as complete as those. Problems: On production I'm getting a 404 not found error when setting the header for response['X-Accel-Redirect'] = '/protected_files/' in the view, And a 403 forbidden error when setting the response['X-Accel-Redirect'] = protected_url in the view. What's happening?? I think the problem is with my location /protected_videos/ {...} directive, but I don't know why. Maybe it's my secret_page/ url??? Project structure: projectcontainer/ project/ settings.py ... static/ public-video.mp4 # all static serves fine PROTECTED/ videos/ private-video.mp4 # … -
Django: Sort articles by hourly/daily views (trending)
Suppose we have a blog with 100 articles. How can we let the users sort articles (objects) by the number of views (field) in the last hour/day/week/month? Can we implement something that makes the field views_today such that it becomes 0 every hour? -
Django how to serialize multiple file upload with validation using forms.ModelForm?
I have file upload model that saves the files based on it's md5 checksum: # models.py class File(models.Model): # use the custom storage class fo the FileField orig_file = models.FileField( upload_to=media_file_name, storage=file_system_storage) md5sum = models.CharField(max_length=36, default=timezone.now, unique=True) created = models.DateField(default=timezone.now) def save(self, *args, **kwargs): print('Saving new raw file.', self.md5sum) if not self.pk: # file is new md5 = hashlib.md5() for chunk in self.orig_file.chunks(): md5.update(chunk) self.md5sum = md5.hexdigest() if not self.id: self.created = timezone.now() print('Saving new raw file.', self.md5sum) super(RawFile, self).save(*args, **kwargs) The form I use to upload files looks like this: # forms.py from django import forms from .models import File class UploadRawForm(forms.ModelForm): orig_file = forms.FileField( widget=forms.ClearableFileInput(attrs={'multiple': True}) ) class Meta: model = File fields = ['orig_file'] I can upload single files, but when I use multiple files only the last file in the list is saved. According to other threads I have to serialize this process. So that the files are processed one by one. Do I need extra packages? -
Can I filter objects in forms.ManyToManyField to equal value selected in another field?
I want to set a queryset on a ManyToManyField to get all objects that have a ForeignKey equal to ForeignKey set in another formfield. class ProductAdminForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProductAdminForm, self).__init__(*args, **kwargs) self.fields['variants'].queryset = Variant.objects.filter(variantCategory__productCategory__name_single='test') This works, It selects all "Variant"'s where value of "name_single" of productCategory in its variantCategory is equal to 'test'. I want to replace 'test' to be equal to "name_equal" of productCategory set in this very form. Here is some code to ilustrate how the objects relate to eachother. class Variant(models.Model): variantCategory = models.ForeignKey('VariantCategory') class VariantCategory(models.Model): productCategory = models.ForeignKey('ProductCategory') class ProductCategory(models.Model): name_single = models.CharField() https://imgur.com/a/OLah8at This shows the field that should define the productCategory to equal to. I realize this is kind of hard to explain, if any of you need extra code/info let me know! Also, I just need the query to get all objects where productCategory equals to another productCategory. The "name_equal" part doesn't really matter, could be the id of the object to! -
How to setup a JQuery Datatable
So I was trying to set-up a JQuery Datatable as in this example: http://plnkr.co/edit/b8cLVaVlbNKOQhDwI2mw?p=preview But I keep getting a "No matching records found" pop-up when I try to implement it. How would I be able to fix it? Here is my JS script: $(function() { otable = $('#amdta').dataTable(); }) function filterme() { //build a regex filter string with an or(|) condition var types = $('input:checkbox[name="item"]:checked').map(function() { return '^' + this.value + '\$'; }).get().join('|'); //filter in column 0, with an regex, no smart filtering, no inputbox,not case sensitive otable.fnFilter(types, 1, true, false, false, false); //build a filter string with an or(|) condition var frees = $('input:checkbox[name="website"]:checked').map(function() { return this.value; }).get().join('|'); //now filter in column 2, with no regex, no smart filtering, no inputbox,not case sensitive otable.fnFilter(frees, 2, false, false, false, false); Here is my HTML <p> <label> <input onchange="filterme()" type="checkbox" name="website" class="filled-in" value="canadacomputers" /> <span>Canada Computers</span> </label> <label> <input onchange="filterme()" type="checkbox" name="item" class="filled-in" value="$2299.0" /> <span>Item</span> </label> </p> <input type="text" id="amdin" onkeyup="amdfun()" placeholder="Search for CPU.."> <table id="amdta"> <thead> <tr> <th class="th-sm">Item</th> <th class="th-sm">Price</th> <th class="th-sm">Website</th> </tr> </thead> {% for item in items %} {% if item.brand == 'amd' %} <tbody> <tr> <td>{{ item.item }}</td> <td>${{ item.price }}</td> <td> <a href="{{ item.website …