Is it possible to restrict the acceptance of certain variables from a CSV file in Django form fields, instead of accepting

In my Django model, I have two fields for latitude and longitude which are both declared as CharField. The model needs to accept multiple coordinates, so in the UI form, I enter these coordinates separated by commas. I then split this char input in a function to perform computations.

This is what my models.py looks like:

class Location(models.Model):
    country = models.ForeignKey(Countries, on_delete=models.CASCADE)
    latitude = models.CharField(max_length=1000, help_text="Add the latitudes followed by comma")
    longitude = models.CharField(max_length=1000, help_text="Add the longitudes followed by comma")

This is the function in my view.py:

def dashboard(request):
    form = LocationForm
    if request.method == 'POST':
        form = LocationForm(request.POST)
        if form.is_valid():
            form.save()
            latitude = list(map(float, form.cleaned_data.get('latitude').split(',')))
            longitude = list(map(float, form.cleaned_data.get('longitude').split(',')))
            .........
            .........
    return render(request, dashboard/dashboard.html, { 'form':form })

Now, I want to be able to add coordinates using a CSV file in addition to manually entering them. I'd like an option in the UI to upload a CSV file containing multiple latitudes and longitudes which will then populate the respective char fields with comma-separated values.

It's important to note that the CSV file won't include the country name, which will still need to be entered through the UI form.

To clarify, I only want some of the form fields to be populated by the CSV file, not all of them. Existing solutions I've found populate all model fields including those not present in the CSV file, creating a dependency issue.

What can I do in this case? Maybe introduce a FileField() in the model or utilize JavaScript to handle coordinate population in the UI... or explore other options?

If you're unsure about the best approach, I'm open to suggestions!

Answer №1

Learn more about upload handlers in Django

To define your form class, follow this example:

# import csv
# import codecs
# form = LocationForm(data=request.POST, files=request.FILES)

class LocationForm(forms.ModelForm):
    file = forms.FileField(required=False)

    class Meta:
        model = Location
        fields = ('file', 'country', 'latitude', 'longitude')  # maintain this order

    def clean_file(self):
        if 'file' not in self.files:
            return

        file = self.files['file']
        reader = csv.reader(codecs.iterdecode(file, 'utf-8'))
        header = next(reader)
        latitudes = []
        longitudes = []
        for lat, long in reader:
            latitudes.append(lat)
            longitudes.append(long)
        self.data['latitude'] = ','.join(latitudes)
        self.data['longitude'] = ','.join(longitudes)
        return file

The benefit of this approach is that any validation defined for clean_latitude/clean_longitude will remain effective.

If you encounter difficulties, refer to my tests: Test scenarios available here


Some reflections:

  1. In the Django framework, models are usually singular – consider renaming Countries to Country
  2. Have you considered using DecimalField instead of CharField for latitude and longitude? Each location can have multiple entries based on country, allowing for a more structured data setup than combining all geo points into one row.

My suggestion: Change longitude and latitude to DecimalField, perform individual field validations, and create a new Location instance for each country-longitude-latitude combination found in the CSV file.

Please note that my recommendations are speculative and based on assumptions without full knowledge of your project requirements.

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

Problem with resizing in CSS and jQuery

I need help creating a chatbox that can be resized. I've almost got it, but the bottom part of the chatbox detaches when I resize it. Also, I'm having trouble making the userList a fixed size that won't be affected by resizing. Check out th ...

Tips for retrieving page source with selenium Remote Control

Looking to Develop a Basic Java Web Crawler. WebDriver driver = new HtmlUnitDriver(); driver.get("https://examplewebsite.com"); String pageSource=driver.getPageSource(); System.out.println(pageSource); The result is as follows: <!DOCTYPE html PUBLIC ...

Using Protractor to extract text from multiple paragraphs

How do I retrieve the values of all paragraphs (p) at once? Below is an example of how my inspect view appears: "Testing sample one." "Testing sample two." And here is a snippet of my code to extract the value of id 'run': browser.findElement ...

Python Selenium output that is out of the ordinary

I'm receiving comments from a website, and I initially tried it out with success. However, the output it now giving me is strange. This is a snippet of my code: comments = driver.find_elements_by_class_name("comment-text") time.sleep(1) print(commen ...

Angular's '@angular/core/core' module does not have the exported member 'ɵɵFactoryDeclaration'

My Angular application was successfully compiled after running npm install. However, upon executing npm start, I encountered the following error: ERROR in node_modules/ng-apexcharts/lib/chart/chart.component.d.ts:57:21 - error TS2694: Namespace '&quo ...

In the process of making a request with axios in an express server

Struggling with a simple call to an API using Axios with Express, and I can't figure out why it's always pending in the browser. Here is my route: var express = require("express"); var router = express.Router(); const controller = require("../. ...

Importing a JSON file into a React component

I have a JSON file that I am importing in my React project: import React from 'react'; import Test1 from './test1.jsx'; import data from './data.json'; class TestWrapper extends React.Component { render () { return ( ...

Utilize Express.js to seamlessly stream and process uploaded files with formidable and gm, ensuring a streamlined process without

I am looking for a solution to upload and resize an image in one step without having to write to disk twice. For uploading images, I am using: node-formidable: https://github.com/felixge/node-formidable And for resizing the images, I am using: gm: Howev ...

Issues with Await and Async functionality in Angular and Ionic 4 causing unexpected behavior

Struggling to show error messages during the sign-up process? Constantly encountering the same issue in your code? The error TS1308 is throwing you off: 'await' expression is only allowed within an async function. Take a look at this problemati ...

Not receiving connections on localhost port 3000

Our team has successfully created a basic Express Node website https://i.stack.imgur.com/5fwmC.png We attempted to run the app using DEBUG=express_example:* npm start https://i.stack.imgur.com/NI5lR.png We also tried running it with node DEBUG=express_ ...

Vanishing Act: React-js MUI Tooltip vanishes upon clicking

The standard behavior of the MUI Tooltip is as follows:
 If the button/icon to trigger a tooltip is not in focus, the tooltip will not disappear when clicking directly on the popper. However, if the button/icon is focused, the tooltip will disappear upo ...

Creating a JavaScript regular expression for formatting time input without using any external plugin

As I work on implementing a time input mask with the meridian of am|pm without using an input mask plugin, I've encountered some challenges. The input should not allow the user to start with alphabets, but my current pattern, although it works, clears ...

Grouping emitted events using RxJS in a Node.js environment

Currently, I am interfacing with a database and receiving the results in a continuous stream of events labeled 'db_row_received'. My aim is to categorize these results based on the company Id, however, I am encountering an issue where the subscri ...

Vue.js HTML5 Editor_vueful

I am currently utilizing browserify and attempting to incorporate the vue-html5-editor library from https://github.com/PeakTai/vue-html5-editor. However, when I attempt the following code: Vue.use(require('vue-html5-editor')); An error is thro ...

Submitting a form in Rails without refreshing the page and dynamically updating the view

Hello everyone! I am currently utilizing Rails and in my process, I would like the user to perform the following steps on the same page: Input their address Completing the form Submit the form Clicking to submit Update the view to display the add ...

Error in the execution of the if statement within $(window).width() when it is not supposed to be

Hello everyone, I'm facing an issue with the jQuery $(window).width when using if statements. It seems that my function is still running even when the window width is smaller than 991 pixels, although my if statement specifies that it should run only ...

Best practices for organizing an array of objects in JavaScript

I have an array of objects with nested arrays inside, and I need to restructure it according to my API requirements. [{ containerId: 'c12', containerNumber: '4321dkjkfdj', goods: [{ w ...

Ways to activate the built-in HTML5 form validation without actually submitting the form

I have a form in my application that I plan to submit using AJAX. However, I would like to implement HTML5 for client-side validation. Is it possible to trigger form validation without actually submitting the form? Here is an example of the HTML code: &l ...

Having trouble getting your Bootstrap v4 carousel to function properly?

Currently, I have implemented the carousel feature from Bootstrap v4 in a Vue web application. I am following the same structure as shown in the sample example provided by Bootstrap, but unfortunately, it is not functioning correctly on my local setup and ...

After a successful transactWrite operation using DynamoDB.DocumentClient, the ItemCollectionMetrics remains unpopulated

Currently, I am utilizing a transactWrite instruction to interact with DynamoDb and I am expecting to receive the ItemCollectionMetrics. Even though changes have been made on the DynamoDb tables, the returned object is empty with {}. Does anyone have any ...