Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I get an error list that says this field is required
this is the forms page from django import forms from django.contrib.auth.models import User from .models import Profile class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput, required=False) class Meta(): model = User fields = ['username', 'email', 'password'] class ProfileForm(forms.ModelForm): class Meta(): model = Profile fields = ['pic'] & this is the views page from django.shortcuts import render from .forms import UserForm, ProfileForm def register(request): if(request.method == 'POST'): userform = UserForm(request.POST) profileform = ProfileForm(request.POST) if(userform.is_valid() and profileform.is_valid()): user = userform.save() user.set_password(user.password) user.save() profile = profileform.save(commit=False) profile.user = user if('pic' in request.FILES): profile.pic = request.FILES['pic'] profile.save() else: print(userform.errors, profileform.errors) else: userform = UserForm() profileform = ProfileForm() return render(request, 'register.html', {'userform':userform, 'profileform':profileform}) when I submit the password or the picture it doesn't save the user to the admin area and says that password is required and the picture is not uploaded -
Django: Check if value in list
I have a QuerySet with several entries order.order_items.all. I want to check in my template if any of these items in my list contain the foreign_key discount. After one is found, I want to display that a discount_code was used for the order. How would you solve this? Example: <QuerySet [OrderItem: #k9ukvrfvjk - 1x Test Ticket 1, OrderItem: #k9ukvrfvjk - 1x Test Ticket 2]> -
Django and python - different versions
i' ve an application running quite long time ago with python 2.6.6 and django 1.4.5 . It' s running on apache2 and debian (of course it uses virtualenv). I' d like to add another application onto that server, but with python 3.4.5 and django 1.9(+). They' d have of course a different virtualenvironment, even a different domain, however i' d like them to use the same db. My question would what kind of complications will i face? For instance different table layout for django tables, no south anymore, but migrate, etc. Are these problems even overcomeable? Thanks. -
Django rest framework+jquery error handling
I've created api using django rest framework. In frontend used jquery to process some inter activity. Using jquery ajax I have done most of the part. But problem is error handling. Want to show error if validation failed. How can I do that easily? -
Error importing data to a model in Django
I´m trying to import data from a csv file to a Django model. I´m using the manage.py shell for it with the following code: >>> import csv >>> import os >>> path = "C:\\Users\Lia Love\Downloads" >>> os.chdir(path) >>> from catalog.models import ProductosBase >>> with open('FarmaciasGob.csv') as csvfile: ... reader = csv.DictReader(csvfile) ... for row in reader: ... p = Country(country=row['Country'], continent=row['Continent']) ... p.save() ... >>> >>> exit() I get the following error message at a given point of the dataset: UnicodeDecodeError: "charmap" codec can´t decode byte 0x81 in position 7823: character maps to (undefined) For what I could find, it seems to be a problem with the "latin" encoding of the csv file. Inspecting the csv, I don´t see nothing special about the specific row where it get´s the error. I´m able to import about 2200 rows before this one, all with latin characters. Any clues? -
Django 2.1 using TinyMCE 4 as the email template editor, but how do I get it to upload images easily?
I am new to Django 2.1 and need to create an admin site to manage and edit email communication templates. The content is stored in a text area field. I tried using TinyMCE both with the JS link and installing Django-TinyMCE and FileBrower to be a full blown WYSIWYG editor to allow for formatting. But, I cannot get it to work using either method to upload images. I followed many steps provided in the TinyMCE website and in other Stack members’ answers. Can someone help? -
Django: constant 3rd party api data stream into frontend?
I'm building an application on react/django that requires me to have a live stream of real time weather information presented to a user. Currently my app gets a snapshot of information whenever a user loads the page via axios request to my django backend that makes an api call and return the weather back at that given time. Only when a user reloads the page can I get new weather information. I've done some reading and it seems that I might want to look into django channels. Is this a proper/standard flow for apps streaming information live from 3rd party sources? I imagine having a websocket connection between react and django, and django having some logic for an api call every set interval - returning that data back to react. If so, where in my django-channels consumer would I have this interval logic? And what is the best way to run an api call every (1 second) in django? Would it be in my Consumer's connect definition? Ideally I'd only like the user to have to send one automatic request on page load that begins the socket connection and have weather information streamed back based on what states the user … -
Django compressor isn't working on heroku
I'm using Django with the Django compressor package on heroku. To make the setup easier I'm using the official Django + Heroku package. My base.html template has the following include tag: {% include 'base/js.html' %} This file contains all JS files: {% load static %} {% load compress %} {% compress js %} <script src="{% static 'libs/jquery/dist/jquery.min.js' %}"></script> <script src="{% static 'libs/bootstrap/dist/js/bootstrap.bundle.min.js' %}"></script> # ... {% endcompress %} I've enabled COMPRESS_OFFLINE = True and my release task has the following command: python manage.py compress Since heroku does the collectstatic before running this command I've added another collectstatic command after the compress command. The first problem is that if I push my code with this settings, the JS just disappears. Event if I add normal html in the js.html file it's not displayed like it was never included. If I move the content from js.html to the base.html file I will get this error: OfflineGenerationError: You have offline compression enabled but key "37bfd22c7ae7d3c1ebae6f1f6cf17b892d51be333cd571cb6c1466d1291cd228" is missing from offline manifest. You may need to run "python manage.py compress". I've also tried running the compress command again but nothing happens. The error is still there. -
Django worker not handling oath replies correctly with daphne
Creating title for this question was tricky, so please forgive. I am trying to setup SSO with MicroSoft and Django. Found a promising plugin to handle this, but having some issues I think may be related to django / daphne more than the plugin itself. The plugin is designed to handle the callback from MS SSO, and there a django view that handles the response. Well, this is not working as expected. The question however is about the behavior of what I am seeing in the logs while troubleshooting. I can see the callback come in: worker logs: 2018-11-23 17:23:54,920 - DEBUG - worker - Dispatching message on http.request to channels.handler.ViewConsumer Bad Request: /microsoft/auth-callback/ daphne logs 2018-11-23 17:23:54,920 INFO "127.0.0.1" - - [23/Nov/2018:17:26:28 +0000] "POST /microsoft/auth-callback/ HTTP/1.1" 400 665 "https://login.microsoftonline.com/common/reprocess?ctx=****&sessionid=*******" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0" However, this is where it dies. The reply is supposed to have a payload containing the session state. However, while watching the django worker log, I restarted the django worker. While shutting down the workers, I see this appear in the logs: 2018-11-23 17:30:26,746 - INFO - worker - Shutdown signal received while idle, terminating immediately {'state': '****', 'session_state': '***'} This … -
How to test POST method using DRF and HyperlinkedModelSerializer serializer
I am using Django Rest Framework (DRF), and I am trying to test a POST method. These are my models: class CustomUser(AbstractUser): def __str__(self): return self.email class Meta: ordering = ('id',) verbose_name = 'user' class Brand(Group): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='%(class)ss', related_query_name='%(class)s') description = models.TextField('description', max_length=3000, blank=True) facebook_url = models.URLField('facebook url', blank=True) twitter_url = models.URLField('twitter url', blank=True) instagram_url = models.URLField('instagram url', blank=True) pinterest_url = models.URLField('pinterest url', blank=True) portfolio_url = models.URLField('portfolio url', blank=True) phone_number = PhoneNumberField('phone number', blank=True) These are my serializers: class CustomUserSerializer(HyperlinkedModelSerializer): brands = HyperlinkedRelatedField( many=True, read_only=True, view_name='brand-detail' ) class Meta: model = CustomUser fields = ( 'url', 'username', 'email', 'brands', ) class BrandSerializer(HyperlinkedModelSerializer): addresses = HyperlinkedRelatedField(many=True, read_only=True, view_name='address-detail') class Meta: model = Brand fields = ( 'url', 'name', 'owner', 'description', 'facebook_url', 'twitter_url', 'instagram_url', 'pinterest_url', 'portfolio_url', 'phone_number', ) These are my views: class CustomUserViewSet(ModelViewSet): """"A view set for viewing and editing custom users.""" queryset = CustomUser.objects.all() serializer_class = CustomUserSerializer class BrandViewSet(ModelViewSet): """A view set for viewing and editing brands.""" queryset = Brand.objects.all() serializer_class = BrandSerializer And this is my test, I am using pytest: @pytest.mark.django_db def test_create_brand_with_valid_data(client): """Tests POST method with valid data to create a Brand instance.""" user = CustomUser.objects.create(username='x', email='x@example.com', password='abc123', ) data = { 'owner': f'http://testserver/api/users/{user.id}/', … -
Session being set but not persisted
Problem The django.contrib.auth.login function is succeeding, but the session does not seem to persist. Code I am creating my own set of functions to use with an AJAX client inside of my Django server. I have the following code in urls.py: from django.contrib.auth import authenticate, login from django.conf.urls import url from django.http import JsonResponse import json def auth_login(request): username = json.loads(request.body)['username'] password = json.loads(request.body)['password'] user = authenticate(request, username=username, password=password) if user is not None and user.is_active: login(request, user) return JsonResponse({}, status=200) else: return JsonResponse({}, status=400) urlpatterns = [ url(r'auth/login/', auth_login, name='login') ] Details As mentioned above, the call to login() succeeds. request.session is being set properly, and I can access if from within auth_login. On subsequent requests, request.session does not exist and django.contrib.auth.get_user returns AnonymousUser. (Possibly relevant) I am also using the seemingly-popular https://django-tenant-schemas.readthedocs.io/en/latest/. This urls.py file is in an application that is per-tenant, so the user is actually authenticating on tenantname.hostname.com/tenant/auth/login/. The tenant's django_session table is being set correctly. For each attempted login, I can see session_key, session_data, and expire_data. The cookie for tenantname.hostname.com is empty after attempted logins. I'm just out of ideas as to what other things I could try to lead me to a solution. Question(s) … -
Start function on run with Flask
I have a flask app @app.route("/hello") def generater(): return "hello world if __name__ == '__main__': app.run() My application runs fine, but i would like to know how I could make a request to http://127.0.0.1:5000/hello when I compile my code -
Can't login django super user using custom command
This is my super user creation logic in djagno, class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, mobile, username, password, **extra_fields): if not mobile: raise ValueError('The given email must be set') user = self.model(mobile=mobile, username=username, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, mobile, username, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) extra_fields.setdefault('is_active', False) return self._create_user(mobile, username, password, **extra_fields) def create_superuser(self, mobile, username, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) return self._create_user(mobile, username, password, **extra_fields) This works when I create a superuser using, python manage.py createsuperuser However when I try using this Custom command, class Command(BaseCommand): def handle(self, *args, **options): logger = logging.getLogger(__name__) with open('config/config.yaml', 'r') as stream: try: conf = yaml.load(stream) username = conf['users']['root']['username'] mobile = conf['users']['root']['mobile'] password = conf['users']['root']['password'] if not User.objects.filter(mobile=mobile).exists(): User.objects.create_superuser(mobile, username, password) except yaml.YAMLError as e: logger.error(str(e)) The User gets created and has all the permissions, yet I can't log into django admin using these credential, I get the following error, Please enter the correct mobile and password for a staff account. Note that both fields may be case-sensitive. Can someone help. -
Return Class based view from function based view
So I set up a login view, and upon successful login I'd like to go to a page of my choice by referencing another class based view. I'm not entirely sure how to achieve this. Login view def login_view(request): if request.method == 'POST': form =AuthenticationForm(data=request.POST) if form.is_valid(): user=form.get_user() login(request,user) #Not sure what to do next #return HttpResponseRedirect(reverse(request, Dashboard))? else: #TODO else: form = AuthenticationForm() Dashboard class I'm trying to get to class Dashboard(ListView): model = models.Note template_name = 'notemanager/dashboard.html' def get_context_data(self, request,**kwargs): context = super().get_context_data(**kwargs) notedata = models.Note.objects.filter(added_by = User) reminderdata = models.Reminder.objects.filter(added_by = User) context['notes'] = notedata context['reminder'] = reminderdata return context -
Posting JSON boolean Django
I'm trying to send a POST request containing a boolean value like this: { "is_manager": true } The request is then handled by an overriden adapter from django-allauth: from allauth.account.adapter import DefaultAccountAdapter class CustomUserAccountAdapter(DefaultAccountAdapter): def save_user(self, request, user, form, commit=True): """ Saves a new `User` instance using information provided in the signup form. """ from allauth.account.utils import user_field user = super().save_user(request, user, form, False) user_field(user, 'is_manager', request.data.get('is_manager', False)) user.save() return user But i get this error: TypeError: 'bool' object is not subscriptable I tried using json.loads but this method only accepts strings as argument. What can i do? Thanks in advance. -
Django uploading to Amazon s3 with chunks
We're using the S3Boto3Storage to upload media files to our s3 storage on Amazon. This works pretty well. Since we're using Cloudflare as a "free" version we're limited to a maximum of 100MB per request. This is a big problem. Even the Enterprise plan is limited to 500MB. Is there a way to use a kind of "chunked uploads" to bypass the 100MB-per-request limit? model.py class Media(models.Model): name = models.CharField(max_length=100, null=True) file = models.FileField(upload_to=get_path) storage.py from storages.backends.s3boto3 import S3Boto3Storage class MediaStorage(S3Boto3Storage): location = 'media' file_overwrite = False views.py @api_view(['POST']) def upload_media(request): if request.method == 'POST': serializer = MediaSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
How to get the current path in a django view?
So the question is really simple i need a method to get the current url in a class based view in django, requests.path doesnt work im not sure why - Do i need to import something? I tried : "from django.http import request" but that doesnt have an Attribute path. -
All data points are not appearing in a line chart made using chart.js
I am using Django 2.0 for back-end development of a BPO website. In that one, I am trying to show one accounting information (trail balance) of an organisation in a table and two separate line chart for credit and debit accounts.I am using Chart.js for plotting the line chart. The corresponding functions in view.py file of django are: #this preprocess function is used to find out the credit and debit accounts def preprocess(a): label1 = [] label2 = [] arr1 = [] arr2 = [] for i in range(len(a)): if int(a[i,1])!=0: label1.append(a[i,0]) arr1.append(int(a[i,1])) else: label2.append(a[i,0]) arr2.append(int(a[i,2])) return label1,label2,list(arr1),list(arr2) @login_required def Acc_Info(request): obj = request.user if(request.method=='GET'): obj1 = Company.objects.get(username=obj) dt = int(datetime.date.today().year) obj2 = AccountingInfo.objects.filter(company_code=obj1,date=dt) if obj2.exists(): obj2 = AccountingInfo.objects.get(company_code=obj1,date=dt) path = settings.MEDIA_ROOT+'/'+str(obj2.info) # names = ['Name of Account','Credit','Debit'] data = pd.read_csv(path) data = np.array(data) # dr = list(data[:,1]) # cr = list(data[:,2]) label1,label2,dr,cr = preprocess(data) print("\n\ncr = ",cr) print("\n\ndr = ",dr) Debit_sum = data[:,1].sum(dtype=np.float64) Credit_sum = data[:,2].sum(dtype=np.float64) return render(request,'Acc_Info.html',{'f':True,'lc':len(cr),'lr':len(dr),'label1':label1,'label2':label2,'cr':cr,'dr':dr,'year':datetime.date.today().year,'data':data,'Suspense':Credit_sum-Debit_sum,'Credit_sum':Credit_sum,'Debit_sum':Debit_sum}) else: return render(request,'Acc_Info.html',{'f':False,'year':dt}) else: obj1 = Company.objects.get(username=obj) dt = request.POST['year'] obj2 = AccountingInfo.objects.filter(company_code=obj1,date=dt) if obj2.exists(): obj2 = AccountingInfo.objects.get(company_code=obj1,date=dt) path = settings.MEDIA_ROOT+'/'+str(obj2.info) data = pd.read_csv(path) data = np.array(data) label1,label2,dr,cr = preprocess(data) print("\n\ncr = ",cr) print("\n\ndr = ",dr) Credit_sum = data[:,2].sum(dtype=np.float64) Debit_sum = … -
Save chinese character in Django SQLite model field & Displaying in Template
How do I save chinese characters in Django model fields and show this properly in the HTML template and django-admin? I would like to save chinese names into the database. They are only 3 characters long. If this is too complex, are there any workaround such as outputting the characters in image file and saving the characters as an image? I don't plan on manipulating the characters stored 'in-string', only saving and showing them on the template. Thank you. -
Django: Combining textbox and dropdown from values stored in database in Django forms
I've two models User and Company. I have created two custom forms from these models and showing in the same template for signup. Logic is like, if the company already exists in the database then it shouldn't create a new record in the Company but just assign the existing company to the user. Otherwise, create a new company and assign to the user. For the convenience, on the signup template, I want to show the dropdown with all the existing company names from the company table. So that either user can select the name from the list or write his own company. Following is my code files signup.html {{ company_info_form.company_name|as_crispy_field }} {{ company_info_form.company_address|as_crispy_field }} forms.py class CompanyInformationForm(ModelForm): company_name = forms.CharField(label = popover_html('Company Name', 'Company Name')) company_address = forms.CharField(label = popover_html('Company Address', 'Compnay Address')) class Meta: model = CompanyInformation fields = ( "company_name", "company_address" ) views.py (for GET request): form = RegistrationForm() company_info_form = CompanyInformationForm() args = {"form": form, "company_info_form": company_info_form} return render(request, "registration/signup.html", args) I assume I don't need to do many changes if I can make a combo of textbox and dropdown both. As I will read the value to apply the logic. P.S. Let me know if you … -
Site matching query problem with redirects app
I would like to use "redirects app" for redirect all paths from an old site to a new site. On my site I've already "sitemap framework" and "syndication feed framework". Without "redirects app" I don't have problems to see feeds page and sitemap page. I've followed the indications of the official guide to install "redirects app"(only 4 clear steps) and, after the installation, I can see the redirects options in to the admin panel, but I can't see anymore feeds page and sitemap page because it's shown me this error: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/blog/feed/ Django Version: 2.1.3 Python Version: 3.6.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.redirects', 'django.contrib.sitemaps', 'blog', 'kernel', 'service', 'team'] 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', 'django.contrib.redirects.middleware.RedirectFallbackMiddleware'] Traceback: File "/var/www/html/dev/miosito/django/v2.1/versions/devenv/lib/python3.6/site-packages/django/contrib/sites/models.py" in _get_site_by_request 41. SITE_CACHE[host] = self.get(domain__iexact=host) File "/var/www/html/dev/miosito/django/v2.1/versions/devenv/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/var/www/html/dev/miosito/django/v2.1/versions/devenv/lib/python3.6/site-packages/django/db/models/query.py" in get 399. self.model._meta.object_name During handling of the above exception (Site matching query does not exist.), another exception occurred: File "/var/www/html/dev/miosito/django/v2.1/versions/devenv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/var/www/html/dev/miosito/django/v2.1/versions/devenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/var/www/html/dev/miosito/django/v2.1/versions/devenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/www/html/dev/miosito/django/v2.1/versions/devenv/lib/python3.6/site-packages/django/contrib/syndication/views.py" in call 39. feedgen … -
Using django.contrib.session with django.contrib.auth
I would like to use Django's session-based authentication. I have used the following page as an example: https://docs.djangoproject.com/en/2.1/topics/auth/default/#how-to-log-a-user-in. Specifically, my login view looks like this: def auth_login(request): username = json.loads(request.body)['username'] password = json.loads(request.body)['password'] user = authenticate(request, username=username, password=password) if user is not None and user.is_active: login(request, user) return JsonResponse({}, status=200) else: return JsonResponse({}, status=400) The only difference between this and the example from the link above is that there they suggest to redirect to a success page. My application is single-page so I'm making AJAX requests and returning JSON responses. This example does not set a session ID in the cookie for this site, however the request succeeds. If I make a subsequent request to a secure resource, I'm still getting a 403 error. This is my first Django project, so I'm likely forgetting something simple. Any thoughts? -
Django Templates and render() - How to access multiple values
Learning Django and I'm having an issue with accessing 2 different values. In views.py under def home(request, I've added a list of 2 dictionary objects and passed it through under context. It works perfectly, I'm about to for loop over the dictionary in my front_page.html template, but I've also added a simple if title variable which only works if I place {'title': 'Competitive'} before the variable context. from django.shortcuts import render # Create your views here. owl = [ { 'title': 'Competitive' }, { 'Team': 'Dynasty', 'Location': 'Souel Korea', 'Colors': 'Black & Gold', }, { 'Team': 'OutLaws', 'Location': 'Houston', 'Colors': 'Green & Black', } ] def home(request): context = { "owl": owl } return render(request, 'overwatch_main_app/front_page.html', context, {'title': 'Competitive') def second(request): return render(request, 'overwatch_main_app/about.html', {'title': 'Boom'}) I've even tried comp = {'title': 'Competitive'}, and placing comp into the render(). It only works when I place comp, or {'title': 'Competitive'}before content and then content doesn't work. return render(request, 'overwatch_main_app/front_page.html', comp, context) return render(request, 'overwatch_main_app/front_page.html', {'title': Competitive'} , context) How can I pass more than 1 value of dictionaries to my template via render() front_page.html {% extends 'overwatch_main_app/base.html' %} {% block content %} <h1> OverWatch</h1> {% for o in owl %} <p>{{o.Team}}</p> … -
Encode decode problem while writing to excell worksheet in django view
I get below unicodedecodeerror while trying to write to excell worksheet. Exception Type: UnicodeDecodeError Exception Value: 'ascii' codec can't decode byte 0xc3 in position 7: ordinal not in range(128) The string that could not be encoded/decoded was: i>����R< My view lines : def file_write(input): handle1=open('/tmp/filelog.txt','a') handle1.write(str(input)) handle1.close() workbook = xlsxwriter.Workbook('report.xlsx') worksheet = workbook.add_worksheet() teachertitle = "ÖĞR" file_write(teachertitle) worksheet.write("A4", teachertitle, titlescell) workbook.close() The strange thing is. File_write function is working well and it writes "ÖĞR" to a local text file. But when i try to write "ÖĞR" to excell workseeht it throws error. I also tried worksheet.write("A4", teachertitle.encode('utf-8'), titlescell) but still problem continue. I also have # -- coding: utf-8 -- at the beginning of views.py -
Using different database values for BooleanField in Django
I am converting an old MS Access database to a Django-based website. I've converted the data to a SQLite database, and automatically generated the models using inspectdb (which worked as well as could be expected). It seems that MS Access stores boolean values as -1 for True and 0 for False. Rather than modify the database (it is a lot of tables!) I'm trying to subclass models.BooleanField, as follows: class MsAccessBooleanField(models.BooleanField): def from_db_value(self, value, expression, connection): if value == -1: return True if value == 0: return False def to_python(self, value): if value == -1: return True if value == 0: return False def get_prep_value(self, value): if value == True: return -1 if value == False: return 0 return None def get_db_prep_value(self, value, connection, prepared=False): if value == True: return -1 if value == False: return 0 return None When I view entries via the Admin interface, this seems to work (-1 values appear as Yes in the dropdown; 0 values as No). However (this is the problem), when modifying the value and saving, I can only save as No or Unknown (selecting Yes produces a message that no value has been specified). Any idea what I might be doing …