Preserving Foreign Key Relationships in Django Rest Framework Serializers

Within my project, I have two interconnected models named Task and Batch, linked through a Foreign Key field. My goal is to verify the existence of a Batch Object in the database before creating a new Task Object. The Batch object represents the current date and allows tasks to be grouped accordingly. If a Batch object does not exist, one should be created and assigned to the Task being generated.

However, during the save process, I encounter an error:

(index):328 POST http://localhost:8000/api/task-create/ 500 (Internal Server Error)

Here's the relevant code snippets:

@api_view(['POST'])
def taskCreate(request):
    batch = Batch.objects.filter(batch = datetime.date.today()).first()
    serializer = TaskSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save(commit=False)
        if batch is None :
            batch = Batch.objects.create(batch = datetime.date.today())
        serializer.batch = batch
        serializer.save()
    return Response(serializer.data)

models.py

class Batch(models.Model):
    batch = models.DateField(auto_now_add=True)
    
    class Meta:
        ordering = ['-batch']
        verbose_name = 'Batch'
        verbose_name_plural = 'Batches'

    def __str__(self):
        return self.batch.strftime("%B %d, %Y %A")

class Task(models.Model):
    title = models.CharField(
            max_length = 256,
        )
    completed = models.BooleanField(
            default =  False,
        )
    batch = models.ForeignKey(Batch, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

serializers.py

class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = '__all__'
        depth = 1

This snippet demonstrates how I handle form submission on the frontend:

var form = document.getElementById("form")
form.addEventListener('submit', function(e){
    e.preventDefault()
    var url = "{% url 'api:task-create' %}"
    if(activeItem != null ){
        url = `http://localhost:8000/api/task-update/${activeItem.id}/`
        activeItem = null
    }
    var title = document.getElementById('title').value
    fetch(url, {

        method: 'POST',
        headers:{
            'Content-type': 'application/json',
            'X-CSRFToken': csrftoken,
        },
        body: JSON.stringify({'title':title})
    }).then(function(response){
        renderList()
        document.getElementById('form').reset()
    })
})

Answer №1

UPDATE: I managed to discover the solution on my own

views.py

@api_view(['POST'])
def taskCreate(request):
    check_batch = Batch.objects.filter(batch = datetime.date.today()).first()
    if check_batch is None:
        check_batch = Batch.objects.create(batch = datetime.date.today())
    serializer = TaskSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save(batch = check_batch)
    return Response(serializer.data)

and I retrieve the foreign key data in vanilla JavaScript using:

${taskList[task].batch.batch}

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

Ensure that TypeScript compiled files are set to read-only mode

There is a suggestion on GitHub to implement a feature in tsc that would mark compiled files as readonly. However, it has been deemed not feasible and will not be pursued. As someone who tends to accidentally modify compiled files instead of the source fil ...

How to retrieve the column names of a table using Web SQL?

Working on extracting column lists from Web SQL (Chrome's local database). One approach is to gather information from sqlite_master. SELECT name, sql FROM sqlite_master WHERE type="table" AND name = "'+name+'"; As an example, here is a sam ...

Utilize React to process and submit payments through Stripe

I am currently working on integrating Stripe Elements with my React application. The JavaScript page below showcases the code I use to submit the payment form, which I have compiled from various sources online. Upon submitting the form, I receive a token; ...

Tips for swapping out a new line character in JavaScript

Hello! I'm currently facing a challenge with some code. I have a function designed to replace specific HTML character values, such as tabs or new lines. However, it's not functioning as expected. var replaceHTMLCharacters = function(text){ tex ...

Error 422 encountered while trying to create a new asset using the Contentful Content Management API

My attempt to create and publish an image as an asset using the Contentful Content Management API has hit a roadblock. I managed to successfully create and publish an entry, but I can't seem to figure out why creating an asset is not working as expect ...

Modifying the width of a jQuery UI dialog from within the dialog box itself

I have designed an ASP.Net web page with a div and iFrame to display another page within it. Now, I am wondering if there is a way to change the width of the dialog from a button inside the dialog itself... Is this achievable? Thank you. ...

Leveraging React's State Values and Props

Can you help me with a React component challenge? I have two components that I need to work with: <select> <mytable> I want to build a new component called <myInterface>. The state of <myInterface>, let's call it S, needs to ...

How can I parse URL paths in jQuery for ASP.NET?

I want to incorporate "~/" and have it resolved on the client side. Here is an example of what I am trying to do: <a href="~/page.aspx">website link</a> <img src="~/page.aspx" /> In my ASP.NET code, I have my base URLs set up like this ...

Securing child paths in Vue.js

Having trouble protecting child routes from parent routes, facing some issues export default new Router({ routes: [ //frontend routes { {path: 'auth', component: Auth, children: authroutes, beforeEnter: (to, from, n ...

Can ngFor be utilized within select elements in Angular?

I'm facing an interesting challenge where I need to display multiple select tags with multiple options each, resulting in a data structure that consists of an array of arrays of objects. <div class="form-group row" *ngIf="myData"> <selec ...

Firefox not responding to input select dropdown selection

When creating a jQuery submenu box in Firefox, I encountered an issue with the input select dropdown. While it functions properly in Google Chrome, the select box behaves erratically in Firefox. When attempting to choose an option from the select box, such ...

Is utilizing v-model to update the Vuex store a recommended practice?

Hello there! As a newcomer to Vue, I find myself facing a dilemma that has been weighing on my mind. I'm confused about whether we should utilize the v-model directive to make changes to the Vuex store. While Vuex guidelines suggest modifying the stor ...

Acquire the current audio video stream directly from the web browser

Currently, I am utilizing a JavaScript library that internally invokes getUserMedia. My objective is to access the stream object that has already been initiated. Unfortunately, the library does not provide any means to retrieve it. Is there a method avai ...

Incorporating Progressive Web App Support into a JavaServer Faces Web Application

Exploring the possibility of integrating Progressive Web App support into a JavaServerFaces web application has become a focal point for our team. As our JSF app continues to evolve, we foresee the need to provide offline access to certain parts of the app ...

AngularJS: Retrieve individual objects from an array and subsequently initiate asynchronous requests

I am working with two tables, Category and Products, linked by a 1-N cardinality relationship. https://i.sstatic.net/e6C2y.png My goal is to retrieve all products belonging to a specific category. https://i.sstatic.net/yDrjr.png Here is the HTML table ...

Ways to incorporate a scroll feature and display an iframe using JQuery

Is there a way to animate the appearance of hidden iframes one by one as the user scrolls down the website using jQuery? I have come across some solutions, but they all seem to make them appear all at once. I'm looking for a way to make the iframes s ...

What could be causing the Javascript Dynamic HTML5 Table to not display on the page?

I have a program that calculates the total price of products based on a specified quantity and updates an HTML table with these values. To demonstrate this, I am constantly taking input using an infinite loop. <!DOCTYPE html> <html> ...

Submitting a JavaScript array to MongoDB using a React application: A guide to success!

As a beginner delving into the world of React and MongoDB, I'm encountering difficulties in establishing communication between the two technologies. Recently, I've been following a detailed tutorial on Medium that focuses on utilizing the Plaid A ...

How can Vue.js implement a satisfactory method for synchronizing computed values with asynchronous data?

Imagine retrieving a list of products from the state manager in your Vue.js component, where a computed property is then used to process this list for display on the DOM. <template> <span>{{ computedProducts }}</span> </template> ...

Issue with remounting in Nextjs 13

import { useRouter, useSearchParams, usePathname } from 'next/navigation'; export function useQueryParams() { const pathname = usePathname(); const router = useRouter(); const searchParams = useSearchParams()!; const updateQu ...