Value auto-populated from associated model

Currently, I have a situation where I have a table for zip codes and another table for persons. The goal is to automatically populate the city field in the person's table based on the zip code entered. It seems like this functionality may not be achievable with Django alone, and I might need to explore jQuery, Ajax, or JavaScript for a solution.

Here are the model definitions in models.py:

from django.db import models

class Zip(models.Model):
    zipcode = models.IntegerField()
    city = models.CharField(max_length=200)

    def __str__(self):
        return str(self.zipcode)

class Person(models.Model):
    name = models.CharField(max_length=200)
    zipcode =  models.ForeignKey('Zip',on_delete=models.CASCADE,related_name="zip_of_this_person")  
    personcity = models.CharField(max_length=200)
    def __str__(self):
        return self.name

Below are the form definitions in forms.py:

from django import forms 
from .models import Zip, Person

class ZipForm(forms.ModelForm):
    class Meta:
        model = Zip
        fields = ('zipcode', 'city',)
        


class PersonForm(forms.ModelForm):
    class Meta:
        model = Person
        fields = ('name', 'zipcode', 'personcity' )

Here is the content of views.py where the form handling and rendering is defined:

from django.shortcuts import render, redirect, get_object_or_404
from .forms import PersonForm, ZipForm
from .models import Zip, Person

# Relevant view functions are defined here

Lastly, the HTML template:

{% extends 'theapp/base/base.html' %}
{% load static %}

{% block title %}Title Tab{% endblock %}

{% block site_css %}{% endblock %}
{% block main_heading %}{% endblock %}   

{% block header_content %}{% endblock %}

{% block body %}
<section>
    <h2>Person</h2>
</section>

<article class="post">
    <h2>Name:{{ post.name }}</h2>
    <p>Zip/city:{{ post.zipcode }}{{ post.personcity }}</p>

        
</article>
{% endblock %}

I have done extensive research but haven't found a clear solution. It seems to be a challenge especially since displaying all related data is simpler. This might be a frontend issue rather than a Django-specific one, despite using a relational database. Any guidance on this matter would be greatly appreciated.

Answer №1

If you want to allow null and blank values in the personcity field and then fill it when the model is saved, you can take the easy route and modify the .save() method like so:

class Person(models.Model):
    name = models.CharField(max_length=200)
    zipcode =  models.ForeignKey('Zip',on_delete=models.CASCADE,related_name="zip_of_this_person")  
    personcity = models.CharField(max_length=200, null=True, blank=True)
    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if not self.personcity and self.zipcode and self.zipcode.city:
            self.personcity = self.zipcode.personcity
        super(Person, self).save(*args, **kwargs)

Alternatively, you can achieve this using a pre_save signal

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

Developing a personalized error message pop-up system in Electron

I am currently in the process of developing an application for file backup, which involves a lot of reading and writing to the filesystem. While most parts of the app are functioning well, I am facing some challenges with error handling. In the image belo ...

What is the best way to pass a boolean value from a Java class to ajax?

I am facing an issue in my Java class where I want to return a boolean value to the Ajax request but getting an error message indicating "unknown return value type." The ajax successfully passes the value to the java method, but there seems to be a problem ...

Updating NPM yields no changes

Having trouble updating dependencies in a subfolder of my MERN stack app. Specifically, I am trying to update the dependencies in the client folder where the React code is located. However, when I attempt to update the dependencies in the client folder, it ...

Is there a C++ equivalent to the JS Array.prototype.map method?

When it comes to JavaScript, Array.prototype.map is a powerful tool for creating a new array by applying a function to each element. Consider the following example: const elements = [{ text: 'hi1' }, { text: 'hi2' }, { text: 'hihi ...

Design a custom screensaver using jQuery that includes a timed delay feature and an alert message

I am currently working on implementing a screensaver feature for my website. Here is the breakdown of what I am trying to achieve: When detecting the onload, clicks, and touches, I want to start a timer that counts 5 seconds. If any of these events are d ...

Master the Art of Modifying a Row in Datatable with .NET Core

I am having trouble updating a row in my datatable using .net core. The datatable display the data correctly and the new/delete buttons are working. However, when I try to edit a row, it is not functioning properly. Below is my index.cshtml code. Thank yo ...

Storing information in local storage as JSON using AngularJS

I am working on a form with the following fields: <form ng-submit="addState()"> <input ng-model="text1" type="text"> <input ng-model="text2" type="text"> <input ng-model="text3" type="text"> ...

Find all strings in the array that do not begin with a letter from the alphabet

When a specific button is clicked, I need to filter the example array provided in the snippet below. The expected output should only include elements that do not start with an alphabet. I attempted: const example = ["test", 'xyz', '1 test& ...

Top solution for live chat between server and client using jQuery, Java, and PHP on a localhost setup

Seeking recommendations for the best chat solution to facilitate communication between client PCs and a server in my private network. Specifically interested in an Ajax/Java solution similar to the chat support feature found in GMail. ...

Monitor website visitors' traffic sources using the Google Analytics Nuxt module

Recently I integrated Google Analytics into my Nuxt website. After installing the module, I configured it in the nuxt.config.js file like this: gtm: { id: 'GTM-WGW****' }, googleAnalytics: { id: 'UA-230******-*' ...

Unable to transform SVG files in Next.js Jest version 28

Currently, my setup involves Next.js version 12.0.7, Jest version 28.1.0, and the use of the next-react-svg library for importing SVG files into components. The configuration in my jest.config.js file looks like this: // jest.config.js const nextJest = re ...

Scrollbar in an HTML selection tag

Is there a way to add a scroll bar to an HTML select box without using JavaScript? Alternatively, is there a JavaScript library that can achieve this behavior? Also, I'm looking for a redesign of the interface where I have two select boxes and items ...

There was a serious issue: The mark-compacts were not working effectively near the heap limit, resulting in allocation failure - the JavaScript heap ran out of memory during the

I recently set up a t2.micro server on AWS and encountered an issue when running our application with the command "sudo npm start". The error message I received was: "FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript he ...

Refresh the page without reloading to update the value of a dynamically created object

Maybe this question seems silly (but remember, there are no stupid questions).. but here it goes. Let me explain what I'm working on: 1) The user logs into a page and the first thing that happens is that a list of objects from a MySQL database is fet ...

How can I determine the remaining amount of scroll left in my HTML document?

Is there a method to determine how many pixels of scroll remain on the page when the scrollbar is set at a specific position? I am currently utilizing jQuery's scrollLeft feature, which can be found here: http://api.jquery.com/scrollLeft/. I want to ...

The error message "404 Not Found" was triggered when attempting to deliver the

Here is the server-side code snippet that I am using: var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendfile( ...

Check if the form field uses Jquery

How can you use Jquery or plain javascript to determine if something is a form field? For example: <div id='some_id'></div> or: <input type='text' id='some_id'> Is there a method to check $('#some_id ...

How can I achieve this outcome using Java?

The following code retrieves data from a database and generates a JSON output: public JSONArray tree_data() { JSONArray result = new JSONArray(); JSONArray nodes = new JSONArray(); try { String query= "select parent_names.name as par ...

Utilizing the require pattern to integrate JavaScript functionality into HTML

Have: project |- consume_script.js |- index.html Need index.html to be like: <html> <head> </head> <body> <script src="consume_script.js"></script> </body> </html> Issue: consume_script ...

Selenium WebDriverJs has difficulty in setting up a new client for iOS devices

Struggling to make Selenium WebDriverJS work with the iOS browser, but unfortunately facing some issues. I followed the instructions on setting up the "iWebDriver" project as mentioned on the iPhoneDriver wiki page. The Python script worked fine, and even ...