Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django left join on models
Assume u have two models. Let's name them computer and log_file. I want to make a join so that a always display all computer objects, but if there is a related log_file object it is also added to the query result. Which is the best way to achieve this? Relationship: one Computer has one log file. But it is possible it's not uploaded yet to the database. Only gets uploaded when my script throws an error. Sorry for my beginner question, I'm new to Django. following simplified models as an example: Model 1: computer id (pk) computer name mac address (unique) Model 2: log file / max one for each computer id (pk) mac address text field required query: list of all computers and also the log file if there is any in the database. The join is made by the value of the mac address. Think the SQL query would look like the following. But I am not able to translate this with the ORM. SELECT * FROM computer LEFT JOIN log ON computer.mac_address = log_file.mac_address; Thank you! -
issue with celery, sqs, and laravel jobs
I am attempting to receive SQS messages with django/celery that have been queued by a Laravel app via job. Historically I have been able to send and receive these messages with Laravel without an issue. However, Celery cannot seem to process these same messages and keeps throwing errors such as binascii.Error: Incorrect padding and Unrecoverable error: Error('Incorrect padding',) I'm kind of unsure where to attack this, since I can see the messages on SQS and they look fine to me. The job on the Laravel side looks like: public function handle(ElasticUpdateOrCreate $event) { $job = (new SendUpdateOrCreateToElastic($event->id, $event->type)) ->onQueue($this->queue) ->onMessageGroup('default') ->withDeduplicator('unique'); dispatch($job); } and the job itself, the 'handle' portion of which would no longer be needed if I can get this to be picked up by django: public function __construct($id, $type, $source = null) { $this->id = $id; $this->type = $type; $this->source = $source; } public function handle(ElasticService $elasticService) { try { $elasticService->updateOrCreate($this->id, $this->type); } catch (\Exception $e) { Log::error($e->getMessage()); } } Another post is suggesting to base64 encode the message and I tried that weirdly in a couple of ways in the constructor of the Job and then it threw UnicodeDecodeError: 'utf-8' codec can't decode byte 0x95 in … -
Django Templateform issue with multiple databases
I am trying to using multiple databases in my Django project. As you can see I am trying to use the custom database rather than default. In the other functions where the data is correctly extracted from the database mentioned in `objects.using='database'. Only while trying to save the form data using a django Templateform the default database is considered and I am getting the error as below: Exception Type: OperationalError Exception Value: no such table: base_clientprofile Exception Location: /opt/.../.../lib/python2.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 485 Below is my config and code samples. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'trace_one': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'somename', 'USER': 'rootuser', 'PASSWORD': 'password', } } forms.py class TraceClientProfileForm(forms.ModelForm): class Meta: model = ClientProfile fields = [ 'full_name', 'short_name', 'address', ] views.py def trace_post_model_client_create_view(request): form = TraceClientProfileForm(request.POST or None) if form.is_valid(): obj = form.save(commit=False) obj.save(using='default') return HttpResponseRedirect("/traceviews/{num}".format(num=obj.id)) context = { "form": form } template = "trace_tmpl/trace_client_create_view.html" return render(request, template, context) urls.py urlpatterns = patterns( '', url(r'^create/$', trace_post_model_client_create_view, name='traceclientcreate'), ) -
Passing data through Django forms
I feel I'm missing the obvious but I cant work it out! I have written a custom form (for use outside of django admin), which I want to use to create / update instances of a number of model instances as well as hold conditional fields. However I seem to be losing my conditional data. In my view I instansiate an instance of my form and pass it into the request context:- view.py form = MyForm(my_bool=True, pid=7) render(request 'my_page.html', {'form': form}) forms.py class MyForm(forms.Form): def __init__(self, *args, **kwargs): my_bool = kwargs.pop('my_bool', False) self.pid = kwargs.pop('pid', None) super(MyForm, self).__init__(*args, **kwargs) if my_bool: self.fields['textbox'] = forms.CharField(max_length=256) That all works fine and the form renders as expected. Now when I submit the form it hits the below view.py if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): # Do Stuff My problem is that the form object in the above code does not contain my 'textbox' or 'pid' fields even though the form I submitted did. I'm certain whatever I'm doing wrong is extremely obvious but from a whole lot of googling I cant work out a simple way to instantiate a form, pass it some data about what fields I want to … -
For django-storages and GCE, how do you set the GS_CREDENTIALS?
For django-storages and google compute engine (GCE), how do you create and set credentials for a web application? Here is the current documentation: http://django-storages.readthedocs.io/en/latest/backends/gcloud.html -
Django Oauth2 permissions
I'm using django oauth2 for permissions. For most purposes I use the permission class, permission.isAuthenticated to restrict access to an endpoint. However there are certain end points that I need to open up to registered apps without access token. If I use the permission settings permissions.allowAny Then anyone can access the end-point. What I'm ideally looking at is that a client with a valid client_id and client_secret should be able to access these without an access token though. How do I achieve this? -
Why indpectdb in django didn't create all table models?
I have restored the database "AdventureWorks2017" into SQL-Server-2017 , which contains a lot of tables such as: dbo.AWBuildVersion dbo.DatabaseLog dbo.ErrorLog HumanResources.Department HumanResources.Employee ... I am using django==2.0.5 , django-pyodbc-azure==2.0.4.1 , pyodbc==4.0.23 I have tried to generate database in tables in django models by using: python manage.py inspectdb>models.py but only three dbo.AWBuildVersion , dbo.DatabaseLog , dbo.ErrorLog tables generated in models and someother models that django generated such as AuthGroup , AuthGroupPermissions , DjangoMigrations ,... What should i have do , to generate all table models? Thanks. -
Django referral system with pinax-referrals?
I am trying to create referral system in my Django project. I found very interesting app (pinax-referrals) for this task and want to test it. From documentation its not clear how correctly to use it and there is no example. As I understand we need make next steps: 1) Create Profile models with such code: from django.contrib.auth.models import User from django.dispatch import receiver from account.signals import user_signed_up # django-user-account app from pinax.referrals.models import Referral class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) referral = models.OneToOneField(Referral, null=True, on_delete=models.CASCADE) @receiver(user_signed_up) def handle_user_signed_up(sender, user, form, **kwargs): Referral.create(redirect_to=user.profile.get_absolute_url()) 2) Сreate custom signup view: from account.views import SignupView from pinax.referrals.models import Referral class RegistrationView(SignupView): def after_signup(self, form): super(RegistrationView, self).after_signup(form) Referral.record_response(self.request, "USER_SIGNUP") How correct are my steps? Could you give a simple example? -
Django model operations
Actually I am working on a project that sells books , I want whenever the admin set in the booking list the field 'contacted' to True , book.quantity = quantity -1 here's my code ` class Book(models.Model): quantity= models.IntegerField() def __str__(self): return self.title class Booking(models.Model): contacted = models.BooleanField(default=False) book = models.ForeignKey(Book, on_delete=models.CASCADE) def Booking_process(self): booking_set = Booking.objects.get(contacted="True") for booking in booking_set(): book_set = Book.objects.prefetch_related('booking').all() book_set.update(quantity=F("quantity")-1) ' can i know where is the mistake ? ` -
URL patterns in Django 2
I just have started my first project by using Django 2.0 in which I need to define a url in a way as: http://localhost:8000/navigator?search_term=arrow But I couldn't know how to define a string parameter for a url in django 2.0 Here's what I have tried: From ulrs.py: from django.urls import path from . import views urlpatterns = [ path('navigator/<str:search_term>', views.GhNavigator, name='navigator'), ] Help me, please! Thanks in advance! -
Django class based views, passing parameters
I've the following class based view in django rest, class UserRoom(views.APIView): def add_user_to_persistent_room(self, request): try: user = User.objects.get(id=int(request.data['user_id'])) club = Club.objects.get(id=int(request.data['club_id'])) location = Location.objects.get(id=int(request.data['location_id'])) name = location.city + '-' + club.name room, created = PersistentRoom.objects.get_or_create(name=name, defaults={'club': club, 'location': location}) room.users.add(user) room.save() return Response(PersistentRoomSerializer(room).data, status=status.HTTP_201_CREATED) except User.DoesNotExist: return Response("{Error: Either User or Club does not exist}", status=status.HTTP_404_NOT_FOUND) def find_all_rooms_for_user(self, request, **kwargs): try: user = User.objects.get(id=int(kwargs.get('user_id'))) persistent_rooms = user.persistentroom_set.all() floating_rooms = user.floatingroom_set.all() rooms = [PersistentRoomSerializer(persistent_room).data for persistent_room in persistent_rooms] for floating_room in floating_rooms: rooms.append(FloatingRoomSerializer(floating_room).data) return Response(rooms, status=status.HTTP_200_OK) except User.DoesNotExist: return Response("{Error: User does not exist}", status=status.HTTP_404_NOT_FOUND) This is my urls.py urlpatterns = [ url(r'^rooms/persistent/(?P<user_id>[\w.-]+)/(?P<club_id>[\w.-]+)/(?P<location_id>[\w.-]+)/$', UserRoom.add_user_to_persistent_room(), name='add_user_to_persistent_room'), url(r'^rooms/all/(?P<user_id>[\w.-]+)/$', UserRoom.find_all_rooms_for_user(), name='find_all_rooms') ] When I run this I get the following error, TypeError: add_user_to_persistent_room() missing 2 required positional arguments: 'self' and 'request' I understand the reason for this error clearly, my question is how do I pass the request object in the urls.py? -
What to respond to AJAX request in a django application's python code?
I have AJAX script running on my Django application, but at the moment the script does not change the content of my page. I'm trying to get content from a sub-url, but only my HTTP-side of things works as it should, whereas AJAX does nothing (although the AJAX-code will be ran). I'm wondering what I need to respond to the AJAX request with in order to give it the directions it needs to replicate the behaviour of what my HTTPResponse does, but with AJAX principles (not changing the actual page) My views.py has the lines if not request.is_ajax(): return render(request, "selectui/index.html", context) return HttpResponse('') and if the request is not ajax, the page content changes accordingly, but the page reloads (or the url changes). If the request is ajax, this code runs, but does nothing (I tested it with alert() ). $(function() { "use strict"; $("#continentMenu a").on("click", function(event) { event.preventDefault(); var url = $(this).attr("href"); $("#continentName").text($(this).text()); $("#tableContainer").load(url); }); }); -
Customize form actions in django admin
I have followed this article on "How to Add Custom Action Buttons to Django Admin" https://medium.com/@hakibenita/how-to-add-custom-action-buttons-to-django-admin-8d266f5b0d41 and I have it almost working. I would like display fields that are pre-populated with values from my model. Here is what I have so far. From this page the user can click on the 'Approve' or 'Deny' buttons. The deny form is simple and looks like this: Here the user needs to type in a reason for denying and then can click the Submit button to execute custom code to process the denial. If the user clicks Approve I would like the user to have the ability to adjust some of the values in my Command model so I need to display those values in the form. So the form would look much like the standard django admin Change form but with just a Submit button that when clicked would update the model with user's changes and call my custom code to process the approval. So the Approval form would look something like this: But I cannot figure out how to get the values for nonroot_risk and nopasswd_risk from my model to display in the form. -
how to solve this: invalid literal for int() with base 10: 'B-A-BRS01' after importing data from a CSV file
to be extremely brief, i have a model called drilling, it contains 4 foreign key from 4 other model tables. when i imported data from a csv file to my drilling table using DB Browser for SQLite, the import is successful. when i now go to the drilling.html page, i am unable to load it. this is the error: ValueError at /project/ invalid literal for int() with base 10: 'B-A-BRS01' And they redirect me to where the error occured: 104 {{ drilling.project_name }} (that is in the drilling.html line 104) this is a portion of my drilling model: project_name = models.ForeignKey(Project) drill_date = models.DateField(default= '2000-01-01') shift = models.CharField(max_length = 1, choices = DRILLING_SHIFT) holes_drilled = models.IntegerField(blank = False, null = True) meters_drilled = models.DecimalField(blank = False, decimal_places=2, max_digits=10, null = True) avgdepth_drilled = models.DecimalField(blank = True, decimal_places=2, max_digits=10, null = True) targetmeters_drilled = models.CharField(max_length = 1, choices = TARGET_MET) comment = models.CharField(max_length = 220, blank = True, null = True) geologist = models.ForeignKey(Personel, related_name='Geologist') driller = models.ForeignKey(Personel, related_name='Driller') auger = models.ForeignKey(Auger) client = models.ForeignKey(Client) vehicle = models.ForeignKey(Vehicle) portion of personel model (one of the foreign keys field of drilling): class Personel(models.Model): personel_full_name = models.CharField(max_length = 220, blank = False, null … -
ValueError while deploying Scrapy
I am trying to deploy Scrapy with scrapyd-deploy command and now it throws next error: Packing version 1526919848 Deploying to project "first_scrapy" in http://my_ip:6800/addversion.json Server response (200): {"node_name": "polo", "message": "Traceback (most recent call last):\n File \"/usr/lib/python3.5/logging/config.py\", line 558, in configure\n handler = self.configure_handler(handlers[name])\n File \"/usr/lib/python3.5/logging/config.py\", line 731, in configure_handler\n result = factory(**kwargs)\n File \"/usr/lib/python3.5/logging/__init__.py\", line 1008, in __init__\n StreamHandler.__init__(self, self._open())\n File \"/usr/lib/python3.5/logging/__init__.py\", line 1037, in _open\n return open(self.baseFilename, self.mode, encoding=self.encoding)\nNotADirectoryError: [Errno 20] Not a directory: '/tmp/first_scrapy-1526919848-13w8cqlm.egg/debug.log'\n\nDuring handling of the above exception, another exception occurred:\n\n Traceback (most recent call last):\n File \"/usr/lib/python3.5/runpy.py\", line 184, in _run_module_as_main\n \"__main__\", mod_spec)\n File \"/usr/lib/python3.5/runpy.py\", line 85, in _run_code\n exec(code, run_globals)\n File \"/home/chiefir/lib/python3.5/site-packages/scrapyd/runner.py\", line 40, in <module>\n main()\n File \"/home/chiefir/lib/python3.5/site-packages/scrapyd/runner.py\", line 37, in main\n execute()\n File \"/home/chiefir/lib/python3.5/site-packages/scrapy/cmdline.py\", line 109, in execute\n settings = get_project_settings()\n File \"/home/chiefir/lib/python3.5/site-packages/scrapy/utils/project.py\", line 68, in get_project_settings\n settings.setmodule(settings_module_path, priority='project')\n File \"/home/chiefir/lib/python3.5/site-packages/scrapy/settings/__init__.py\", line 292, in setmodule\n module = import_module(module)\n File \"/home/chiefir/lib/python3.5/importlib/__init__.py\", line 126, in import_module\n return _bootstrap._gcd_import(name[level:], package, level)\n File \"<frozen importlib._bootstrap>\", line 986, in _gcd_import\n File \"<frozen importlib._bootstrap>\", line 969, in _find_and_load\n File \"<frozen importlib._bootstrap>\", line 958, in _find_and_load_unlocked\n File \"<frozen importlib._bootstrap>\", line 664, in _load_unlocked\n File \"<frozen importlib._bootstrap>\", line 634, in _load_backward_compatible\n File \"/tmp/first_scrapy-1526919848-13w8cqlm.egg/first_scrapy/settings.py\", line 25, in <module>\n File \"/home/chiefir/lib/python3.5/site-packages/django/__init__.py\", line … -
Django simple-history - track "Tags" field changes
Currently I am having a problem with storing history of tag addition/modification/deletion with the simple-history package Everything is working as expected, except for the fact that the "tags" field changes are not represented in the history changes. Trying to check any other instance in history shows the same tags everywhere, no matter when they were added or deleted - they are always there. class Task(models.Model): <... some fields ...> tags = TaggableManager() history = HistoricalRecords(inherit=True) I am stuck with the documentation for at least an hour or two and I'm, to be honest, really inexperienced with Python and Django in general. How can I make the history for tags work for me? -
How to handle an exception in Django moving from get() to filter()
original code with get() try: record = Record.objects.get(name__iexact=record_name) except Record.DoesNotExist: logging.debug("Error: Record does not exist") return Response({"Error": "Record does not exist"}, status=status.HTTP_404_NOT_FOUND) This query can return more than one record, so I am going to switch to this try: record = Record.objects.filter(name__iexact=record_name)[0] except Record.DoesNotExist: logging.debug("Error: Record does not exist") return Response({"Error": "Record does not exist"}, status=status.HTTP_404_NOT_FOUND) However, then my exception handling doesn't work. How do I make my exception catch if the query returns an empty list? -
How can I delete duplicates in a Python list
Please how can I delete duplicates in list. Example dup_list = ['he', 'he', 'sh', 'sh', ' jk', 'jk', 'gf', 'gf'] I want the new list to look like this. new_list = ['he', 'sh', ' jk', 'gf'] Please can some help me with this. -
Django Modelform - it is not validating, why?
I have a Django modelForm which I am trying to validate. The field is a 'custom' field - i.e it is not a field in the model, rather a combination of two fields that I want to parse and check if exists during cleaning. However the is_valid() form method is not working, it is saying valid=unknown when I print the form. I am using Django crispy forms Forms.py class SingleSampleForm(forms.ModelForm): sample_id = forms.CharField( required=True, label='Sample ID:') class Meta: model = Sample fields = ('sample_id',) def __init__(self, *args, **kwargs): super(SingleSampleForm, self).__init__() self.helper = FormHelper() self.helper.layout = Layout( Field('sample_id', # autocomplete='off', css_class="search-form-label", ), Submit('submit', 'Search sample', css_class='upload-btn') ) self.helper.form_method = 'POST' def clean_sample_id(self): self.sample_id = self.cleaned_data['sample_id'] print('CLEAN SAMPLE') try: ... parse self.sample_id and check if exists ... except Exception as e: return('Sample does not exist') Views.py: class SampleView(View): sample_form = SingleSampleForm def get(self, request, *args, **kwargs): sample_form = self.sample_form() self.context = { 'sample_form': sample_form, } return render(request, 'results/single_sample_search.html', self.context) def post(self, request, *args, **kwargs): sample_form = self.sample_form(request.POST) if sample_form.is_valid(): print('VALID') ... HttpRedirect()... else: print('NOT VALID') ... raise error ... self.context = { 'sample_form': sample_form, } return render(request, 'results/single_sample_search.html', self.context) every time I submit the form charfield and try to validate it, it … -
Django rest framework - upload images to Azure storage
django-storages and azure-storage 0.36(newer versions give loads of errors) installed in the virtualenvironment the upload seems to be working as the API sends a response with the supposedly correct link to the image. But on the Azure storage nothing is created. Just using the default file upload options, the file uploads work normally. Is using the django-storages backends the way to go or am I supposed to use the Azure python sdk directly? settings.py INSTALLED_APPS = ( .... 'storages' ) DEFAULT_FILE_STORAGE = 'storages.backends.azure_storage.AzureStorage' AZURE_ACCOUNT_NAME = "myaccountname" AZURE_ACCOUNT_KEY = "mykey" AZURE_CONTAINER = "media" MEDIA_ROOT = "http://mystorageaccount.blob.core.windows.net/" MEDIA_URL = "http://mystorageaccount.blob.core.windows.net/media/" models.py image = models.ImageField(upload_to='images', null=True, blank=True) With this setup it seems to be working -
How to use tree-multiselect.js with django
Hi everyone I've been trying to use https://github.com/patosai/tree-multiselect.js with django, It's working but the nested part I don't have any idea how to implement. thanks in advance but in the documentation say to use this, to make nested <option value="wow" data-section="top/inner/this/is/really/nested">Wow</option> this is my form <div class="container"> <div class="row"> <div class="card"> <div class="card-body"> <h2 class="text-center card-title">Informações Gerais</h2> <form method="post" enctype="multipart/form-data" novalidate> {% csrf_token %} {{ form|crispy }} <input class="btn btn-primary btn-block" type="submit" value="Update" /> </form> </div> <div class="card-footer"> </div> </div> </div> </div> <script> $("#id_knowledge_areas").treeMultiselect({searchable: true, searchParams: ['section', 'text']}); $("#id_application_area").treeMultiselect({searchable: true, searchParams: ['section', 'text']}); </script> -
Creating a group hierarchy in Django
I can't seem to figure out how to best implement a user model following this schema in Django: All are members, some are staff and must be part of a committee, where each committee has a leader I'm creating a custom admin interface for my use. I've extended the AbstractBaseUser class to create a new class User that represents all members, but there are some fields that are not relevant to members. class User(AbstractBaseUser): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) username = models.CharField(max_length=20, unique=True) date_joined = models.DateTimeField(auto_now_add=True) email = models.EmailField(max_length=100, default='') phone_number = models.CharField(default='', blank=True) balance = models.IntegerField(default=0) minimum_balance = models.IntegerField(default=0) status = models.CharField(choices=STATUS, default=STATUS_ACTIVE) committee = models.CharField(choices=COMMITTEE, default=COMMITTEE_1) objects = MyUserManager() USERNAME_FIELD = 'username' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'email',] def get_full_name(self): return "{0} {1}".format(self.first_name,self.last_name) def get_short_name(self): return self.first_name def __str__(self): return self.username These fields are not needed by a regular member: status = models.CharField(choices=STATUS, default=STATUS_ACTIVE) committee = models.CharField(choices=COMMITTEE, default=COMMITTEE_1) Should these fields be included in the User class and be part of a Group, or should they be somewhere else? How can a leader of a committee be represented in this Django model? Also, is there a better way to implement a hierarchy of users like … -
Reading bytes "string" filename into pandas read_csv()
I am using Django and Pandas to try to request the info for the currently authenticated user, and in turn use that data to read in a corresponding csv file into a DataFrame. def clientarea(request): users = {1:"admin", 2:"rgoulding",3:"ladams"} if request.user.is_authenticated: current_user = users[request.user.id] df = pd.read_csv(current_user+".csv") return render(request, 'strategies/clientarea.html',context={}) else: return render(request, 'strategies/home.html',context={}) I am getting the error message: File b'ladams.csv' does not exist When I print "[request.user.id]" I get 3 and when I check the type I get "int". I am confused as to why a simple dictionary lookup with an int of "3" would change the string "ladams" into a bytes object and add the "b" before the string. I have tried numerous ways to decode the bytes object that seems to be returned: str = current_user.decode() sand have also tried: str(current_user, 'utf-8') but I get the error message: 'str' object has no attribute 'decode' or: decoding str is not supported So it seems to think it's already a string, which seems to be correct - but then why is it showing up as "b'ladams' when passed to the read_csv() function? -
How do I delete a single instance of an intermediate model in a Django Many-to-many (through) relationship?
This is a M2M relationship, that has the intermediate model 'Membership' (the intermediate model stores extra information about the relationship between a student and a course, using the 'through' keyword). In my case the extra relationship is the grade a student has in each of his courses. MY PROBLEM IS: I can't find a way in django to delete/remove only one of the relationships between one of the courses and the grade the student has. class Student(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Course(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Student, through='Membership') def __str__(self): return self.name class Membership(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) group = models.ForeignKey(Course, on_delete=models.CASCADE) grade = models.CharField(max_length=64) Since 'Membership' is an intermediate model, it disables the remove(), that would be accesible in a normal ManyToMany relationship. You can use the clear() method, but his would remove every grade the student has in a course relationship. For example: If 'Carlos' was in 5 different courses with 5 different grades for each course, and also some other student 'Maria' c = Course c.members.clear() would clear every grade relationship. You can see another example in the docs: https://docs.djangoproject.com/en/2.0/topics/db/models/#extra-fields-on-many-to-many-relationships And if I try to use the remove() method I get an … -
Django model A field default to value of model B field
I have two models, let's say one is Account and the other is AccountMember. There is a certain permission I want to give, for example "Can unlock door". This permission can be set on the Account and on AccountMember (for an individual membership). What I'm trying to achieve is to have AccountMember inherit from Account's "Can unlock door" permission. My initial solution was to create a signal on AccountMember that sets the permission to match Account after creation. This caused some confusion because people wanted to be able to set the permission when creating the AccountMember, not after. So I have two questions, 1. Why can't I have the default value for AccountMember "can unlock" be set to reference Account's "can unlock"? 2. Is there a better way to do this than to have a post save signal? For example, this is what I would like to do... class Account(models.Model): can_unlock = models.BooleanField(default=False) class AccountMember(models.Model): can_unlock = models.BooleanField(default=Account.can_unlock)