Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CBV - Formsets : 'NoneType' object has no attribute 'id'
I'm working with Django CBV and I'm trying to use formsets for the first time. I would like to fill two forms in the same time with a Foreign Key as common element between both. I have 2 models : class Publication(models.Model): title = models.CharField(max_length=512, verbose_name=_('title'), null=False, unique=True) description = models.TextField(verbose_name=_('description'), null=True) download_limit = models.IntegerField(verbose_name=_('download limit'), null=True) time_limit = models.IntegerField(verbose_name=_('expiration delay'), null=True) category = models.ForeignKey(Category, verbose_name=_('category'), null=False) nb_document = models.IntegerField(verbose_name=_('number of document'), default=0) creation_date = models.DateTimeField(auto_now_add=True, verbose_name=_('creation date'), null=False) modification_date = models.DateTimeField(auto_now=True, verbose_name=_('modification date'), null=False) class Meta: verbose_name = _('publication') verbose_name_plural = _('publication') def __str__(self): return f"{self.title}" class Document(models.Model): FORMAT_CHOICES = ( ('pdf', 'pdf'), ('epub', 'epub'), ) edqm_id = models.CharField(max_length=12, verbose_name=_('publication ID'), unique=True, default='') language = models.CharField(max_length=2, verbose_name=_('language'), null=False) format = models.CharField(max_length=10, verbose_name=_('format'), choices=FORMAT_CHOICES, null=False) title = models.CharField(max_length=512, verbose_name=_('title'), null=False) publication = models.ForeignKey(Publication, verbose_name=_('publication'), null=False, related_name='documents') upload = models.FileField(upload_to='media/', validators=[validate_file_extension]) creation_date = models.DateTimeField(auto_now_add=True, verbose_name=_('creation date'), null=False) modification_date = models.DateTimeField(auto_now=True, verbose_name=_('modification date'), null=False) class Meta: verbose_name = _('document') verbose_name_plural = _('document') def __str__(self): return f"{self.edqm_id} : {self.title} - {self.publication}" I defined formset in my forms python file : class PublicationForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['category'].empty_label = _('Select a category') # Modify initial empty_label class Meta: model = Publication fields … -
Project entering limitation in Django
I want to make a part for my Django project. In my Django app, there is a new project part. But I the thing I want is a user can enter only one project. This user must not enter the second one. How can I do it? views.py def project_new(request): if request.method == 'POST': form = ProjectForm(request.POST) if form.is_valid(): project = Project() project.first_name = form.cleaned_data['first_name'] project.last_name = form.cleaned_data['last_name'] project.email = form.cleaned_data['email'] project.project_name = form.cleaned_data['project_name'] project.project_description = form.cleaned_data['project_description'] project.project_notes = form.cleaned_data['project_notes'] project.published_date = timezone.now() project.save() return redirect('project_detail', pk=project.pk) else: form = ProjectForm() return render(request, 'blog/project_new.html', {'form': form}) models.py class Project(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.CharField(max_length=100) project_name = models.CharField(max_length=300) project_description = models.TextField() project_notes = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.project_name I find django singleton model but I cannot make it. Please help me. -
Generating dynamic form fields from querysets in Django
So I have this queryset that I get by using a filter. The queryset looks like this: <QuerySet [<Producto: Budin>, <Producto: Papas>, <Producto: Bolson de verduras>, <Producto: Bolson frutal>, <Producto: Pepas>, <Producto: Popas>, <Producto: Pipos>, <Producto: Café Molido Colombiano Agroecólogico Pues x1/2Kg>, <Producto: Albacores>, <Producto: Cangrejos>, <Producto: Peces>, <Producto: lardis>, <Producto: nueces>]> The filter looks like this: Producto.objects.filter(productor=pk) Each "producto" from the queryset has a field called stock. I want to generate dynamic forms that display, for each user, the amount of stock they have and a form field for they to change it It should look like this: https://gyazo.com/e1a1024515ff31e1f6d00e35a0f464fb How should the forms.py class look like? -
Django - Pivot data
I am preparing a report where the output needed is something like a pivot table. I am able to get the required output numbers but not in desired format. Below is the query that i have written for getting the data. net2 = AccountNetworkMapping.objects.filter(accountId=24).values_list('accountId__accountName','serviceFunctionName', 'networkCode', 'cji3report__period').annotate(Sum('cji3report__valInRepCurrency')) Now i am getting a queryset with something like this ('Acc1', '1st Level Ops', 10048666, 1, Decimal('1996')) ('Acc1', '1st Level Ops', 10048666, 2, Decimal('1868')) ('Acc1', '1st Level Ops', 10048666, 3, Decimal('872')) ('Acc1', '2nd Level Ops', 10048667, 4, Decimal('119.4')) ('Acc1', '2nd Level Ops', 10048667, 5, Decimal('128.2')) ('Acc1', '2nd Level Ops', 10048667, 6, Decimal('127')) ('Acc1', '2nd Level Ops', 10048667, 7, Decimal('135')) ('Acc1', 'Dispatch', 10069920, None, None) ('Acc1', 'Incident Mgmt.', 10048674, 1,Decimal('6067.71 ('Acc1', 'Incident Mgmt', 10048674, 2, Decimal('5276.65 ('Acc1', 'Incident Mgmt', 10048674, 3, Decimal('6077.88 ('Acc1', 'Incident Mgmt', 10048674, 4, Decimal('4617.83 ('Acc1', 'Incident Mgmt', 10048674, 5, Decimal('5125.52 ('Acc1', 'Incident Mgmt', 10048674, 6, Decimal('4630.80 ('Acc1', 'Incident Mgmt', 10048674, 7, Decimal('5502.61 ('Acc1', 'Operations mgmt', 10048673, 1, Decimal('1914.18')) ('Acc1', 'Operations mgmt', 10048673, 2, Decimal('9371.42')) ('Acc1', 'Operations mgmt', 10048673, 3, Decimal('6550.40')) ('Acc1', 'Operations mgmt', 10048673, 4, Decimal('5687.95')) ('Acc1', 'Operations mgmt', 10048673, 5, Decimal('5885.44')) ('Acc1', 'Operations mgmt', 10048673, 6, Decimal('448.20')) ('Acc1', 'Operations mgmt', 10048673, 7, Decimal('3393.38')) ('Acc1', 'Optimization', 10048671, 1, Decimal('17664.03')) ('Acc1', 'Optimization', … -
Django - migrate error occurs when change the existing ManyToMany field to ForeignKey field
I'm trying to change a model field from ManyToMany field to ForeignKey field. This error was thrown when I run python manage.py migrate book. I have no idea how this happened. Error: django.db.utils.IntegrityError: Cannot add or update a child row: a foreign key constraint fails (`eshop`.`#sql-1a1a_233a`, CONSTRAINT `book_book_publisher_id_7f77c06a_fk_book_publisher_id` FOREIGN KEY (`publisher_id`) REFERENCES `book_publisher` (`id`)) book_book table in MySQL: mysql> describe book_book; +---------------+---------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------------+---------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | title | varchar(255) | NO | | NULL | | | pub_date | date | NO | | NULL | | | language | varchar(255) | NO | | NULL | | | print_length | decimal(6,0) | NO | | NULL | | | price | decimal(10,2) | NO | | NULL | | | quantity | int(11) | YES | | NULL | | | description | longtext | YES | | NULL | | | created_date | datetime(6) | NO | | NULL | | | is_active | tinyint(1) | NO | | NULL | | | last_modified | datetime(6) | NO | | NULL | | | … -
Django Inline Add Another not responsive
I'm managing a Django (1.11) app and I've noticed that all of the Add Another buttons on an admin page for one object are not responsive, i.e. clicking on them does nothing. This happens for one particular model only. Using Inspect Element on the buttons, I noticed that they seem to be different from the Add Another buttons in inlines on admin pages of other models. Affected model admin page inlines: <a href="javascript://" class="add-handler djn-add-handler "> Add another File Upload </a> Other working model admin pages: <a href="javascript://" class="add-handler djn-add-handler djn-model-tracker_app-fileupload"> Add another File Upload </a> I'm still fairly new to Django, so I'm not sure how these are generated. I've searched the entire project and I found the code snippets below in app_root\static\nested_admin\dist\nested_admin.js and app_root\static\nested_admin\dist\jquery.djangoformset.js 49 this.opts = _jquery2.default.extend({}, this.opts, { 50: addButtonSelector: '.djn-add-handler.djn-model-' + inlineModelClassName, The FileUploadInline definition (reused for all models in the app) is as following: class FileUploadInline(NestedStackedInline): # object of type FileUpload model = FileUpload extra = 0 # the attach_file field is a string pointing out the path to a certain document in the media folder fields = ['attach_file'] def has_change_permission(self, request, obj=None): if request.user.has_perm('tracker_app.change_fileupload') or request.user.has_perm( 'tracker_app.view_fileupload'): return True else: return False Has … -
Django crispy forms: one help text for two fields?
I have a form where my users can fill out latitude and longitude coordinates. Now I'd like to write a help text for both, but don't want it to split or to only write the help text for one field. Is it possible to have a help text that takes the whole row under my fields? I know I could just simply remove the help_text from my model fields and add a HTML() to my crispy form, but I wonder if there is a smoother solution? My code right now is like this: model.py latitude = models.DecimalField(u'Latitude', max_digits=11, decimal_places=8, blank=True, null=True) longitude = models.DecimalField(u'Longitude', max_digits=11, decimal_places=8, blank=True, null=True) forms.py class myForm(forms.ModelForm): ... self.helper.add_layout(Layout( Row( Div('latitude', css_class='col-sm-6'), Div('longitude', css_class='col-sm-6'), // is adding HTML() the best solution? ), )) thanks for the answers! -
use of jinja logic and multiple models in a webpage
i have 3 model class that i want to fit into my html home page, using jinja to {% block featurette %} {% endblock %} to get the models information, but just one models seems to be working on my html page. here's my html home page {% block marketing %} <div class="container marketing"> <!-- Three columns of text below the carousel --> <div class="row"> {% for first in object_list %} <div class="col-lg-4"> <center><img class="rounded-circle" src="{{ first.image.url }}" alt="Generic placeholder image" width="140" height="140"></center> <center><h2><a href="/home/{{ first.id }}">{{ first.title }}</h2></center></a> <p><a href="/home/{{ first.id }}">{{ first.body}}</p></a> <p><a class="btn btn-info" href="/home/{{ first.id }}" role="button">View details &raquo;</a></p> </div> {% endfor %} {% endblock %} </div> <!-- START THE FEATURETTES --> {% block featurette %} {% for second in posts %} <hr class="featurette-divider"> <div class="row featurette"> <div class="col-md-7"> <h2 class="featurette-heading">{{ second.title }}</h2> <p class="lead">{{ second.body }}</p> </div> <div class="col-md-5"> <img class="featurette-image img-fluid mx-auto" src="src="{{ second.image.url }} alt="Generic placeholder image" width="350" height="300"> </div> </div> {% endfor %} and my models are : `from django.db import models from django.contrib.auth.models import User class First(models.Model): title=models.CharField(max_length=800) body=models.TextField() image = models.ImageField(upload_to='profile_image/%Y/%m/%d', blank=True) date = models.DateTimeField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Second(models.Model): title=models.CharField(max_length=800) body=models.TextField() image … -
502 Bad Gateway django nginx/1.14.0 (Ubuntu)
I am using post request to load a big amount of data from user input (textarea) to the database(18k lines) And I get the 502 Bad Gateway error When I print sudo nano /var/log/nginx/error.log I get this: 2018/09/06 10:21:04 [alert] 19688#19688: *3 open socket #22 left in connection 4 2018/09/06 10:21:04 [alert] 19688#19688: aborting 2018/09/06 11:04:32 [error] 20076#20076: *14 upstream prematurely closed connection while reading response header from upstream, client: 95.1$ This is only on my production server (nginx + gunicorn + postgres), on my dev server it works great. What do I do? -
Why Django Signal used weakref and threading.Lock()?
As I'm reading the Django-Signal source code, I found it used weakref and threading.Lock, But why used this? The receiver decorator will decorate receive-function at Django initialization, where is the multiprocessing? And I know the weakref is the weak reference, but why should it used this? Singal.connect: if weak: ref = weakref.ref receiver_object = receiver # Check for bound methods if hasattr(receiver, '__self__') and hasattr(receiver, '__func__'): ref = WeakMethod receiver_object = receiver.__self__ if six.PY3: receiver = ref(receiver) weakref.finalize(receiver_object, self._remove_receiver) else: receiver = ref(receiver, self._remove_receiver) with self.lock: self._clear_dead_receivers() for r_key, _ in self.receivers: if r_key == lookup_key: break else: self.receivers.append((lookup_key, receiver)) self.sender_receivers_cache.clear() -
Django update settings in Celery's async task
I am using celery to load Neural Network models and would like to store the loaded model in settings. For fast prediction. in django.conf.settings I have: MODELS = {} and in celery task, I have the following snippet: settings.MODELS[new_model.name] = {'model': net, 'graph': sess} However, I noticed that the tasks are running in another thread that launches different Django Environment and any changes in the settings will not be reflected back to the main thread. Is there a workaround for this? -
Django : User account creation with two different models
disclaimer : I've gone through the django - documentation, but didn't come to a conclusion. I was handed over a project of my senior in college to work on with. In an application in the project: accounts - obviously it's to create user accounts. in models.py from django.contrib import auth from django.db import models class User(auth.models.User, auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) though in the forms.py this model was not used. forms.py from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from django import forms class UserCreateForm(UserCreationForm): class Meta: fields = ("first_name", "last_name", "username", "email", "password1", "password2") model = get_user_model() But here the imported model is something other than the defined model in models.py, rather he imported the model from from django.contrib.auth So I've tried to comment out the model from the models.py and migrate, it yields an error. django.db.utils.OperationalError: near ")": syntax error rather instead of model = get_user_model I've used model = User (from models.py) even this yield's error unable to import User Could anyone please explain me what's the relation and why should I use both the models?? Since the senior is no more, I've no chance of contacting him. -
How To lookup tuples in Serializer?
I have models.py like This .......... ... GENDER =( ('MALE',1), ('FEMALE',2), ('OTHERS',3) ) class User(BaseModel, AbstractUser): type = models.IntegerField(choices=USER_TYPE,null=True) gender = models.IntegerField(choices=GENDER,null=True) ......................... ......................... And Views.py to list student is like this def list(self,request): for adm in StudentAdmission.objects.all(): user = adm.student.user tmp['user'] = UserGetSerializer(user).data ud = UserDetail.objects.filter(user_id=user.id) if ud: tmp['user_detail'] = UserDetailSerializer(ud.first()).data tmp['Address..........lots of code..... And serializer.py like This... class UserBaseSerializer(serializers.Serializer): first_name = serializers.CharField(max_length=120,required=True) last_name = serializers.CharField(max_length=120,required=True) email = serializers.EmailField(required=True) class UserSerializer(UserBaseSerializer): gender = serializers.IntegerField() type = serializers.IntegerField(default=3) class UserGetSerializer(UserBaseSerializer): gender = serializers.SerializerMethodField() type = serializers.IntegerField(default=3) def get_gender(self, obj): #Here Confusion return {'id':obj.gender, 'value':value} It returns the output 1 in gender instead of returning male. I want to return male instead of 1 . For that i made a get_gender() function to lookup from the tuple and return the value for that object Id .. So My Question Is how can i write get_gender() function To lookup the Gender tuple. Sorry For The English I hope U will Understant My Question -
Type object 'Template' has no attribute 'objects'? [duplicate]
This question is an exact duplicate of: Django type object 'Template' has no attribute 'objects'? i am using django 1.10.5 and having a template app and in model i am using template structure . first it was working but i dont know from yesterday Exception is coming type object 'Template' has no attribute 'objects' and where ever i am using template. template = Template.objects.get(template_default__exact=1) . in traceback it shows error where i define template in my views on every view and every template page . Extension/Views.py from rentacar.forms import * from template.models import Template from module.models import * @csrf_protect def rentacar_list(request, page_number=1): menu_config_list = MenuItemRentacarList.objects.all()[0] menu_config = MenuItemRentacarList.objects.get(id=menu_config_list.id) all_cars = Car.objects.all().order_by('-id') if menu_config.menu_item_rentacar_list_show_unavailable == 0: all_cars = all_cars.exclude(car_available=0) else: all_cars = all_cars cars_page = Paginator(all_cars, menu_config.menu_item_rentacar_list_pagination) args['cars'] = cars_page.page(page_number) template = Template.objects.get(template_default__exact=1) args['main_menu'] = MenuMenu.objects.get(id__exact=template.template_main_menu_id) args['menu_items'] = MenuItem.objects.filter( menu_item_menu=args['main_menu'], menu_item_published=1, ) template_page = template.template_alias + str("/rentacar/rentacar_cars_list.html") args['current_menu_item'] = menu_config.menu_item_rentacar_list_menu_item all_modules = Module.objects.filter( module_show_option__exact='all', module_published=1 ) selected_modules = Module.objects.filter( module_show_option__exact='selected', module_published=1, module_menu_item=args['current_menu_item'] ) excluded_modules = Module.objects.filter( module_show_option__exact='except', module_published=1, ).exclude( module_menu_item=args['current_menu_item'] ) args['modules'] = list(chain(all_modules, selected_modules, excluded_modules)) return render(request, template_page, args) Templates/Models.py from __future__ import unicode_literals from django.db import models from mega_admin.models import MenuMenu # Create your models here. class Template(models.Model): class … -
Django shows error while connecting models (ManyToManyField)
django shows operational error when i try to add an object with another object or shows no such table. MODELS: class Tag(models.Model): name = models.CharField( max_length=31, unique=True) slug = models.SlugField( max_length=31, unique=True, help_text='A label for URL config.') class Meta: ordering=['name'] def __str__(self): return self.name ##################### TWO class Startup(models.Model): name = models.CharField( max_length=31, db_index=True) slug = models.SlugField( max_length=31, unique=True, help_text='A label for URL config.') description = models.TextField() founded_date = models.DateField( 'date founded') contact = models.EmailField() website = models.URLField(max_length=255) tags = models.ManyToManyField(Tag) def __str__(self): return self.name SHELL: from organiser.models import Startup,Tag s=Startup(name="expressbay",slug="danish",founded_date="2018-8-6") s.save() t=Tag(name="django",slug="amir") t.save() s.tags.add(t) OperationalError: no such table: organiser_startup_tags -
Meaning of return HttpResponse("")
In python, what the meaning of the below code if written in a function return HttpResponse("") -
Django channels redis channel layer opens a lot of connections
We ported a part of our application to django channels recently, using the redis channel layer backend. A part of our setup still runs on python2 in a docker which is why we use redis pub/sub to send messages back to the client. A global listener (inspired by this thread) catches all messages and distributes them into the django channels system. It all works fine so far but I see a lot of debug messages Creating tcp connection... passing by. The output posted below corresponds to one event. Both the listener as well as the consumer seem to be creating two redis connections. I have not enough knowledge about the underlying mechanism to be able to tell if this the expected behavior, thus me asking here. Is this to be expected? The Listener uses a global channel layer instance: # maps the publish type to a method name of the django channel consumer PUBLISH_TYPE_EVENT_MAP = { 'state_change': 'update_client_state', 'message': 'notify_client', } channel_layer = layers.get_channel_layer() class Command(BaseCommand): help = u'Opens a connection to Redis and listens for messages, ' \ u'and then whenever it gets one, sends the message onto a channel ' \ u'in the Django channel system' ... def … -
error :object can't be deleted because its id attribute is set to None
Trying to Delete an object using shell in django. How do i delete the object say "Ron"? I use the following command: t.delete('Ron') -
how to reinitialise the value for {% with %} django
I want to do something like this. {% with x=1 %} {% x =5 %} {%endwith} -
if I am using django-rest-auth how to check if email is verified or not in my LoginView?
I want to show a different message if user hasn't verified email address. def post(self, request, *args, **kwargs): self.request = request self.serializer = self.get_serializer(data=self.request.data, context={'request': request}) # print(self.request.data) # print(self.request.user) # print(self.request.data.email) email = self.request.data['email'] # print(email) # if not request.user.email.verified: # print("in verification") # return Response({"message":"Please verify your email"}) from allauth.account import app_settings if app_settings.EMAIL_VERIFICATION == app_settings.EmailVerificationMethod.MANDATORY: email_address = self.request.user.emailaddress_set.get(email=self.request.user.email) print(email_address) if not email_address.verified: return Response({"message":"Please verify your email id"}) if self.serializer.is_valid(): # print(self.serializer.errors) # print(self.serializer.data) response = super().post(request, *args, **kwargs) # print(self.request.user) email = self.request.user.email # print(email) if response.status_code == 200: self.save_header() return self.get_response() User Model (I've different table in where I can see if the user have verified it or not (Django-rest-auth provides other model)) class User(AbstractUser): """User model.""" username = None email = models.EmailField(_('email address'), unique=True) mobile_token = models.CharField(max_length=20,blank=True,null=True) U_ID = models.CharField(max_length=20,blank=True,null=True) AI = models.IntegerField(default=0) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] -
Django import-export when exported more than once in a row updated database for all but gives only one file
This view is used to export a file with 50 items at a time. I am using postgresql. from items.resources import ItemResource from django.db import transaction class ExportView(View): @transaction.atomic def get(self, request): item_resource = ItemResource() queryset = Item.objects.select_for_update().filter(used=False)[:50] for i in queryset: i.used = True i.save() dataset = item_resource.export(queryset) response = HttpResponse(dataset.tsv, content_type='text/tsv') response['Content-Disposition'] = 'attachment; filename="item.txt"' return response But when a link that redirects to this view is clicked multiple times say 3 times instead of 50 items having been updated, 150 items are updated. Earlier it caused a deadlock and I started using the select_for_update. So what can be done to prevent this behaviour? If anyone can explain or even point to the right direction for reading material I will be grateful. I have tried to solve this with onclick the style of the link is "display:none" as a temporary measure. <a href="/my_dowload">Download</a> -
How To Convert (2018-09-05T09:00:06.540486Z) Into (2018-09-05) In python?
I have searched for a solution but I have not found any, I have a dictionary like This tmp ={ 'admission_date':adm.admission_date, 'course':adm.course.name } In models.py i have admission_date to DatetimeField. In the Get Function I want to format this date like this 2018-09-05 By removing all part How can i do This. -
Django Gunicorn where logs are stored
I have deployed my app using some tutorial(don't remember which exactly) nginx+gunicorn Right now everything works fine on my dev server But on production it fails with Internal Server Error when I try to download file How and where can I find gunicorn logs? (I use ubuntu) Also, this is piece of code that causes an error just in case: def download_xlsx(request): user = request.user file_name = request.GET['file_name'] file_path='main_app/static/xlsx/' + str(user.id) + '/' + file_name disposition= 'attachment; filename="' +smart_str(file_name) + '"' disposition=disposition.encode('utf-8') if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel") response['Content-Disposition'] = disposition return response return projects.to_utf8_json_response('not found') -
How can I know if my django SQL queries are fully optimized?
I'm learning how to optimize my database queries to achieve the minimal amount of queries possible, and I'm doing so in my django admin. I've optimized two models already to a number of queries (5 for the first model and 6 for the second model) that isn't dependent on the amount of model objects I have. I used to suffer from the N+1 (it was more than n+1 though) and now I always get k queries, no matter how many model objects exist, which is great, but I don't know if my queries are optimized to their fullest. So my questions are: If my query amount is non-dependent on the number of models, does that mean my code is as optimized as it can be? If not, what's an indicator that my queries are at their minimal amount? -
Django Fields - How to prefix a field's db value based on another field's value?
I am trying to prefix the username field of the user object. But I'm also trying to make the prefix dependant on the value of is_staff. I've looked into using the from_db_value and get_prep_value methods, but these don't provide the user object (thus, no way to determine the is_staff value) The pre_save provides access to the user model, but does not help when querying e.g. .filter(username='Username123', is_staff=True) to filter Users with username staff:Username123 Does anyone have any recommendations on how to both save and query against the prefixed value which depends on the is_staff flag?