Dynamic setting of field values in Django based on the values of other fields

My goal is to automatically set a default value for a field in Django based on the selection of another field. In this case, the field that needs the default value is linked to a foreign key.

class Product(models.Model):
        description = models.CharField('Description', max_length=200)
        price = models.FloatField('Price')

class Sell(models.Model):
        product = models.ForeignKey(Product)
        price = models.FloatField('Price')

Each "Product" has a default price or suggested price stored in the database. When a user wants to add a new sell entry in the Admin pages and selects a specific product, I need to dynamically copy the suggested price from the corresponding Product entry to the Sell entry's price field. However, I can't depend on the standard save method as the user might make changes during the process.

Is there an elegant way within Django to achieve this functionality without explicitly resorting to JavaScript?

Answer №1

To handle this situation, you have options like implementing a pre-save hook or overriding the save() method of the Sell model.

from django.db import models

class Product(models.Model):
    description = models.CharField('Description', max_length=200)
    price = models.FloatField('Price')

class Sell(models.Model):
    product = models.ForeignKey(Product)
    price = models.FloatField('Price')

    # Approach 1:
    from django.db.models.signals import post_save
    def default_subject(sender, instance, using):
        instance.price = instance.product.price
    pre_save.connect(default_subject, sender=Sell)

    # Approach 2:
    def save(self, *args, **kwargs):
        self.price = self.product.price
        super(Sell, self).save(*args, **kwargs)

Answer №2

If you're wondering how to update form field values dynamically on the Admin webpage, it will require client-side scripting with JavaScript. While Django's Admin does offer some scripts for tasks like adding or removing Inlines, it doesn't provide functionality at a deeper level.

In the context of Django's Admin, jQuery can be accessed through window.django.jQuery (or simply django.jQuery). The form field IDs generated by Django Forms remain stable in the output code. By identifying the Product selector and the Sell.price input field in the form code, you can utilize jQuery to create an event handler such as .change() or .on('change', ...) to automatically update the price when the Product selection changes.

In terms of enhancing this functionality in Django Admin, there is a feature called ModelAdmin.prepopulated_fields. However, it's important to note that prepopulated_fields does not support DateTimeField, ForeignKey, or ManyToManyField fields.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

python continue looping until the depth in django is determined

In my Django project, I have a unique Custom User model where users report to each other in a hierarchical structure. Each user reports to another user until the top-level user does not report to anyone else. The tasks assigned to the lowest level user sho ...

Pinchin opts for alternative methods over utilizing the Hammer library for calls

After downloading Hammers.js version-1.0.10, I have been trying to call the 'pinch in' function from the JavaScript file but it is not executing. I suspect there may be a problem with the library as I have tried downloading another one, but the s ...

How can I place the current date inside a red dashed box with text using JavaScript?

Let's Solve This: The date currently appears in the top left corner without any special formatting. My goal is to make it bold, red, and encased in a dashed-red border. I have identified the element by its ID "datetext", corresponding to a "p" tag w ...

Incorporating elements with wrapping capabilities in ExtJS

I'm puzzled by what should be a straightforward issue. I am trying to place items (buttons, specifically) on a panel so that they are displayed side-by-side and wrap once they reach the end of the panel... Appreciate any insights, JJ ...

The Django formview encounters an error stating that the form_valid method does not have the 'instance' attribute

Currently, I am in the process of creating a form view by utilizing the FormView class. Everything seems to be working perfectly when displaying the post form. However, upon posting the data, an error occurs when the form_valid function is called: Attribu ...

Angular allows for the dynamic inclusion and exclusion of components, providing a flexible

In my setup, I have a container that houses two distinct components. The first component receives a list of users from the backend. Upon clicking on a specific user, I aim to display all of their detailed information in the main container of the second co ...

Tips for combining values with Reactive Forms

Is there a way to merge two values into a single label using Reactive Forms without utilizing ngModel binding? <label id="identificationCode" name="identificationCode" formControlName="lb ...

Locate items within a collection using Django and mongodb

Although I am familiar with django, I am relatively new to mongodb. Below is the model I am working with: class Conversation(models.Model): date = models.DateTimeField(auto_now_add=True, db_index=True) users = ListField(models.CharField(max_length ...

Discovering the method to retrieve a previous month's date within a VueJs application using Javascript

Can someone guide me on how to retrieve the date of the past month using Vue? This is the code I currently have: import SomeTable from "./table/SomeTable"; export default { name: "Cabinets", components: {SomeTable}, data() { return { ...

How can I extract and display a particular attribute from an object in a list retrieved through AJAX?

I am currently working on an AJAX call that retrieves a list of objects in JSON format from a database. These objects are then used in an autocomplete text input. However, my challenge is to display only the NAME attribute of each object in the list. $(fu ...

Performing an API GET request in a header.ejs file using Node.js

Looking to fetch data from an endpoint for a header.ejs file that will be displayed on all routed files ("/", "/news" "/dogs"). Below is my app.js code: // GET API REQUEST var url = 'https://url.tld/api/'; request(url, function (error, response, ...

Laravel validation successfully validates Vanilla AJAX request, but the controller does not receive the values

Currently, I am utilizing AJAX (vanilla JS) to send a form to a Laravel 5.5 controller for searching the Amazon products API. The AJAX is sending the correct keywords and category inputs, but the controller is not receiving them. Even though the request p ...

Express server fails to receive data from jQuery AJAX post request

I am attempting to send form data to my Express app.js without the page refreshing. I believed I had the correct code, but when trying to retrieve the data from the AJAX call on the server side, I encounter an undefined data variable. app.js: (relevant li ...

"Graphs not Displaying Properly in ChartJs

Seeking assistance with rendering a chart inside a bootstrap popover. Despite various debugging attempts, the chart refuses to render. Any help or insight would be greatly appreciated. Below is my HTML code: <div id="popover-content" style=&qu ...

The method OnJSAlert in WebChromeClient is failing to execute

I am currently working with a JS script in a WebView, where the script triggers an alert message to the WebView that I want to capture in my app. However, I am facing an issue where the onJSAlert method is not being called and I am unable to use the @Overr ...

Using jQuery to submit a form via ajax and retrieve values from a datepicker and button

Currently, I am in the process of configuring my ajax form to display an alert box when it either succeeds or fails. The form includes options for two different boxes, a datepicker, email address input, and phone number input. My main query is regarding ho ...

An exploration of effortlessly moving elements using webdriver.io - the power of

I have been attempting to utilize the drag and drop method in WebDriver.io, but I am encountering issues. I followed the example for drag & drop on this website: https://www.w3schools.com/html/html5_draganddrop.asp. This functionality is essential for ...

javascript/typescript - conditionally adding an item to an object

If I have an object called userData = {..} and I need to create another object, userDataB, with properties a, b, c, and d from userData but only if they are defined. One way to achieve this is by using the following approach: userDataB = {} if(userData.a ...

The date error from day.js in Firefox is not valid

My date is formatted as 2022-01-27 09:23:48 UTC and I am trying to parse it into MMMM-DD-YYYY format (Jan-27-2022) using day.js. The parsing works well in Chrome, but Firefox returns an 'Invalid' result. import dayjs from "dayjs" const ...

Slider functionality is no longer operational

After running smoothly for two and a half years, the slider on our website suddenly stopped working in Chrome today. This same slider is used across multiple pages, but now it fails to function on any of them. For those with a retina screen, there is an a ...