Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django orm JSONField for mysql
I am trying to define a model with one column being a mysql json type. Searching on web results in suggestions related to django's postgresql support for JSONField type or django-jsonfield. Is there currently no way django natively supports mysql's json type. Also while doing inspectdb a column of type json in mysql was assigned the type TextField with a comment This field type is a guess. How would I declare my model in such a way that it supports json fields? -
Django - get() returned more than one model_item -- it returned 2
I have this error: get() returned more than one model_item -- it returned 2! The line that throw this error is : earray.sort(key=lambda x:"%s" % (x.model_rule.model_item.PRDT_ID.TITLE)) In below my model : model_rule: class model_rule(models.Model): key_id = models.AutoField(primary_key=True) model_item = models.ForeignKey(model_item,db_column='item_key_id') def __unicode__(self): return "%s:%s" % (self.model_item.PRDT_ID.TITLE,self.rule.name) class Meta: db_table = 'model_rule' model_item: class model_item(models.Model): ITEM_Id = models.CharField(max_length=64, primary_key=True, db_column = "item_id") Id = models.CharField(max_length=64, primary_key=True, db_column = "public_id") category_ID = models.CharField(max_length=64, primary_key=True, db_column="category_ID") PRDT_ID = models.ForeignKey('PRODUCT', db_column = "product_id") class Meta: db_table = 'model_item' There are many location where "x.model_rule.model_item" used i can't change one by one, so i need to do change one time in model by adding this filtre in list of "category_ID" (17,11,16,15,4,1) to avoid this error and every time "model_rule.model_item" or "model_rule.filter" called the filter is added to the query. -
How to add custom button for model in Django
I want to create custom button for Django which will allowed importing data from JSON files to database. Is it possible to add custom button in Django Admin, like in example below (Button Import JSON)? How it should looks like I have tried this gist, but it is do not work, because i use latest version of Django. How should looks like content of json file: { "records": [ { "name": "countries", "content": [ { "label": "Russia", "value": "Russia" }, { "label": "Norway", "value": "Norway" } ] } ] } -
Django get image from ModelForm
I have a model containing an ImageField like this: class MyModel(models.Model): photo = models.ImageField() and a form like: class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = ['photo',] and the in my view: def show_form(request): form = MyModelForm(request.POST or None) content = { 'form': form, } if form.is_valid(): mymodel = form.save(commit=False) mymodel.save() return render(request, 'appname/template.html', content) and my template: <!DOCTYPE html> <html> <body> <form action="" method="POST"> {% csrf_token %} <table align="center"> {{ form.as_table }} <tr> <td> <input type="submit" value="Submit" /> </td> </tr> </table> </form> </body> </html> but whenever I choose a picture and click submit the form tells me that this field is required and it is not saving it. Thanks in advance. -
Ensure queryset is cached
I am calling a function that starts a process that takes long to execute, many different things are done. This function chiefly handles instances of a particular class, Item. These items are categorized by different attributes: category1, category2 and category3. Now, there is a different model that applies some sort of rules to these categories: Rule with many-to-many attributes: categories1, categories2 and categories3. A rule applies to an Item, if the same rule points to different categories, only one of them should be applied. The decision of which one is defined by a certain logic encapsulated in a function: class Rule(models.Model): warehouse = models.ForeignKey('Warehouse') categories1 = models.ManyToManyField('Category1') categories2 = models.ManyToManyField('Category2') categories3 = models.ManyToManyField('Category3') @staticmethod def get_rules_that_applies(item): rules = warehouse.rule_set.all() if not rules.exists(): return None # ... determine which rule applies to the item by filtering, etc. return rule The issue lies in the get_rules_that_applies method. Every time we need to get the rule that applies to a certain item, and let me say again that many many items are involved in the process we are talking about, warehouse.rule_set.all() is called. Since the rules will not change during this process, we can just cache all the rules in the ware house, … -
Django: Update object from view, with no model or template
I'm currently working on a Django app that allows users to set synonyms for keywords. Its using the following model: class UserSynonym(models.Model): user = models.ForeignKey(Tenant) key = models.CharField(max_length=255) value = models.CharField(max_length=255) A ListView provides users with an overview, and each entry is followed by an 'edit' button that links to a relevant EditView that allows the user to change the 'value' parameter. I now want to add a button that allows the user to quickly reset the object to its original meaning (Set the 'value' to the value of 'key') I want this to be a single button, without any forms or html templates. Just a button on the list that, when pressed, 'resets' the value of the model. I reckon I have to edit an EditView for this task, however, these views keep demaning that I supply them with either a form or a HTML template/page Which is not what I want to do. Is there a way to change the EditView so that it changes the value of the object, without redirecting the user to a form or a new webpage? EDIT: for completeness sake I've added the UpdateView as I'm currently using it class SynonymUpdate(UserRootedMixin, UpdateView): model … -
Issue in view.py : message error Invalid literal for int() with base 10
I've created the following structure for my Django app: ../programs/ #home page for the app ../program/id #detailed page about a specific program stored in the db However, when I try to access from the browser ../programs/1 (with 1 being the id of the program I want to see details about) I get the following error: ValueError at /programs/1/ invalid literal for int() with base 10: '1/' Request Method: GET Request URL: http://127.0.0.1:8000/programs/1/ Django Version: 1.10.7 Exception Type: ValueError Exception Value: invalid literal for int() with base 10: '1/' Here is my code: views.py from django.http import Http404 from django.shortcuts import render from .models import Step, Cycle, Program, MotorSetting, GeneralSetting from django.core.exceptions import ObjectDoesNotExist def index(request): all_programs = Program.objects.all() context = { 'all_programs': all_programs } return render(request, 'programs/index.html', context) def program(request, program_id): try: program = Program.objects.filter(id=program_id).get() return render(request, 'programs/program.html', {'program': program}) except ObjectDoesNotExist: raise Http404("A program with this ID does not exist yet.") program.html {{ program }} programs.urls.py from django.conf.urls import url from . import views urlpatterns = [ #frontend homepage url(r'^$', views.index, name='index'), #single program page url(r'^(?P<program_id>[0-9]+/)$', views.program, name='program'), ] models.py from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator class Program(models.Model): program_name = models.CharField(max_length=50) program_description = models.CharField(max_length=250) cycles = … -
Django- build model from database
I have a database (built with python and sqlite3) that the table looks like this: id number and the file that this id appears. id_number file_name 1 a.pdf 55 a.pdf 47 b.pdf 41 c.pdf I'm trying to build a website using django that someone will write the id in a search bar and it will find the name of the file that this id appears in it. I did python manage.py inspectdb>models.py to make a models file. the models file that was created: # This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey has `on_delete` set to the desired behavior. # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. from __future__ import unicode_literals from django.db import models class AuthGroup(models.Model): id = models.IntegerField(primary_key=True) # AutoField? name = models.CharField(unique=True, max_length=80) class Meta: db_table = 'auth_group' class AuthGroupPermissions(models.Model): id = models.IntegerField(primary_key=True) # AutoField? group = … -
Django ValueError: I/O operation on closed file, after using clean_<fieldname>() on FileField
I am attempting to create a page with a formset to allow the user to upload CSV files, the contents of which I want to validate before saving. I have a formset where each form has some CharFields pre-populated and then a FileField. I want to validate the contents of the CSV before I save it to a location on the disk, as they must be a very specific format. My current code performs this validation in a custom clean_<fieldname>() function for the FileField in the form. The validation all appears to work, however, when I attempt to write the file to the intended location on the disk I get a ValueError: I/O operation on closed file. I am using Python 3.4.3 with Django 1.11 and my code is below. I've only included the function which is giving the error in csv_funcs.py, specifically on the call to csv_f.chunks which tries to do self.file.seek(0). The other functions in that file which perform validation don't explicitly call close() on the file object anywhere, although they do use csv.DictReader on it after which I always seek(0) to return to the start of the file. forms.py class CsvUploadForm(forms.Form): nom = forms.CharField(widget=forms.HiddenInput()) machine = forms.CharField(widget=forms.HiddenInput()) … -
Loading .txt file from media django
I have a function which will open all .txt files and read the words/frequency into and array, so I'm trying to tell that function that all the .txt files are in the media folder. This is first part of my function: from django.conf import settings class TrademarkOpenFileReadWords(object): file_name = settings.MEDIA_ROOT @staticmethod def open_file_read_words(file_name): """ TODO: open each trademark class file and read the words/frequency back into an array :param file_name: :return: TODO """ unique_words_and_count_not_format = [] tm_word_count_array = [] my_list = [] all_possible_entries = 1 with open(file_name) as f: lines = [line.strip() for line in open(file_name)] all_possible_entries = len(lines) so I'm trying to set this globally out site of my function but I'm getting this error Environment: Request Method: GET Request URL: http://127.0.0.1:8000/trademark/ Django Version: 1.11.2 Python Version: 2.7.12 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'classifier', 'crispy_forms', 'allauth', 'allauth.account', 'allauth.socialaccount', 'widget_tweaks', 'debug_toolbar'] Installed 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', 'debug_toolbar.middleware.DebugToolbarMiddleware'] Traceback: File "/home/petar/.virtualenvs/trademark/local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/petar/.virtualenvs/trademark/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/petar/.virtualenvs/trademark/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/petar/.virtualenvs/trademark/local/lib/python2.7/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/home/petar/.virtualenvs/trademark/local/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, … -
Django Filter returning empty set for a thread id,but , thread is present in db
I Have this following line in views.py file message_rows=HostedEvents.objects.filter(thread_id=decl_th.thread_mapping.original_id) logger.debug('message rows are {}'.format(message_rows)) import pdb;pdb.set_trace() Output: message rows are [] (pdb)HostedEvents.objects.filter(thread_id=decl_th.thread_mapping.original_id) [<< HostedEvents: 15dcaea4b6657031 - 15dcaea4b6657031>>] How come message rows are empty, where as in pdb which is immediate to that line, while calling from pdb, that code is working. Moreover for suppose if there are thread with three message id's, this is happening for every first thread and remaining two are working properly. One more thing if "X" is a thread id with three children , one of the children(first one)'s id is same as thread_id. -
Django nested formsets- actual working
I have heavily searched the internet but didn't find any reliable and independent source to apply nested form-sets in django including how to initialise them, and show them on templates along with fetching data at back end on post request. There are many packages available named "nested-formsets", but those also aren't functioning properly. Even packages are displaying all information about everything except how to use them in code. Anyone,please help. -
Django rest framework: Insert multiple objects in one post request
I am using DRF for my API backend. I need to insert multiple objects into one post request. I saw so many tutorials, as well How do I create multiple model instances with Django Rest Framework?, but not success. I am using ModelSerializer, but when using many=True then have problem with ListSerializer. Please advise. Thanks. -
Why does 'DIRS' only have an effect when APP_DIRS is False?
Why does 'DIRS' in TEMPLATES in settings.py only have an effect when 'APP_DIRS' is set to False? I tried to load a custom html widget, but changing the 'DIRS' have not changed the 'Template-loader postmortem' when 'TemplateDoesNotExist' is thrown. When I set the 'APP_DIRS' to False, the 'DIRS' setting suddenly had an effect. I've tried to search for similar questions, but haven't found an answer. I've also looked through the docs, but neither the paragraph about DIRS or APP_DIRS mention one working when the other doesn't. Example 1: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'), '/Users/jonas/Documents/jobb/dynamicSurvey/survey/templates/django/forms/widgets'], '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', ], }, }, ] Gives this output: Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /Users/jonas/venv/lib/python3.6/site-packages/django/forms/templates/horizontal_select.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/jonas/venv/lib/python3.6/site-packages/nested_admin/templates/horizontal_select.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/jonas/venv/lib/python3.6/site-packages/django/contrib/admin/templates/horizontal_select.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/jonas/venv/lib/python3.6/site-packages/django/contrib/auth/templates/horizontal_select.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/jonas/Documents/jobb/dynamicSurvey/survey/templates/horizontal_select.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/jonas/venv/lib/python3.6/site-packages/tellme/templates/horizontal_select.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/jonas/venv/lib/python3.6/site-packages/tinymce/templates/horizontal_select.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/jonas/venv/lib/python3.6/site-packages/django/forms/templates/horizontal_select.html (Source does not exist) Example 2: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'), '/Users/jonas/Documents/jobb/dynamicSurvey/survey/templates/django/forms/widgets'], 'APP_DIRS': False, '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', ], }, … -
How Django resolve this non-greedy regex url pattern?
I'm following a tutorial which works with Django, there is a url pattern like this: url(r'^lists/(.+)/$', views.list_view, name='list_view') That's a greedy regex pattern and it will match something such as: lists/123/add_item/ with 123/add_item as matched-group. That is not what is expected. So I tried to change it to non-greedy one like this: url(r'^lists/(.+?)/$', views.list_view, name='list_view') But Django still resolve lists/123/add_item/ to views.list_view Could you please give me some explain? -
Call forwarding with twimlets in Django App
I am implementing a Twilio call functionality in my Django app, where in I want to get a call to specified no, after the call is picked by a person it should connect the call to another phone no. This is what I have already implemented to get the call functionality running but I am not able to forward it to the desired no. def call(country_code, to, lead_cc, lead_no, configuration): account_sid = "XXX22a62f54bXXXXXXXXXXXXX" auth_token = "XXXXXa61188eXXXXXXXXXXX" client = Client(account_sid, auth_token) no_str = str(country_code) + str(to[0]) no_uni = unicode(no_str) lead_str = str(lead_cc) + str(lead_no[0]) lead_uni = unicode(lead_str) client.calls.create(from_="+17xxXXXXX", to=no_uni, url= 'http://twimlets.com/forward?PhoneNumber=+91xxxxxxxxx') Also, I need pass "lead_uni" in the URL like this but it's now working (url= 'http://twimlets.com/forward?PhoneNumber=lead_uni').Please, sugges ! -
Why Django build-in documentation doesn't display chosen methods?
Let's take as an example object User. I have only available list, create, read, update however I have methods like url(r'^users/(?P<user_id>[0-9]+)/object1$', views.UserObject1.as_view()), url(r'^users/(?P<user_id>[0-9]+)/object2$', views.UserObject2.as_view()), url(r'^users/(?P<user_id>[0-9]+)/object3$', views.UserObject3.as_view()), Unfortunately they aren't visible in documentation. I have also Swagger documentation and all methods are displayed properly. Any ideas why in Django build-in documentation objects with URLs as I have shown above are not available? Any suggestions how can I solve it? -
Django forms: How to simply include all attributes in the associated model
I am working through how to use Django's forms (https://docs.djangoproject.com/en/1.11/topics/forms/#more-on-fields) and I can't see a way to generate a form structure that is based on a defined Model. In Symfony, I remember I was able to get my form to automatically include all parameters of myModel (for example) even if any new attributes were later added to the model. For example: class myModel(models.Model): name = models.CharField(max_length=50) created=models.DateTimeField(null=False) modified=models.DateTimeField(null=True) myParameter= models.IntegerField(default=None) // ... plus many more parameters Rather than having to manually type corresponding rows into my class myModelForm(forms.Form):, I'm looking/hoping for a 'catch all'. -
How to check the middleware class for session time out in view using Django and Python?
I am implementing session time out in Django login form. I have declared the middleware class and set the time interval for session alive. Here I need to check those for all pages. I am explaining my code below. settings.py: SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer' AUTO_LOGOUT_DELAY = 5 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', 'bookingservice.middleware.AutoLogout', ] middleware.py: from datetime import datetime, timedelta from django.conf import settings from django.contrib import auth class AutoLogout: def process_request(self, request): if not request.user.is_authenticated() : #Can't log out if not logged in return try: if datetime.now() - request.session['last_touch'] > timedelta( 0, settings.AUTO_LOGOUT_DELAY * 60, 0): auth.logout(request) del request.session['last_touch'] return except KeyError: pass request.session['last_touch'] = datetime.now() views.py: def home(request): """ This function provides the home page .""" pers = User.objects.get(pk=request.session['id']) user_name = pers.uname return render(request, 'bookingservice/home.html', {'username': user_name, 'count': 1}) Here I need after login when home page will come it will check whether the defined session is alive or not if not then it will redirect to login page.Please help. -
Django backend not returning JSON on production server, getting 404
I have a Django backend that returns json data. I'm able to get data back on my localhost but got a 404 on production server. I'm running nginx in front of gunicorn server. Any ideas why I'm getting a 404? Shouldn't this be able to work to retrieve json data, or do I need to use django rest framework and implement viewsets to make this work? Not Found The requested URL /about was not found on this server. urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^about/', about.get_info), ] about.py from django.http import JsonResponse def get_info(req): return JsonResponse({"test": "hello"}) -
Populate data in <div> after retrieving through ajax
My view clearly returns the data as I desired, but thing is that I'am unable to lode these data on a particular div, I have shown the div tag below. Thanks in advance for your help :) My views looks like this def pop_user(request, username): print('user') data = dict() profile = get_object_or_404(User, username=username) context = {'profile': profile} data['html_form'] = render_to_string('profile/pop_user.html', context, request=request, ) return JsonResponse(data) My js/ajax is like this : $(document).ready(function() { $('.user').hover(function (e) { // alert($(this).closest(".username").attr("data-url")) var offset = $(this).offset(); var left = e.pageX; var top = e.pageY; var theHeight = $('#myPopoverContent').height(); $('#myPopoverContent').show(); $('#myPopoverContent').css('left', (left+10) + 'px'); $('#myPopoverContent').css('top', (top-(theHeight/2)-10) + 'px'); $.ajax({ url: $(this).closest(".username").attr("data-url") +"/", type: 'get', data: form.serialize(), dataType: 'json', success: function (data) { $("#myPopoverContent").html(data.html_form); } }); }); $('#myPopoverContent').focusin(function (e) { $('#myPopoverContent').active(); }); $('#myPopoverContent').mouseout(function (e) { $('#myPopoverContent').hide(); }); $('.user').mouseout(function (e) { $('#myPopoverContent').hide(); }); }); And my html is <div id="myPopoverContent" class="dealBg"> </div> -
Django username matching in database
Is it possible write condition code when user registering with the same username in the database and print error about username matching? -
Django - performance difference between join/no join existence filter
currently I have a Tinder-like application that functions off the following models class User(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=50) age = models.PositiveIntegerField() pic_url = Models.CharField(max_length=100) class Rating(models.Model): id = models.BigAutoField(primary_key=True) by_user = models.ForeignKey(User, on_delete=models.PROTECT, related_name='written_ratings') for_user = models.ForeignKey(User, on_delete=models.PROTECT, related_name='received_ratings') like = models.BooleanField() In order to get new User objects to swipe left and right on, we need to query the database (PostgresSQL) for users that we have not yet rated. I am currently doing this by performing the following query users_that_i_havent_rated_yet = models.User.objects.all().exclude( id=current_user_id ).filter( age__gte=some_minimum_age, age__lte=some_maximum_age, ).exclude( received_ratings__by_user_id=current_user_id ) Now, I intend on separating the User object into a Profile object - so as to maintain a "history" of any user's changes to their profile, as well as acting as a container for additional unrelated information (also because my professor asked us to do this for our project) # as the user changes their profile pictures, we will just create # a new `Profile` object and set the `current_profile` pointing to it class User(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=50) age = models.PositiveIntegerField() current_profile = models.OneToOneField(Profile, on_delete=models.PROTECT) class Profile(models.Model): id = models.BigAutoField(primary_key=True) pic_url = models.CharField(max_length=100) by_user = models.ForeignKey(User, on_delete=models.PROTECT, related_name='created_profiles') class Rating(models.Model): id = models.BigAutoField(primary_key=True) by_user = … -
How to implement session time out in Django login form using Django and python
I need some help. I need to implement the session time out functionality in inbuilt Django form. Here I need to save time in session and will check in each page. If the expired time is out then again the it will return to login page. I am explaining my code below. class Signup(View): """ this class is used for user signup """ def get(self, request): """ this function used to get the sign up form """ form = UserCreationForm() return render(request, 'booking/signup.html', {'form': form}) def post(self, request): """ this function used for post the sign up data """ form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('login') class AuthLogin(View): """ Its for login """ def get(self, request): """ this function used to get the login form """ form = AuthenticationForm() return render(request, 'booking/login.html', {'form': form}) def post(self, request): """ this function used for post the login data """ form = AuthenticationForm(None, request.POST or None) if form.is_valid(): login(request, form.get_user()) return redirect('/') def home(request): """ This is for displaying the home page """ return render(request, 'booking/home.html', {}) Here My requirement is when user will logged in the current time will store in session and it will check in home page, here the … -
Django - Create a dropdown list from database
I'm very new to Django and I would like to create a drop down box using distinct value of a column in a database: models.py: from django.db import models class SensorsTable(models.Model): sensor_uuid = models.CharField(primary_key=True, max_length=32) sensor_desc = models.CharField(max_length=256) sensor_mid = models.CharField(max_length=256) gw_uuid = models.CharField(max_length=32, blank=True, null=True) sensor_loc_lat = models.DecimalField(max_digits=11, decimal_places=8, blank=True, null=True) sensor_loc_long = models.DecimalField(max_digits=11, decimal_places=8, blank=True, null=True) sensor_loc_blg = models.CharField(max_length=100, blank=True, null=True) sensor_loc_room = models.CharField(max_length=100, blank=True, null=True) sensor_loc_position = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = False db_table = 'sensors_table' def __str__(self): return self.sensor_uuid I want a drop down list to contain all distinct values of sensor_loc_room and if the user select a room (sensor_loc_room), table displaying all sensors in the room will be displayed. This is my current view.py (only use to display a table of all sensors): from django.shortcuts import render # Create your views here. from django.http import HttpResponse from django.template import loader from django.shortcuts import render from django.views.generic.edit import CreateView from .models import * #def index(request): # return HttpResponse("Smart Uni Analytics Test") def index(request): query_results = SensorsTable.objects.all() locationForm = LocationChoiceField() context = { 'query_results': query_results, } return render(request,'analytics/index.html', context) And index.html(only use to display a table of all sensors): <table> {% for item in query_results …