"Encountering a puzzling issue with Django Rest Framework where the path setup is functioning for one link but not for

I'm currently attempting to connect to my MySQL database using the Django REST backend. On my frontend, I'm using Vue with Axios. Specifically, I have a junction table called TeacherSubjectJunction, and I want to access it through the following path to retrieve all subjects for a specific teacherid.

app/urls.py

path('teacherssubjects/<int:teacherid>/', TeacherSubjectJunctionList.as_view())

views.py:

class TeacherSubjectJunctionList(generics.ListAPIView):
    queryset = TeacherSubjectJunction.objects.all()
    serializer_class = TeacherSubjectJunctionDeepSerializer
    filterset_class = TeacherSubjectJunctionFilter

serializer.py:

class TeacherSubjectJunctionDeepSerializer(serializers.ModelSerializer):

    class Meta:
        model = TeacherSubjectJunction
        fields = ['teacherid', 'subjectid']
        depth = 3

To filter, I am utilizing the third-party library django-filter.

filters.py

class TeacherSubjectJunctionFilter(filters.FilterSet):
    class Meta:
        model = TeacherSubjectJunction
        fields = ['teacherid', 'subjectid']

models.py

class TeacherSubjectJunction(models.Model):
    pk_teachersubject = models.AutoField(primary_key=True)
    teacherid = models.ForeignKey(Teachers, models.CASCADE, db_column='TeacherID')  
    subjectid = models.ForeignKey(Subjects, models.CASCADE, db_column='SubjectID')

    class Meta:
        db_table = 'teacher_subject_junction'

In my Vue file, I'm trying to access this path with the given code snippet:

async getSubjectsforTeacher(teacher){
                await getAPI.get('/teacherssubjects/?teacherid='+teacher)            
                    .then(response =>{
                        this.SubjectsforTeacherData[teacher] = response.data
                        console.log(this.SubjectsforTeacherData)
                    }).catch(error =>{
                        if (error.response){
                            console.log( error.response )
                        }else if(error.request){
                            console.log( error.request )
                        }else if(error.message){
                            console.log( error.message )
                        }
                    })
               }

The above setup results in the following error message:

GET http://127.0.0.1:8000/teacherssubjects/?teacherid=3 404 (Not Found)

Given that I'm relatively new to DRF, I suspect there might be an issue with my URL configuration. However, what's intriguing is that I have a similar setup for another junction table named StudentLectureJunction, as shown below:

app/url.py:

path('studentslectures/<int:lectureid>/', StudentLectureJunctionList.as_view())

views.py:

class StudentLectureJunctionList(generics.ListAPIView):
    queryset = StudentLectureJunction.objects.all()
    serializer_class = StudentLectureJunctionDeepSerializer
    filterset_class = StudentLectureJunctionFilter

serializer.py:

class StudentLectureJunctionDeepSerializer(serializers.ModelSerializer):
    
    class Meta:
        model = StudentLectureJunction
        fields = ['lectureid', 'studentid']
        depth = 4

filters.py:

class StudentLectureJunctionFilter(filters.FilterSet):
    class Meta:
        model = StudentLectureJunction
        fields = ['studentid', 'lectureid']

models.py

class TeacherSubjectJunction(models.Model):
    pk_teachersubject = models.AutoField(primary_key=True)
    teacherid = models.ForeignKey(Teachers, models.CASCADE, db_column='TeacherID')
    subjectid = models.ForeignKey(Subjects, models.CASCADE, db_column='SubjectID')

    class Meta:
        db_table = 'teacher_subject_junction'

When implementing this setup in my Vue file, everything works correctly and returns the expected results. Can anyone assist me in troubleshooting the issue with my first setup?

Answer №1

Based on the reply

GET http://127.0.0.1:8000/teacherssubjects/?teacherid=3 404 (Not Found)

It appears that instead of simply passing the number 3, the string ?teacherid=3 is being passed.

One solution is to use backticks in the URL string of the GET request like this:


async getSubjectsforTeacher(teacher){
                await getAPI.get(`/teacherssubjects/${teacher}/`)            
                    .then(response =>{
                        this.SubjectsforTeacherData[teacher] = response.data
                        console.log(this.SubjectsforTeacherData)
                    }).catch(error =>{
                        if (error.response){
                            console.log( error.response )
                        }else if(error.request){
                            console.log( error.request )
                        }else if(error.message){
                            console.log( error.message )
                        }
                    })
               }

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

How can one adhere to Angular's recommendation of "always using dots with ngModel" while working within isolate scopes?

Currently, I am working on developing an Angular application utilizing Bootstrap. To reduce the impact of Bootstrap on my HTML code, I have implemented two directives specifically for forms: form-control.js module.directive('formControl', func ...

Ensuring Consistent Visual Harmony Across Linked Elements

As part of my project developing an iPad app with PhoneGap and jQuery Mobile, I am looking to incorporate a preview pane within a carousel. This preview pane should display smaller versions of the other panes scaled inside it. The panes are dynamic and upd ...

When you reach the end of the page, the loadMore function is triggered multiple times

On my webpage, I have a list of profiles that are displayed. When the user reaches the bottom of the page, more data should be loaded through the loadMore function. While the loadMore function itself works correctly, I am facing an issue with the listener. ...

The error message "Error: 'x' is not a defined function or its output is not iterable"

While experimenting, I accidentally discovered that the following code snippet causes an error in V8 (Chrome, Node.js, etc): for (let val of Symbol()) { /*...*/ } TypeError: Symbol is not a function or its return value is not iterable I also found out ...

Using Vue.Js to link a value to a checkbox within a component

I'm currently developing a custom component that wraps around a checkbox (similar to what I've done with text and number input types), but I'm facing an issue with binding the passed-in value correctly. Here's the structure of my compo ...

Vue: nesting components within components

Looking for a clever solution to create a nested component system with efficient rendering? Check out the code snippet below: custom-tab.vue (child component) <template> <slot></slot> </template> <script> export def ...

Testing of onClick event in a React component using styled-components with Sinon spies

Utilizing sinon to test a react component and verify that an onClick function is triggered. Struggling to target the element to click on due to the use of styled-components. Encountering this error message: The "simulate" method should only be run on ...

When clicked, you will be redirected to the details page

Currently, I am developing a React JS application that showcases a list of companies fetched from a Node.js/Express server in a table format. When clicking on each row, it triggers a modal to display some details about the company. The modal consists of t ...

show information retrieved from database according to the drop-down menu selection

Can anyone assist me with this query? I have a drop-down menu that includes "Shop A" and "Shop B". Shop A has a value of 1, and Shop B has a value of 2. When I select Shop A from the dropdown, I want to display the data from the database as a table specifi ...

The overlay feature in Vuetify 3 seems to be malfunctioning following the migration from Vue 2

I have recently migrated a Vue2 project to Vue3 and set up a Vite project. Even though the code from the old Vue2 project works fine, I am facing issues with an overlay functionality in one of my components. Despite setting the overlay to true in data and ...

Achieving distinct CSS margins for mobile and desktop devices in a Django template without the need for multiple {% block content %} statements

Is there a way to dynamically change the margin-left of my main {% block content %} in the base.html template based on whether the viewer is using a mobile or desktop device? This is how my current base.html looks like: <div class="content container-f ...

Reversing data in Vue3

I've been struggling to create a custom dropdown for my application. I need to implement a function that adds a class called is-active to a div element. So, what I have done is created a simple div with an onclick function as shown below: <div :cla ...

Switch div and expand/shrink the rest

Apologies for what might seem like a trivial question, but after working for a few hours now, I'm finding it difficult to wrap my head around this. My initial instinct is to handle this by manipulating the entire div structure with JavaScript, but I c ...

What is the reason that jQuery does not work on HTML generated by JavaScript?

One of my JavaScript functions, named getImages, is responsible for loading the following HTML structure: // Function starts here function getImages() { $.getJSON(GETIMAGELIST, function(data) { var items = []; // Populating the HTML $.each(dat ...

It's time to wrap up the session with some old "cookies" and a closing function

Would like the message to only display once after clicking the "Cookies" button. Once the user accepts cookies, they should be stored on their device for a set period of time. Your assistance is greatly appreciated. :) Below is the html and js code: $(do ...

Dynamic CSS Changes in AngularJS Animations

I am currently working on a multi-stage web form using AngularJS. You can see an example of this form in action by visiting the link below: http://codepen.io/kwakwak/full/kvEig When clicking the "Next" button, the form slides to the right smoothly. Howev ...

Tips for incorporating the multiply times async function into mocha tests

I am attempting to utilize the async function foo multiple times in my mocha tests. Here is how I have structured it: describe('This test', () => { const foo = async () => { const wrapper = mount(Component); const button ...

Navigate to the specific page using the router-link with the designated path

I have 10 different filters displayed in a table and I want each filter name to link to a specific page. Here is an example of my table row: <md-table-row v-for="(row, index) in manage" :key="index"> In the first cell of the table, I'm trying ...

Extract content from whole webpage including HTML, CSS, and JavaScript

Currently I am working on developing a webpage version control backup/log system. The goal is to automatically save a static copy of the webpage, including all its CSS and JavaScript files, whenever there are any changes made. I have already figured out h ...

Retrieve the height of an element containing images, even if the images have not finished loading

After making an Ajax call and inserting some HTML code, I require the height of the newly added div in the Ajax callback. However, the issue arises because the HTML from the Ajax call contains elements like images that need to be loaded first. I have crea ...