I am new to vue.js and django also,
Need some help on below issue.
I have created an api in which I am trying to fetch the data from one DB table and send the same to vue.js page to have check on it.
I am getting error "{"detail":"Method \"GET\" not allowed."}"
I tried it in multiple ways like sending the data in JSON form or as a array but still getting the same issuse
Model.py below are the models for deserializing and for the table I am using to fetch the data
def deserialize_Issue(issue):
"""Deserialize user instance to JSON."""
return {id': issue.id, 'IName': issue.IName, 'IDesc': issue.IDesc, 'ITeam': issue.ITeam,'IStat': issue.IStat, 'IChat': issue.IChat, 'Iuri': issue.Iuri, 'Ibridge': issue.Ibridge, 'Ibridgedetails': issue.Ibridgedetails }
class Issue(TrackableDateModel):
IName=models.CharField(max_length=500)
IDesc=models.CharField(max_length=1000)
ITeam =models.CharField(max_length=500)
IStat=models.CharField(max_length=250)
IChat=models.CharField(max_length=2,default='NA')
Iuri=models.URLField(default='NA')
Ibridge=models.CharField(max_length=2,default='NA')
Ibridgedetails=models.CharField(max_length=20,default='NA')
def __str__(self):
return self.IName, self.IStat
IN my view.py file I have created the calls and the get method to fetch the data from the table.
class IssuesDetailsView(APIView):
def get(self, request, *args, **kwargs):
DETAILS='Issue.objects.all()'
serializer=deserialize_Issue(DETAILS,many=True)
return Response ({'Issues': serializer.data})
abc.vue in vue.js file trying to acees the get the data
fetchIssueDetails () {
$.get(`http://127.0.0.1:8000/api/chats/`, (data) => {
this.Issues = data.Issues
})
.fail((response) => {
alert(response.responseText)
})
}
I want to read the table data in the vue.js file in for loop
Here's the urls.py you've provided me in the comments:
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('chats/', views.ChatSessionView.as_view()),
path('chats/<uri>/', views.ChatSessionView.as_view()),
path('chats/<uri>/messages/', views.ChatSessionMessageView.as_view()),
]
Notice how the url /api/chats/ is tied to views.ChatSessionView, not IssuesDetailsView. Yet in your Javascript you are making the request to /api/chats/.
So one way to resolve your issue is
path('chats/', views.IssuesDetailsView.as_view()),
Related
I try to use class method in mongoengine to define a method that hash the password and write data to mongodb, then call the method outside the class, here is my code
model.py
from mongoengine import Document, connect, fields
connect("mongoUserDB", host="127.0.0.1", port=27017)
class Users(Document):
userID = fields.StringField(unique=True)
password = fields.StringField()
#classmethod
def signup(cls,**kwargs):
print(kwargs.get("password",cls.password))
cls.password = pbkdf2_sha256.encrypt(kwargs.get("password",cls.password))
print(cls.password)
Users(**kwargs).save()
api.py
from flask import render_template
from blueprint_poc.auth import bp
from models import Users
#bp.route("/sign-up", methods=['GET', 'POST'])
def sign_up():
Users().signup(userID='aaa',password='b')
It did write data to the db, but only with userID info,the password field is missing.
I am not sure what went wrong, any advice for this.
I'm trying to add a new screen to Subiquity but Subiquity gets stuck every time I run it.
running server pid 40812
connecting... /
To create my controller I used an example from DESIGN.md
My server controller class is as below:
import logging
from subiquity.common.apidef import API
from subiquity.server.controller import SubiquityController
log = logging.getLogger('subiquity.server.controllers.example')
class ExampleController(SubiquityController):
endpoint = API.example
model_name = 'example'
async def GET(self) -> str:
return self.model.thing
async def POST(self, data: str):
self.model.thing = data
await self.configured()
Also, I added my Example controller class to controllers[] in subiquity/server/server.py:
controllers = [
# other classes
"Kernel",
"Keyboard",
"Example",
"Zdev",
"Source",
# some other classes
]
And added example = simple_endpoint(str) to apidef.py
My model as simple as possible:
class ExampleModel:
thing = "example_var"
What might cause the problem? If I remove my Example controller from controllers[], Subiquity works but obviously doesn't use my controller.
I have a viewset like this:
class MyViewSet(CreateAPIView, RetrieveModelMixin, ListModelMixin, GenericViewSet):
queryset = MyModel.objects.all()
serializer_class = MySerializer
def post(self, request, *args, **kwargs):
import pdb; pdb.set_trace()
class MySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = MyModel
fields = ['id', 'field1', 'field2'] #only field1 is required in the model
The GET requests for list, and retrieve works perfectly. When I make a POST request, sending the field1 I get a status 201 and a new record is added to the database, so it works too.
But my method MyViewSet.post() that should overwrite the same one from generics.CreateAPIView never gets called.
Not only that, but I've tried to add the pdb.set_trace(), literally inside the generics.CreateAPIView.post() and in the CreateModelMixin.create() functions and neither stopped once I made the POST request.
So something else is handling this POST request and inserting into the DB, I just don't know what. And how can I overwrite it, so I can customize what should be done with a post request?
PS.: Also, I don't think it's a routing problem, my urls.py:
from rest_framework import routers
from myapp.views import MyViewSet, AnotherViewSet
router = routers.DefaultRouter()
router.register(r'route_one', MyViewSet)
router.register(r'route_two', AnotherViewSet)
I think you need to use the exact class in order to use POST api.
class MyView(CreateModelMixin, ListModelMixin, generics.GenericAPIView):
queryset = MyModel.objects.all()
serializer_class = MySerializer
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
In urls.py
from django.urls import path
from .views import MyView
urlpatterns = [
path('route_one', MyView.as_view(), name="my_view_detail")
]
Read:How to upload multiple files in django rest framework
read:django rest framework for multiple image upload
But still unable to follow as proper description is not given
hi,
i am creating a rest api and new to django rest framework. I need help with few points mentioned below:
How to create Foreign key correctly.I have two tables one where images will be uploaded and one where data will be saved, i want id of these two tables should be foreign key so that when i select data from table 1 i can make query and get images related to id of table 1 from images table
I have created serializers but they say when i run my code to check errors using serializers.error
{'image': ['Incorrect type. Expected pk value, received bytes.'], 'img_id':
['Invalid pk "1" - object does not exist.']}
I am writing a post api to i need to save data and images first
How can i achieve this
my code
models
from django.db import models
# Create your models here.
class ImageModels(models.Model):
media = models.ImageField(upload_to="images")
class categoryRegistration(models.Model):
name = models.CharField(max_length=100)
image=models.ManyToManyField(ImageModels,related_name="file_content",blank=True,null=True)
description = models.TextField()
price = models.IntegerField()
img_id = models.ForeignKey(ImageModels,on_delete=models.CASCADE)
serializer
from rest_framework import serializers
from apps.categorymanagement.models import categoryRegistration
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = categoryRegistration
fields = ("id",'name', 'image', 'description', 'price',"img_id")
extra_kwargs = {
"image":{
"required":False,
},
}
urls:
from django.conf.urls import url
from apps.categorymanagement import views
urlpatterns = [
url( r'^object/categories$',views.category_list ,name="categoryList"),
url( r'^categories/data/(?P<pk>[0-9]+)$',views.category_detail,name="categoryDetails" ),
url( r'^categories/released$',views.category_released,name="categoryReleased" )
]
views:
from django.http.response import JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework.response import Response
from rest_framework import status
from apps.categorymanagement.models import ImageModels, categoryRegistration
from apps.categorymanagement.serializers import CategorySerializer
from rest_framework.decorators import api_view
# all the views written here are fuctions based
#api_view(['GET','POST','DELETE'])
def category_list(request):
# get list of all categories
if request.method=="POST":
files = request.FILES.getlist("file_content")
form_data = {}
form_data["name"] = request.data["name"]
form_data["description"] = request.data["description"]
form_data["price"] = request.data["price"]
form_data["img_id"] = request.data["img_id"]
for images in files:
form_data["image"] = images
serializer = CategorySerializer(data=form_data)
print(serializer.is_valid())
print(serializer.errors)
return Response('ok')
I'm trying to create a simple model Node and a simple web page that shows all of my nodes in a list. But it seems not working and everytime I change the code I got a new error. So I gave up and came to here.This is what I did:
I created a Node model:
class Node(models.Model):
ID = models.DecimalField(max_digits=9, decimal_places=6)
nb_solenoid = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
connexion = models.CharField(max_length=255)
def get_absolute_url(self):
return reverse("node:index", kwargs={"id": self.id})
with this form:
class NodeForm(forms.ModelForm):
ID = forms.DecimalField(initial=0)
nb_solenoid = forms.DecimalField(initial=1)
connexion = forms.CharField(required=False,
widget=forms.Textarea(
attrs={
"placeholder": "type of connexion"
}))
class Meta:
model = Node
fields = [
'ID',
'nb_solenoid',
'connexion'
]
And this is my views.py:
def index(request):
queryset = Node.objects.all()
context = {
"object_list": queryset
}
return render(request, "node/index.html", context)
This is my code in urls.py:
urlpatterns = [path('', views.index, name='index')]
When I call this url: http://localhost:8000/node I get this error now:
NoReverseMatch at /node
Reverse for 'index' with keyword arguments '{'id': 1}' not found. 1 pattern(s) tried: ['node$']
What is a NoReverseMatch error and how do I fix my problem? Let me say that I'm a Django beginner developer.
Thank you.
The issue is that your named url path node:index takes no arguments (presumably because that view is just listing out all the nodes, not a specific node), yet your model's get_absolute_url is trying to reverse the pattern with a kwarg of id. The core problem is your get_absolute_url method; however, you really probably also would benefit from just using class based generic views:
urls.py:
urlpatterns = [
path('nodes/', NodeList.as_view(), name="node-list"),
path('node/<id>/', NodeDetail.as_view(), name="node-detail")
]
view.py:
from django.views.generic import ListView, DetailView
from .models import Node
class NodeList(ListView):
model = Node
class NodeDetail(DetailView):
model = Node
models.py:
class Node(models.Model):
<snip>
def get_absolute_url(self):
return reverse("node-detail", kwargs={"id": self.id})
I really should have mentioned, documentation for class based generic views are at: https://docs.djangoproject.com/en/2.1/topics/class-based-views/generic-display/