Skip to main content

I'm having problems when sending User's Id's on a django model

I'm tryng to do a post method on projetos on my Vue Front-end but i keep getting the error message of "null value in column "professor_id" of relation "fabrica_projeto" violates not-null constraint" even though the request body is the same when i try to post on django-admin and it works there

I'm kinda new to this whole coding world so sorry if my vocabulary is lacking

On Vue/ my front-end enter image description here

On Django-Admin(works)

enter image description here enter image description here

This is the model for Projeto enter image description here

from django.db import models
from usuario.models import Usuario
from uploader.models import Image


class Projeto(models.Model):
    nome = models.CharField(max_length=200)
    descricao = models.CharField(max_length=2500)
    data = models.DateTimeField(auto_now_add=True) 
    professor = models.ForeignKey(Usuario, related_name='professor', on_delete=models.PROTECT) 
    alunos = models.ManyToManyField(Usuario, related_name='alunos') 
    capa = models.ForeignKey(
        Image,
        related_name="+",
        on_delete=models.CASCADE,
        null=True,
        blank=True,
    )
    
    def __str__(self):
        return self.nome

My Vue page is looking like this: (the professor part of the request is getting directly from the current user id):

import api from '../plugins/api'
import {useAuthStore} from '../stores/auth'

class WorkspaceService {
  async getAllWorkspaces() {
    const response = await api.get('/projetos/')
    return response.data
  }
  async saveWorkspace(workspace) {
    const authStore = useAuthStore()
    workspace.professor = authStore.user_id
    let response
    if (workspace.id) {
      response = await api.put(`/projetos/${workspace.id}/`, workspace)
    } else {
      response = await api.post('/projetos/', workspace)
    }
    return response.data
  }
  async deleteWorkspac(workspace) {
    const response = await api.delete(`/projetos/${workspace.id}/`)
    return response.data
  }
}

export default new WorkspaceService()
<script setup>
import { RouterLink } from 'vue-router'
import { ref, onMounted } from 'vue'
import WorkspaceService from '../services/workspaces'
import UserService from '../services/users';

const users = ref([])

const workspaces = ref([])
const currentWorkspace = ref({
  nome: '',
  descricao: ''
})

onMounted(async () => {
  const data = await UserService.getAllUsers()
  users.value = data
})

onMounted(async () => {
  const data = await WorkspaceService.getAllWorkspaces()
  workspaces.value = data
})

async function save() {
  await WorkspaceService.saveWorkspace(currentWorkspace.value)
  const data = await WorkspaceService.getAllWorkspaces()
  workspaces.value = data
  currentWorkspace.value = { nome: '', descricao: '' }
}

async function deleteWorkspace(workspace) {
  await WorkspaceService.deleteWorkspace(workspace)
  const data = await WorkspaceService.getAllWorkspaces()
  workspaces.value = data
}

function editWorkspace(workspace) {
  currentWorkspace.value = { ...workspace }
}
</script>

<template>
  <div class="wrapper">
    <div class="sidebar">
      <img class="logo" src="../components/icons/logo-green.svg" />
      <div class="nav-list">
        <RouterLink class="nav-links" to="/post">Novo Post</RouterLink>
        <RouterLink class="nav-links" to="/new-workspace">Novo Workspace</RouterLink>
        <RouterLink class="nav-links" to="/home">Home</RouterLink>
      </div>
    </div>

    <div class="main">
      <form class="work-box" @submit.prevent="save" >
        <input v-model="currentWorkspace.nome" class="input" type="text" placeholder="Nome do Workspace" />
        <textarea v-model="currentWorkspace.descricao" class="input area" type="text" placeholder="Descrição do Workspace" />
        <label tabindex="0" class="file-input-area">
          <div class="input-image-box">
            <img class="file-input-image" src="../components/icons/clip.svg" />
          </div>
          <span class="image-text">
            Arraste arquivos aqui para anexar, ou
            <span class="highlight">procure-os</span>
          </span>
          <input type="file" accept="image/png, image/jpeg" name="file_upload" class="file-input" />
        </label>
        <input type="number" v-model="currentWorkspace.alunos" />
        <button type="submit" class="button">Enviar</button>
      </form>

      <div class="work-box">
        <div class="past-posts">
          <h1>Workspaces</h1>
          <div v-for="workspace in workspaces" :key="workspace.id" class="past-post-box">
            <div class="img-pad">
              <img class="post-img" src="../components/icons/logo-green.svg" />
            </div>
            <div class="post-info">
              <h2></h2>
              <p></p>
            </div>
            <div class="post-btns">
              <button class="edit-btn" @click="editWorkspace(workspace)">
                Editar
              </button>
              <button class="delete-btn" @click="deleteWorkspace(workspace)">
                Deletar
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

I tried using workspace.professor.id, and v-model="currentWorkspace.alunos.id" but it doesn't work and gives me another error message of "Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'id')"

Via Active questions tagged javascript - Stack Overflow https://ift.tt/OTmRClD

Comments

Popular posts from this blog

Prop `className` did not match in next js app

I have written a sample code ( Github Link here ). this is a simple next js app, but giving me error when I refresh the page. This seems to be the common problem and I tried the fix provided in the internet but does not seem to fix my issue. The error is Warning: Prop className did not match. Server: "MuiBox-root MuiBox-root-1" Client: "MuiBox-root MuiBox-root-2". Did changes for _document.js, modified _app.js as mentioned in official website and solutions in stackoverflow. but nothing seems to work. Could someone take a look and help me whats wrong with the code? Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype

Why is my reports service not connecting?

I am trying to pull some data from a Postgres database using Node.js and node-postures but I can't figure out why my service isn't connecting. my routes/index.js file: const express = require('express'); const router = express.Router(); const ordersCountController = require('../controllers/ordersCountController'); const ordersController = require('../controllers/ordersController'); const weeklyReportsController = require('../controllers/weeklyReportsController'); router.get('/orders_count', ordersCountController); router.get('/orders', ordersController); router.get('/weekly_reports', weeklyReportsController); module.exports = router; My controllers/weeklyReportsController.js file: const weeklyReportsService = require('../services/weeklyReportsService'); const weeklyReportsController = async (req, res) => { try { const data = await weeklyReportsService; res.json({data}) console