Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django views receiving FormData() object without keys
Here what i am basically trying is to stringify an array and append it to form data object and pass it to a view through ajax. The strange part is values are sent to the views but without keys. Here is my ajax formData = new FormData() var instrument = [136519172, 136485892] formData = new FormData() formData.append('instrument', JSON.stringify(instrument)) $.ajax({ type: 'POST', url: 'place_orders', cache:!1, processData:!1, data: formData, success:function(data){ }, error:function(){ } }); Here is my view def placeOrders(request): if request.is_ajax(): instrument = request.POST.get('instrument') return HttpResponse(instrument) The response i get is None This is the Formdata sent(took from headers of Network tab) ------WebKitFormBoundaryNPW2Q1atgClRKOyY Content-Disposition: form-data; name:"instrument" [136519172,136485892] ------WebKitFormBoundaryNPW2Q1atgClRKOyY-- -
Django - saving form to the built in database SQLite
This is my first time using django and I am very simply trying to save text to the database. I have created the table inputs in the database. I am getting the following error; Error - Page not found (404) My code is as follows; Models.py from django.db import models class Input(models.Model): waist = models.IntegerField(default=0) height = models.IntegerField(default=0) def __unicode__(self): return "{0} {1} {2}".format( self, self.waist, self.height) forms.py class InputForm(forms.ModelForm): class Meta: model = Input fields ={ 'waist', 'height' } views.py def InputView(request): if request.POST: form = InputForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('account/input') else: form = InputForm() args = {'form' : form} return render(request,'accounts/input.html', args) urls.py url(r'^input/$',views.InputView, name='view_input') input.html {% extends 'base.html' %} {% block head %} <title> Edit Profile </title> {% endblock %} {% block body %} <div class="container"> <h1> Enter Body Details </h1> <br> <br> <form action="account/input" method="post"> {% csrf_token %} <ul> {{form.as_ul}} </ul> <input type="Submit" name="submit" value="submit"/> </form> </div> {% endblock %} If any one can help it would be greatly appreciated. -
Class based view and call function to script
I'm learning django and I'm facing a problem I can't figure how to debug. I have a lobby_detail.html template that shows a button like this: <button type="button" href="{% url 'sign'%}" class="btn btn-primary btn-lg btn-block">Sign this Document</button> The template is a Detail view modelview: class LobbyDetailView(generic.DetailView): model = Lobby I would like the button to execute some code that requires both user connected and current lobby instances How can I use the button thanks to class based view? Thanks in advance. -
Django Q object AND operation not working
I have a listview of people with a filter. The filter has the following code: if textquery: qs = qs.filter() qs = qs.filter(Q(name__icontains=textquery) | Q(surname__icontains=textquery) | Q(surname__icontains=textquery) & Q(name__icontains=textquery) ) return qs People can have both a first and a last name, and searching for those works as expected. However, when I input both the first AND the lastname, the program does not return any results (even though I thought that the '&' operation in the end should include both variables). In summary: this is currently the result of my queries: Person: 'John Doe' Query: 'John' Result: 'John Doe' Person: 'John Doe' Query: 'Doe' Result: 'John Doe' Person 'John Doe' Query: 'Johh Doe' Result: '' Does anyone know what I am doing wrong, and why matches for both the NAME and SURNAME do not return any results? -
Django - multiple databases - how to define the router?
I would like to connect my application to 3 different databases. To do this, I've changed the following code in the settings file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'local_db', 'USER': 'root', 'PASSWORD': 'password1', 'HOST': 'localhost', 'PORT': '3306', 'OPTIONS': { 'sql_mode': 'traditional', } }, 'firstExternalDb': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'firstExternalDb', 'USER': 'userName', 'PASSWORD': 'password1', 'HOST': 'firstExternalDb.node.com', 'PORT': '3306', 'OPTIONS': { 'sql_mode': 'traditional', } }, 'secondExternalDb': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'secondExternalDb', 'USER': 'userName', 'PASSWORD': 'password1', 'HOST': 'secondExternalDb.node.com', 'PORT': '3306', 'OPTIONS': { 'sql_mode': 'traditional', } }, } And I want to have a possibility to specify for which database I will create a datatable. For example all django tables like 'auth_group' , 'django_admin_log' I want to save in localhost. Was trying to create a router going through this tutorial https://docs.djangoproject.com/pl/1.11/topics/db/multi-db/#topics-db-multi-db-routing But I do not understand this. Could you answer my questions: Should I create new router for each application ? how to define that all django tables should be used by default database ? -
How to display twitter feeds based on users in django & tweepy?
I want to show twitter data based on twitter username in my template (Tweepy) but I don't know how to send data from my models into my views. models.py: <pre> from django.db import models from django.conf import settings User = settings.AUTH_USER_MODEL # Create your models here. class Feed(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) feed = models.CharField(max_length=211, blank=True, null=True) twitter = models.CharField(max_length=211, blank=True, null=True) # this is the twitter user name which the user can enter. def __str__(self): return self.feed </pre> views.py: <pre> from django.shortcuts import render from django.views.generic import TemplateView from .tweet import * from .models import Feed def feed(request): api = tweepyapi(request) username = Feed.objects.filter(owner=request.user) user = api.get_user(twitter) # I want this portion to be dynamic. findfriends = user.friends() return render(request, 'feeds/feeds.html', { 'user': user, 'findfriends': findfriends }) </pre> -
Is there anyway to delete object from queryset that already chosen in django?
Example: query = Test.objects.all() I want to delete the specific one. But before deletion I want to do some function like so. for q in query: if q.name == something: newq = q.relate_set.all() query.remove(q) # this remove not work -
Export User model into different app
I have a project with one app, where user, their posts and other models are located. Now I want to separate User model and put it into different app, called users. How should I do this correctly? User model looks like this: class ExternalUser(AbstractUser): class Meta: permissions = ( ('can_do_this', 'Permission1'), ('can_do_that', 'Permission2'), ..., ) I've done django-admin startapp users and copy-pasted user's model code into created app models.py. Then I tried makemigrations and it failed, showing: SystemCheckError: System check identified some issues: ERRORS: photogal.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'ExternalUser.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'ExternalUser.groups'. photogal.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'ExternalUser.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'ExternalUser.user_permissions'. users.ExternalUser.groups: (fields.E304) Reverse accessor for 'ExternalUser.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'ExternalUser.groups' or 'User.groups'. users.ExternalUser.user_permissions: (fields.E304) Reverse accessor for 'ExternalUser.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'ExternalUser.user_permissions' or 'User.user_permissions'. Adding related_name='+' to the old user model resulterd in: ERRORS: <class 'django.contrib.auth.admin.UserAdmin'>: … -
Django - app in subfolder
I've created new django app in a subdirectory using the command: python manage.py startapp appName subFolder/appName but if I try to add this app to INSTALLED_APPS at the end of the list I see the following error: ImportError: No module named appName Does anyone know what I am doing wrong ? -
Django - delete record view based on the same method as django admin?
id like a are you sure page like the one in django admin that enables users to delete records if they have perms. currently my view and templates are per the below (the template is modified from the admin template in the Django install) the view I think ive got half right, I just need to send the model_count and deleted_objects, but im not sure how to obtain them in my view? {% extends "home/sbadmin_base.html" %} {% load extras %} {% load static %} {% block content %} {% if perms_lacking %} <p>{% blocktrans with escaped_object=object %}Deleting the {{ object_name }} '{{ escaped_object }}' would result in deleting related objects, but your account doesn't have permission to delete the following types of objects:{% endblocktrans %}</p> <ul> {% for obj in perms_lacking %} <li>{{ obj }}</li> {% endfor %} </ul> {% elif protected %} <p>{% blocktrans with escaped_object=object %}Deleting the {{ object_name }} '{{ escaped_object }}' would require deleting the following protected related objects:{% endblocktrans %}</p> <ul> {% for obj in protected %} <li>{{ obj }}</li> {% endfor %} </ul> {% else %} <p>{% blocktrans with escaped_object=object %}Are you sure you want to delete the {{ object_name }} "{{ escaped_object }}"? … -
Django makemigrations permission denied for relation django_migrations
I have Python 2.7.14, Django 1.11 and PostgreSQL 9.4.15, and cannot run python manage.py makemigrations with it. It says: django.db.utils.ProgrammingError: permission denied for relation django_migrations But python manage.py migrate works just fine. Sudo's mode is not what I need. With sudo it has another mistakes -- it cannot import settings, but everything is fine with settings, because other developers don't meet this problem. What could be the issue? -
Django: make model field and foreign key unique together
I have the following model: class Locale (models.Model): """ Locale model """ locale_id = models.AutoField(primary_key=True) locale_name = models.CharField(max_length=800) magister = models.ForeignKey(Magister, on_delete=models.CASCADE) def get_name(self): return self.locale_name In the database, there must be exactly one locale-magister pair. To create each locale item, an administrator has to upload the locales. This is done via a bulk upload: try: lcl=Locale(locale_name = data_dict["locale_name"], magister = data_dict["magister "]) # lcl.full_clean() locales_list.append(lcl) rows+=1 if rows==INSERTNUMBER: try: Locale.objects.bulk_create(locales_list) locales_uploaded+=rows except IntegrityError as e: print("Error: locale bulk_create "+repr(e)) locales_list=[] rows=0 I tried using lcl.full_clean() in my bulk upload but I get a UNIQUE constraint failed: zones_locale.locale_name error and only about 1/2 of all locales upload successfully. I also tried using: def validate_unique(self, exclude=None): lcl = Locale.objects.filter(locale_id=self.locale_id) if lcl.filter(magister=self.magister).exists(): raise ValidationError("item already exists") But the same error occurs. I also tried using: class Meta: unique_together = (("locale_name", "magister"),) This did not work either. From what I can tell, the problem is that there exist locales with the same name that belong to different magisters. How can I allow locales with the same name to be uploaded while also enforcing the uniqueness of any given locale-magister pair? -
Why does this URL work in Django? It is not in urls.py
I've never worked with Django before. I'm taking over a Django project that was started by another programmer, who is now long gone. There is some magic happening in the code that I do not understand. For instance, in this file: urls.py I see this: from django.conf.urls import url, include from django.contrib import admin from django.core.urlresolvers import reverse_lazy from django.views.generic.base import RedirectView from django.conf import settings from core import views as core_views from sugarlab.search.views import validate_collections, create_document, delete_interest, rename_interest, add_url, my_interests from sugarlab.search.views import content, score, terms from django.contrib.auth.views import logout as django_logout from django.conf.urls.static import static admin.autodiscover() urlpatterns = [ url(r'^admin/logout/$', django_logout, {'next_page': '/'}), url(r'^admin/', admin.site.urls), url(r'^accounts/logout/$', django_logout, {'next_page': '/'}), url(r'^accounts/', include('allauth.urls')), url(r'^unsecured/$', core_views.home), The confusing part is these two lines: from django.conf import settings url(r'^accounts/', include('allauth.urls')), "allauths" is some configuration set inside of this file: settings/common.py The data looks like this: 'allauth', 'allauth.account', 'allauth.socialaccount', 'django.contrib.auth', 'django.contrib.sites', # Social/3rd party Authentication apps 'allauth.socialaccount.providers.linkedin_oauth2', 'captcha' Somehow this is a URL that actually works: /accounts/signup/ This file is completely blank: settings/__init__.py So I've two questions: how does "import settings" manage to magically import allauths? how does /accounts/signup/ map to an actual view? I don't see anything in urls.py, nor in settings, … -
DJANGO - Add field to default auth.User model - simpliest way
Looking for a simpliest way to add one field to Django's User model. I have two types of users with different fields - Company and Customer so I decided to create two types of UserProfiles. CompanyProfile and CustomerProfile. Every user has either CompanyProfile or CustomerProfile. To be able to filter and deciding which type is it, I want to add type field to User model. What would you suggest? Now I have UserProfile in the middle which seems to be overkill and it makes filtering, lookups and many other things less straightforward. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='userprofile') type = models.CharField(max_length=100, choices=settings.OBSTARAJME_USERPROFILE_TYPE_CHOICES) company_profile = models.OneToOneField('CompanyProfile', null=True, blank=True, on_delete=models.CASCADE, related_name='userprofile') customer_profile = models.OneToOneField('CustomerProfile', null=True, blank=True, on_delete=models.CASCADE, related_name='userprofile') I'm considering to create my custom User model. class User(AbstractBaseUser): type = models.CharField(max_length=100, choices=settings.OBSTARAJME_USER_TYPE_CHOICES) USERNAME_FIELD = 'username' but Django say's that there is no such field like username and I would like to avoid writing whole User model and all it's fields manually. EDIT I know that I could filter based on customerprofile__isnull=False so practically, I don't need type field at all but it doesn't look to be the best way. -
Django ModelForm: Display readonly boolean field as ModelAdmin().readonly_fields does
When in the admin class, a boolean field becomes read-only: class MyAdmin(admin.ModelAdmin): readonly_fields = ('a_boolean_field', ) it gets a great appearance using icons as described in this answer. If this boolean field is defined in a forms.ModelForm: class MyForm(forms.ModelForm): a_boolean_field = forms.BooleanField(disabled=True) How can I present it in the admin interface as if I had set it in the readonly_fields of the admin.ModelAdmin()? -
Django raw query "Schema does not exists"
I'm using django 1.7, and I wish to make us a Count with a conditional. This is possible in django 1.8 onwards, but I'm unable to upgrade. As such, I'm trying to write a raw query as detailed in this question.. Regretfully, I haven't yet managed. My query: a = Photo.objects.raw( 'select "photos_photo"."id" , ' 'COUNT(' 'DISTINCT ' 'CASE ' 'WHEN "point_substanceexistslabel"."substance"."name" = "fabric" then 1 else null end) as c ' 'FROM "photos_photo" ' 'LEFT OUTER JOIN "points_substanceexistslabel" ' 'on ("photos_photo"."id" = "points_substanceexistslabel"."photo_id")' ' GROUP BY "photos_photo"."id"' ) Running the query and trying to print a result raised the following error: ProgrammingError: schema "point_substanceexistslabel" does not exist -
How to get a list of many to many relation to the same model
I want to move the list of related messages with a given model to the variable in the view - this is the "related" field. At the moment I'm getting all the objects that are badly displayed on the site. Please any hint, thanks a lot. Model: class News(models.Model): title = models.CharField(max_length=500) subtitle = models.CharField(max_length=1000, blank=True) text = models.TextField() link_title = models.CharField(max_length=500) date = models.DateField(null=True) related = models.ManyToManyField('self', symmetrical=False, blank=True) class Meta: verbose_name_plural = 'news' ordering = ['-date'] View: class NewsDetailView(DetailView): model = models.News context_object_name = 'news_item' def get_context_data(self, **kwargs): context = super(NewsDetailView, self).get_context_data(**kwargs) context['related_news'] = models.News.objects.values_list('related', flat=True) return context -
Django sorl thumbnail not creating thumbnail but returning results
This worked locally and also on a prior digitalocean VM I made (I believe I also found a solution prior but I'm now putting the same site from a repo on Google Cloud). This is the code from the Image model as a function class Image(models.Model): grey_image = ImageField(upload_to="black", null=True, blank=True) ... def left_half_full(self, img_type='black'): if self.grey_image: image = self.grey_image im = PIL_Image.open(image.path) image = im.convert('RGB') else: image = self.image im = PIL_Image.open(image.path) image = im.convert('RGB') if img_type == 'black': image = get_thumbnail(image, '{0}x{1}'.format(image.width/2, image.height), crop='left') return image it uses get_thumbnail and PIL as shown from the imports here from PIL import Image as PIL_Image from sorl.thumbnail import get_thumbnail This is trying to see if it creates a file successfully In [1]: from gallery.models import Image In [2]: image = Image.objects.get(id=171) In [3]: image.left_half_full() Out[3]: <sorl.thumbnail.images.ImageFile at 0x7ff4dc348e50> In [4]: image.left_half_full().url Out[4]: '/media/cache/a1/6a/a16a3cc553a1a9390713b812004c02ee.jpg' In [5]: exit() (djangoenv) muiruri_samuel@pluscolor:~/webapp/revamp$ cd revamp/media (djangoenv) muiruri_samuel@pluscolor:~/webapp/revamp/revamp/media$ cd a1 -bash: cd: a1: No such file or directory (djangoenv) muiruri_samuel@pluscolor:~/webapp/revamp/revamp/media$ ls add_color background both colored_images crop full_both original timeline all black cache colorfest full_all images profile_pic uploads there's a problem where it seems to create a file but actually doesn't. Same goes for on the site … -
Import Django QuerySet to python list
I am trying to export my Django QuerySet to a python list but I couldn't achieve it. My data structure: [{'time_stamp': datetime.datetime(2017, 9, 30, 22, 0, 37, tzinfo=<UTC>), 'num': 1}, {'time_stamp': datetime.datetime(2017, 9, 31, 22, 0, 37, tzinfo=<UTC>), 'num': 2}] My attempt is: my_query=MyModell.objects.all().filter(time_stamp__range=('2017-10-01', '2017-10-02')).values('time_stamp').annotate(num_avg=Avg('number')).order_by('time_stamp') data=[i.num_avg for i in my_query] Unfortunately I got this error message when I tried to retrieve the num. AttributeError: 'dict' object has no attribute 'num_avg' My aim is to get a list like this a=[1,2] Thank you in advance! -
Disqus universal code for Django
I try to install disqus in my site, but nothing is displayed on the page. Site url - djaway.net This is my code: views.py def detail(request, slug): url = (reverse('content:detail', args=[slug])) content_info = Post.objects.get(slug = slug) return render(request, 'detail.html', {'content_info':content_info, 'url':url}) template.html <script> var disqus_config = function () { this.page.url = 'djaway.net{{ url }}'; // Replace PAGE_URL with your page's canonical URL variable this.page.identifier = '{{ url }}'; // Replace PAGE_IDENTIFIER with your page's unique identifier variable }; (function() { // DON'T EDIT BELOW THIS LINE var d = document, s = d.createElement('script'); s.src = 'djaway.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })(); </script> <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> Tag {{ url }} return right links, for example - /content/slug/ -
How can I randomize csrf token for django admin
I've just got vulnerability report that came from pentesters for my Django project. The report says my Django app is vulnerable to the BREACH ATTACK. SSL is active, cookies are flagged as a secure, session cookies are set as a secure. HTTP Compressions closed by the sysadmin it is controlled from the Nginx that I have no access. So gzip is close. Now I want to randomize csrf token for per client-side request for the django admin, especially for the login page. Is there a way to do this in settings.py in a simple way or do I have to write custom admin view? What is the best practice for this issue? -
How to add mouse click event in python nvd3?
I'm beginner to Data visualization in python, I'm trying to plot barchart (multibarchart) using python-nvd3 and django, It's working fine but my requirement is need to add click event to Barchart to get the data if user click the chart.I searched quite a lot but i couldn't found any reference or solution due to lack of documentation.Below i mentioned my code.Thanks in advance! In view.py: from django.shortcuts import render_to_response import random import datetime import time def demo_multibarchart(request): nb_element = 10 xdata = range(nb_element) ydata = [random.randint(1, 10) for i in range(nb_element)] ydata2 = map(lambda x: x * 2, ydata) ydata3 = map(lambda x: x * 3, ydata) ydata4 = map(lambda x: x * 4, ydata) extra_serie = {"tooltip": {"y_start": "There are ", "y_end": " calls"}} chartdata = { 'x': xdata, 'name1': 'series 1', 'y1': ydata, 'extra1': extra_serie, 'name2': 'series 2', 'y2': ydata2, 'extra2': extra_serie, 'name3': 'series 3', 'y3': ydata3, 'extra3': extra_serie, 'name4': 'series 4', 'y4': ydata4, 'extra4': extra_serie } charttype = "multiBarChart" data = { 'charttype': charttype, 'chartdata': chartdata } return render_to_response('multibarchart.html', data) in template page: {% load static %} {% load nvd3_tags %} <head> {% load_chart charttype chartdata "multibarchart_container" %} </head> <body> {% include_container "multibarchart_container" 400 600 %} </body> -
Django: using ConTeXT mkiv to output PDF
i have a small Django app to manage my patients data, and use LaTeX to output reports. It consists un a parent model called Patients and child models Consultation , StressEcho and so on. With LaTex this works without problems def courrier_pdf(request, pk2, pk1): entry = Courrier.objects.get(pk=pk2) source = Patient.objects.get(pk=pk1) context = dict({'courrier': entry, 'patient': source}) #buffer = BytesIO() template = get_template('courrier/courrier.tex') rendered_tpl = template.render(context, request).encode('utf-8') #Python3 only. For python2 check out the docs! with tempfile.TemporaryDirectory() as tempdir: # Create subprocess, supress output with PIPE and # run latex twice to generate the TOC properly. # Finally read the generated pdf. for i in range(2): process = Popen( ['xelatex', '-output-directory', tempdir], stdin=PIPE, stdout=PIPE, ) process.communicate(rendered_tpl) with open(os.path.join(tempdir, 'texput.pdf'), 'rb') as f: pdf = f.read() r = HttpResponse(content_type='application/pdf') r.write(pdf) return r i tried with this view in order to use ConTeXT but without success def courrier_mkiv(request, pk2, pk1): entry = Courrier.objects.get(pk=pk2) cource = Patient.objects.get(pk=pk1) context = dict({'courrier': entry, 'patient': cource}) # buffer = BytesIO() template = get_template('courrier/courrier.mkiv') rendered_tpl = template.render(context, request).encode('utf-8') with tempfile.TemporaryDirectory() as tempdir: process = Popen(['context', '--result', tempdir], stdin=PIPE, stdout=PIPE, ) process.communicate(rendered_tpl) with open(os.path.join(tempdir, 'textput.pdf'), 'rb') as f: pdf = f.read() r = HttpResponse(content_type='application/pdf') r.write(pdf) return r My feeling … -
django pagination can not direct to next page
I want to use pagination to list data from database,but when I click next page button,it shows “local variable 'context' referenced before assignment” I use filter to searching data from database first ,and use "REQUSET.POST" to get the data back。then send the data to another html。I think when I click next page,it will do all these again ,but I don't know how to code it。 Please help me to find out the problem,thank you! Below is my code: view.py from django.template.loader import get_template from django.template import RequestContext from django.shortcuts import render,redirect from django.http import HttpResponse,HttpResponseRedirect from django.shortcuts import render,render_to_response from datetime import datetime from .form import DateRangeForm from .models import Post import tkinter.messagebox from tkinter import * from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger # Create your views here. def answer(): showerror("Answer", "Sorry, no answer available") def homepage(request): posts = Post.objects.all() now = datetime.now() context = {'posts':posts,'now':now} return render(request,'jishi.html',context) def showpost(request,times): template=get_template('post.html') ##posts=Post.objects.all().values('customer') posts=Post.objects.filter(pub_date__year=2018) now = datetime.now() html = template.render(locals()) return HttpResponse(html) def foobar(request): date_sel1 = request.POST.get('datetime1',None) date_sel2 = request.POST.get('datetime2',None) if date_sel1!=None: posts = Post.objects.filter(pub_date__range=(date_sel1,date_sel2)).order_by("pub_date","time") paginator = Paginator(posts,6,1) page = request.GET.get('page') try: customer = paginator.page(page) except PageNotAnInteger: customer = paginator.page(1) except EmptyPage: customer = paginator.page(paginator.num_pages) context={'posts':customer} return render(request,'sheet.html',context) html: {% extends 'balance.html' %} … -
django-filter for Boolean
I am a beginner to Django and doing a learning project which is a booking system. Can anyone recommend me an open source django project where I can check the source code for best practices. Thanks in advance When I use the code below, get method gets "on" or "off". How can it be "True"/"False"? Model.py class Mymodel(models.Model): ... is_xxx_approved = models.BooleanField(default=False,blank=False,null=False) is_contracted_by_yy= models.BooleanField(default=False,blank=False,null=False) is_zz_approved = models.BooleanField(default=False,blank=False,null=False) Filter.py class MymodelFilter(django_filters.FilterSet): class Meta: model = Mymodel fields = ['is_xxx_approved', 'is_contracted_by_yy', 'is_zz_approved'] exclude = [ 'name', 'address', 'phone', 'email',] filter_overrides = { models.BooleanField: { 'filter_class': django_filters.BooleanFilter, 'extra': lambda f: { 'widget': forms.CheckboxInput, }, }, } Template <div class="filter_index"> {% with field=filter.form.is_xxx_approved %} {{ field.label_tag }} {{ field }} {% endwith %} </div> <div class="filter_index"> {% with field=filter.form.is_contracted_by_yy %} {{ field.label_tag }} {{ field }} {% endwith %} </div> <div class="filter_index"> {% with field=filter.form.is_zz_approved %} {{ field.label_tag }} {{ field }} {% endwith %} </div>