Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
OperationalError at Django + Apache + wsgi Read-only file system
I deployed my code with django 1.6.11 and wsgi. My website was up and running and suddenly below error popped up. I did sync and initialize my db and changed the permissions but still not able to resolve this error. Any inputs? OperationalError at / FATAL: could not open file "base/16386/12805": Read-only file system Request Method: GET Request URL: http://starcast.com/ Django Version: 1.6.11 Exception Type: OperationalError Exception Value: FATAL: could not open file "base/16386/12805": Read-only file system Exception Location: /var/lib/jenkins/workspace/starcast_prod/venv/lib/python2.7/site- packages/psycopg2/init.py in connect, line 130 Python Executable: /usr/bin/python Python Version: 2.7.13 Python Path: ['/var/lib/jenkins/workspace/starcast_prod/starcast', '/var/lib/jenkins/workspace/starcast_prod/venv/lib/python2.7/site-packages', '/usr/local/lib/python27.zip', '/usr/local/lib/python2.7', '/usr/local/lib/python2.7/plat-linux2', '/usr/local/lib/python2.7/lib-tk', '/usr/local/lib/python2.7/lib-old', '/usr/local/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/site-packages'] Server time: Tue, 23 May 2017 17:58:50 -0500 -
Django filtering based on login details
I am building a web app that lists courses. I can filter courses based on location and category. However, the next step is to allow users to login and assign courses to their profile. Where I am struggling is filtering courses based on the login credentials. Can it even be done? I cannot find anything on it and I have been searching for days. I'll start with the course provider. A dashboard that filters the course where the login has a foreign key course (there are multiple courses per organisation): class ProviderProfile(models.Model): organisation = models.ForeignKey(Provider) username = models.ForeignKey(User) firstname = models.CharField(max_length=200) lastname = models.CharField(max_length=200) email = models.EmailField(max_length=200) Once the user a logged in and clicked on the dashboard view, I would like it to return all the courses associated with the organisation attached to the ProviderProfile. The course model has the following in the model: provider = models.ForeignKey(Provider). Below is an example of how I am filtering courses in other views like this: class Courses_By_Location(LoginRequiredMixin, ListView): template_name = 'courses/course_list.html' model = models.Course context_object_name = 'courses' def dispatch(self, request, *args, **kwargs): self.location = kwargs.get('location', 'DEFAULT-LOCATION') return super().dispatch(request, *args, **kwargs) def get_queryset(self): return date_screen( super().get_queryset().filter(location__gen_local__iexact= self.location).order_by('date'), ) raw_courses = date_screen(models.Course.objects.all()) def get_context_data(self, … -
Celery task state switching from progress to pending and back to progress
My code was working as desired while testing until it hit the production server. The celery task state which is set by update_state is changing from PENDING to PROGRESS and back to PENDING erratically. When it returns to the PROGRESS state its back how it should be. I tested in the django shell and the task.state is as it should be and completely stable. Is there a reason it would be erratic like this only in the browser?? Again while testing I'm not having this issue at all. I'm trying to sort out any config issues there might be but within the app at least its consistent from what I have seen thus far. CELERY_ACCEPT_CONTENT = ['pickle', 'json', ] # CELERY_ENABLE_UTC = False CELERY_RESULT_BACKEND = 'rpc://' CELERY_RESULT_PERSISTENT = True CELERY_RESULT_SERIALIZER = 'pickle' CELERY_TASK_RESULT_EXPIRES = None # no result is return back Unfortunately this is a proprietary project so providing working code isn't an option. I'm hoping someone else has perhaps ran into this oddity. -
Migrate from one django model to two models referenced with a foreign key
I need to outsource some of the attribues in the following Django model: class TextResult(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) text = models.ForeignKey(Text) # following fields will be in the referenced model wpm = models.FloatField(default=0.0) accuracy = models.FloatField(default=1.0, validators=[MinValueValidator(0.0), MaxValueValidator(1.0)]) to a model, that references to the specific data: class TextResult(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) text = models.ForeignKey(Text) typing_result = models.ForeignKey(TypingResult) class TypingResult(models.Model): wpm = models.FloatField(default=0.0) accuracy = models.FloatField(default=1.0, validators=[MinValueValidator(0.0), MaxValueValidator(1.0)]) The problem is, that there is already some data in the database, so I have to migrate the data to the new structure, what is the easiest, cleanest way to achieve that? -
django-imgur api manage.py get_imgur_token not working
I am using the django imgur api here https://github.com/spekzz/django-imgur. I am going through the set up it says to, but when I try to run python manage.py get_imgur_token, I get this error. PS C:\Users\Bright Bridge\Desktop\SuperYachtingit> python manage.py get_imgur_token WARNING Sass integration not enabled. Traceback (most recent call last): File "manage.py", line 19, in <module> execute_from_command_line(sys.argv) File "C:\Users\Bright Bridge\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\management\__init__. py", line 353, in execute_from_command_line utility.execute() File "C:\Users\Bright Bridge\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\management\__init__. py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Bright Bridge\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\management\__init__. py", line 195, in fetch_command klass = load_command_class(app_name, subcommand) File "C:\Users\Bright Bridge\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\management\__init__. py", line 39, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "C:\Users\Bright Bridge\AppData\Local\Programs\Python\Python35\lib\importlib\__init__.py", line 126, in import_mo dule return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 661, in exec_module File "<frozen importlib._bootstrap_external>", line 767, in get_code File "<frozen importlib._bootstrap_external>", line 727, in source_to_code File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "c:\users\bright bridge\desktop\superyachtingit\src\django-imgur\django_imgur\management\commands\get_imgur_token .py", line 13 print "Url:", url I have the IMGUR_CONSUMER_ID, the IMGUR_CONSUMER_SECRET, and the IMGUR_USERNAME. How can I get the imgur_token using django-imgur? As a side note, using the regular … -
How to freeze display columns after selecting specific columns using DisplayFieldsSettingsAdmin..?
from admin_display_fields_settings.admin import DisplayFieldsSettingsAdmin class VendorAdmin(DisplayFieldsSettingsAdmin): list_display=['vendor_id','vendor_name','deleted','date_created'] admin.site.register(Vendor,VendorAdmin) Columns are displayed in a different order..! -
Pass data from a signal to another
I have 2 signals, pre_save and post_save. When Post_Save execute I will need the variable R existing in pre_save for post_save, how could I do that ? @receiver(pre_save, sender=Student) def student_pre_save(sender, instance, **kwargs): R = ClassRoom.objects.get(pk=instance.ClassRoom.pk) @receiver(post_save, sender=Student) def student_post_save(sender, instance, **kwargs): t = ClassRoom.objects.get(pk=instance.ClassRoom.pk) t.qtt_current_students = instance.ClassRoom.student_set.count() t.save() -
Django: NoReverseMatch at /users/password-change
I'm trying to implement Django's built-in auth views but it's not working. In my app's urls.py I have: from django.conf.urls import url from django.contrib.auth.views import password_change, password_change_done from . import views urlpatterns = [ url(r'^$', views.login_view, name='home'), url(r'^login/$', views.login_view, name='login'), url(r'^password-change/$', password_change, name='password_change'), url(r'^password-change/done/$', password_change_done, name='password_change_done'), ] and in my main project's urls.py I have: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^users/', include('users.urls', namespace="users")), ] When I try to visit http://127.0.0.1:8000/users/password-change/, I get: NoReverseMatch at /users/password-change/ Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name. -
Django Rest Frameworks, Nested many to many serialization
I'm new to using DRF. I have a 2 layered many-to-many relationship I would like to be able to serve up. # models.py class Person(models.Model): name = models.CharField(max_length=32) class Group(models.Model): name = models.CharField(max_length=32) people = models.ManyToManyField(Person,related_name='groups',blank=True) class Event(models.Model): name = models.CharField(max_length=32) groups = models.ManyToManyField(Group,related_name='events',blank=True) In my serializer I would like to be able to show in Person, which event they are attending. class PersonSerializer(serializers.ModelSerializer): groups = serializers.StringRelatedField(many=True) #not sure how to lookup the events related field here... events = EventSerializer(source='groups.name', many=True,read_only=True) class Meta: model = Person fields = ( 'id', 'name', 'groups', 'events') However, I'm getting an error when I look up events. Is this lookup even possible? Currently the output looks like this, I have groups mapped to events "party" but it says 'null': { "id": 1, "name": "mike", "groups": [ "dev" ], "events": null } I'd would like the output to be a list of events. Like this: { "id": 1, "name": "mike", "groups": [ "dev" ], "events": [ "party" ] } -
Django form: How to filter ModelChoiceField after initilizaiton?
Wanted functionality: User can select from brands only they created, or create a new one. Right now, my BottleForm is showing all brands added by all users. Relevant snippet from view.py: form = BottleForm() if user.is_authenticated: test_var = Brand.objects.filter(business__owner=user).all() form['brand'].queryset = test_var # trying to re-set the brand field args['form'] = form args['form2'] = BrandForm() return render(request, template_name="index.pug", context=args) My ModelForm in forms.py: class BottleForm(ModelForm): capacity = forms.IntegerField(initial=750, max_value=2000, min_value=50) class Meta: model = Bottle fields = "__all__" -
django-mptt OperationalError no such column
I've installed django-mptt and django-mptt-admin. When trying to add a item via admin i get: OperationalError at /admin/item/item/add/ Exception Value: no such column: item_item.lft I belive this has to do with the tables is not created. But I added both mptt and mptt-admin in installed_apps in settings.py INSTALLED_APPS = [ 'mptt', 'django_mptt_admin', I have also run the migrations in the terminal. python manage.py makemigrations <app_name> python manage.py migrate I have also tried python manage.py migrate --run-syncdb and get this Operations to perform: Synchronize unmigrated apps: django_mptt_admin, messages, mptt, staticfiles Apply all migrations: admin, auth, contenttypes, item, sessions Synchronizing apps without migrations: Creating tables... Running deferred SQL... Running migrations: No migrations to apply. Now I'm out of ideas to solve this -
Using the Django sites framework in the Django admin
I'm implementing a solution using the Django sites framework for the first time, and am not sure whether there is a better way of implementing it on the Django admin. Currently I have it working on the frontend, but I want users to be restricted to only manage the content on the backend that belongs to 'their' site (each user is assigned to a site). To do this currently, I'm splitting the fields available to a superuser (is_superuser) and anyone else by specifying the respective fields in the Admin class. I'm then overriding the following: The get_form method to return a different form depending on the user. For instance, a superuser can create content for any site, whereas any other user can only create content for their own site. def get_form(self, request, obj=None, **kwargs): if request.user.is_superuser: self.fieldsets = self.user_fieldsets + self.superuser_fieldsets else: self.fieldsets = self.user_fieldsets return super(FaqCategoryAdmin, self).get_form(request, obj, **kwargs) The get_queryset method, to only show the relevant entries for the site the user has access to. def get_queryset(self, request): qs = super(FaqCategoryAdmin, self).get_queryset(request) if request.user.is_superuser: return qs else: return qs.filter(site=settings.SITE_ID) The save_model to ensure if a non-superuser saves a new entry, that it defaults to their site: def save_model(self, … -
Django admin panel new action intermediate page
I added to admin panel new action with redirection to intermediate page. But my problem is that I don't know where to put the template of intermediate page. No matter where I put it, I get 404 error. So my question is where should I put the template of my intermediate page. (what should be it's exactly path) -
Porting (postgresql) SQL into django model classes
I am porting a database schema (by hand), from (postgresql) SQL to django (1.10) model. Here is my SQL: CREATE TABLE ref_continent ( id SERIAL PRIMARY KEY, name VARCHAR(64) ); CREATE UNIQUE INDEX idxu_continent_nm ON ref_continent (name); CREATE TABLE ref_geographic_region ( id SERIAL PRIMARY KEY, continent_id INTEGER REFERENCES ref_continent(id) ON DELETE RESTRICT ON UPDATE CASCADE, name VARCHAR(256) ); CREATE UNIQUE INDEX idxu_geogreg_nm ON ref_geographic_region (name); I am particularly interested in how to create the UNIQUE INDEX and how to link the FK to the PKey, since (AFAIK), django creates the primary key id behind the scenes? -
Django : aggregation down to specific level after annotation() & value()
I'm trying to aggregate values down to a specific level with Django, but it does not seem straighforward : aggregation occurs at the full queryset or at the entry level, but not 'in-between'. Here is my query : I need to compute a total activity time by year from multiple event entries. events = events.annotate( # Extracting the year year = ExtractYear('dtstart') ).annotate( # Computing duration... time_span= ExpressionWrapper( F('dtend') - F('dtstart'), output_field=IntegerField() ) ).values( # ... then aggregating by year 'year', 'time_span' #!!!! ... BUT ALSO unfortunately # by 'time_span' !!!!!!!!!!!!!!! ).annotate( # otherwise 'time_span' would not total_span=Sum('time_span') # be available for a new computation. ).values( # Therefore, the result is not 'year', 'total_span' # grouped by year, but by the ).order_by( # distinct combination of 'year' 'year' # AND 'total_span' ) As a consequence, I get this result : <QuerySet [ {'total_span': 1800000000, 'year': 2016}, {'total_span': 7200000000, 'year': 2016}, {'total_span': 2700000000, 'year': 2016}, {'total_span': 14400000000, 'year': 2016}, {'total_span': 8100000000, 'year': 2017}, ...> instead of something like this : <QuerySet [ {'total_span': 1800000000, 'year': 2016}, {'total_span': 7200000000, 'year': 2017}, ...> In order to set the aggregation level, I would need something like : aggregate(total_span=Sum('time_span'), group_by=['year']) I guess I should turn … -
After deploy to PythonAnyWhere get NoReverseMatch error
i'm trying the djangoGirls tutorial, and after doing the Extend Your Application, my site works just fine at local, on the http://127.0.0.1:8000/. But when i pull to the PythonAnyWhere and try to acess the site, i got the error NoReverseMatch, like the picture below: NoReverseMatch Error So i want to know if anyone have a idea of what i can do to solve the problem, because i try and can't do it. I have no idea how to make it work. All my codes are similar to the tutorial, here they : urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.post_list), url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail), ] views.py from django.shortcuts import render, get_object_or_404 from django.utils import timezone from .models import Post # Create your views here. def post_list(request): posts = Post.objects.filter(published_date__lte = timezone.now()).order_by('published_date') return render(request, 'blog/post_lists.html', {'posts': posts}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) models.py: from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length = 200) text = 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.title base.html {% load … -
Django Postgers Replace Function
I want to find all strings, but discard unwanted characters. I have the following rows: test! t!est !t!e!st! aaa! I want to find all test(but remove all unwanted characters). From above table I want to get test! t!est !t!e!st! Table.objects.filter(name=test_or_test_with some_unwanted_symbols). I don't know how to apply Django F and Func here. -
Do I use a Wagtail form or a Django one?
I want to add a simple form to my Wagtail site, which will enable some users (with suitable permissions perhaps) to create a new page, outlining a game scenario. Just a title field and a rich-text field in other words. Now I have read the docs at http://docs.wagtail.io/en/v1.10.1/reference/contrib/forms, which is close to what I need, except that the AbstractForm class or the like appears to be geared towards letting users design their own forms, which I do not want them to do. So the alternative is to use a standard Django form, as per the 'example' given at https://github.com/gasman/wagtail-form-example/commits/master. However I do not find that to be useful. So my question is this: do I use a Wagtail form which (I presume) has the 'correct' page-handling code, or I do I somehow shoe-horn a Django form into my Wagtail site and hope that it integates well with the Wagtail stuff? Alternatively, can I simply use the Wagtail form and prohibit users from modifying it? -
I have written django tests something like this. Is this the correct test?
I have written django tests something like this. Is this the correct test? class DaterManagerTests(TestCase): def setUp(self): self.user = User.objects.create_user('ali','ali@gmail.com', '123456') """ Make sure that DaterProfile active method works. """ def test_dater_profile_manager_active(self): DaterProfile.objects.create(user=self.user) #Created object self.assertQuerysetEqual( DaterProfile.objects.active(), map(repr, DaterProfile.objects.filter(user__is_active=True)), ordered=False ) -
Does uploading files causes Django server to be unresponsive for other users?
So as I understood Django framework and python language are synchronous which means things are processed sequentially and only one user can be served at each particular moment. In that case what happens when a single user tries to upload relatively large file to server. Does the whole web-app become unresponsive for everyone else? What is the right way to do the file upload in Python anyways? -
Loop through queries of different length
I'm using zip to loop through the results of two queries simultaneously. However in some cases the results are not of equal length. In those cases I want to set the values of the query that ends first to 0. It is always the occupancy_agency that ends first as it is a subset of the first query. Specifically it is occupancy_agency_y['supply'] and occupancy_agency_y['available']. I've tried to come up with a solution but couldn't figure out how to combine it with zip that allows me to loop through both results at the same time. def occupancy_data(area_id, description, period, agency_id): occupancy = Occupancy.objects.filter(description=description) \ .values('start_date') \ .annotate(supply_total=Sum('supply')) \ .annotate(available_total=Sum('available')) \ .order_by('start_date') occupancy_agency = Occupancy.objects.filter(description=description, agency_id=agency_id) \ .values('start_date',) \ .annotate(supply=Sum('supply')) \ .annotate(available=Sum('available')) \ .order_by('start_date') x = [] _input = occupancy.values('start_date') for row in _input: x.append("Uge " + str(int(row['start_date'].strftime("%V")))) y = [] for occupancy_y, occupancy_agency_y in zip(occupancy, occupancy_agency): comp_supply = (occupancy_y['supply_total'] - occupancy_agency_y['supply']) comp_available = (occupancy_y['available_total'] - occupancy_agency_y['available']) occupancy_combined = ((comp_supply - comp_available) / comp_supply) y.append(occupancy_combined) return {'x': x, 'y': y} -
Django cannot find ajax static file
Im using Python and Django. I have tried to implement a simple ajax call, however the function never gets called. I am assuming that the static js file cannot be located and hence the event is never triggered. There is no log error either Any help would be appreciated. Sorry folder structure pic does not want to upload but basically sProduct\ myapp\ sproduct\ manage.py static\ js\ jquery-3.2.1.min.js myapp-ajax.js settings.py STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '2exl1&c-4p9g2(8!h)si1g7ilvidk&31fg%@nlkp)^32k1d28g' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True #LOGGING_CONFIG = None #LOGGING = {"INFO"} #import logging.config #logging.config.dictConfig(LOGGING) ALLOWED_HOSTS = [] STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Application definition ENVIRONMENT = "dev" INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', 'markdown_deux', 'django_tables2', 'django_tables2_simplefilter', ] index.html (base file) <script type="text/javascript" src="{{ STATIC_URL }} /static/jquery-3.2.1.min.js"> </script> <script type="text/javascript" src="{{ STATIC_URL }} /static/myapp-ajax.js"> </script> myapp-ajax.js $('#qty_id').change(function(){ var catid; qid = $(this).attr("data-quoteid"); $.get('/calcTotalPrice/', {quote_id: "2"}, function(data){ $('#total').html(data); }); }); $('#price_id').change(function(){ var catid; qid = $(this).attr("data-quoteid"); $.get('/calcTotalPrice/', {quote_id: … -
How create several elements in D3.js?
In my django project I have 3 connected with each other models. GROUP -> TASK -> FUNCTION. I am tring to create tree with the help of D3.js library. The problem is my current code show me only first element of Group model. How to show other elements? Is it possible in D3.js? models.py: class Group(models.Model): name = models.CharField(_('Name'), max_length=250) class Task(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) name = models.CharField(_('Name'), max_length=250) class Function(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE) name = models.CharField(_('Name'), max_length=250) template: var treeData = [ {% for group in groups %} { "name": "{{ group }}", "parent": "null", "children": [ {% for task in group.task_set.all %} { "name": "{{ task }}", "parent": "{{ group }}", "children": [ {% for function in task.function_set.all %} { "name": "{{ function }}", "parent": "{{ task }}" }{% if not forloop.last %},{% endif %} {% endfor %} ] }{% if not forloop.last %},{% endif %} {% endfor %} ] }{% if not forloop.last %},{% endif %} {% endfor %} ]; -
How do I auto-create model classes with relational attributes from json data for django?
I have a bunch of json data files that I need to put into my database for django, and for the project I'm working on, I need all of the nested dictionaries/lists to be converted into nested django models. All of the json files follow a similar structure, but are not the same, and are quite large. Doing it manually isn't an option. I've seen some examples on how to do this for python objects, but I'm not sure how to implement those solutions for django models. There's an example of one of the json files here: https://github.com/JAMeador13/the-se7en-clan-stats/blob/master/example.txt Ideally, I would like to generate all of these models following a format similar to this: (from the example) class Data(models.Model): # PGCR is just the model that each of the json files is stored in PGCR = models.ForeignKey(PGCR, related_name='data') # fieldname would be the key for that dictionary fieldName = models.CharField(max_length=30) def __str__(self): return fieldname class ActivityDetails(models.Model): data = models.ForeignKey(data, related_name='activityDetails') fieldname = models.CharField(max_length=30) # keys/values in the dictionary... activityTypeHashOverride = models.CharField(max_length=30) etc... def __str__(self): return fieldName I'm using django 1.11, python 3.6, and sqlite3 for my database. Any help would be greatly appreciated! -
Django Admin autofill data from ForeignKey select
I'm looking for a way to autofill some fields in the admin, based on a selected field. I have a foreign key field in an Inline and want to show some data from the current selected object in the form in realtime. A simplified version of my code to exemplify what I'm doing would be: # models.py class Product(models.Model): code = models.CharField(max_length=6, default=0) name = models.CharField(max_length=25, null=True, blank=True) class Provider(models.Model): code = models.CharField(max_length=6, default=0) name = models.CharField(max_length=25, null=True, blank=True) address = models.CharField(max_length=25, null=True, blank=True) class ProductProvider(models.Model): product = models.ForeignKey(Product) provider = models.ForeignKey(Provider) cost = models.DecimalField(max_digits=6, decimal_places=2, default=0) And my admin class is as follows: # admin.py class ProductProviderInline(admin.TabularInline): model = ProductProvider fk_name = 'product' fields = ('provider', 'cost', 'provider_address') readonly_fields = ('provider_address',) extra = 1 def provider_address(self, obj): return obj.provider.address @admin.register(Product) class ProductAdmin(admin.ModelAdmin): model = Product list_display = ('code', 'name') inlines = [ProductProviderInline] @admin.register(Provider) class ProviderAdmin(admin.ModelAdmin): model = Provider In this example, once a Provider have been selected, I'd like to update the readonly field address without having to save the object just yet. I've tried most of the "autocomplete" third-party applications, sadly for me, most of them focus on autocomplete Choice fields, and not autofilling forms based on a …