I am creating one crud operation in django restframework and I have created project name "portfolio" and app "stock" and store in postgres database Here is my code.
stock.models.py
from django.db import models
class Stocks(models.Model):
Name = models.CharField(max_length=50)
Number_of_Share = models.IntegerField()
Unit_Price = models.IntegerField()
ShareValue=models.IntegerField()
Total_Share_Value= models.IntegerField()
stock.serializers.py
from rest_framework import serializers
from .models import Stocks
class StocksSerializer(serializers.ModelSerializer):
class Meta:
model =Stocks
fields = '__all__'
stock.viewset.py
from rest_framework import viewsets
from .models import Stocks
from . import serializers
class StockViewset(viewsets.ModelViewSet):
queryset = Stocks.objects.all()
serializer_class = serializers.StocksSerializer
portfolio.router.py
from stock.viewsets import StockViewset
from rest_framework import routers
router = routers.DefaultRouter()
router.register('Stocks',StockViewset)
portfolio.urls.py
from django.urls import path, include
from .router import router
urlpatterns = [
# path('admin/', admin.site.urls),
path('portfolio/',include(router.urls))
]
But I am facing this error.
Exception Type: ProgrammingError
Exception Value:
relation "stock_stocks" does not exist
LINE 1: ...reValue", "stock_stocks"."Total_Share_Value" FROM "stock_sto...
Please help me solve this error.
Related
I'm struggling to fix an error that doesn't allow me to access my /api/lead/ URL, as I keep getting an error "module object is not callable. Within my DjangoApp project, I have one other folder named api, and one other folder with the standard name of the project, which in my case is "DjangoApp".
api/models.py :
from django.db import models
# Create your models here.
class Lead(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
message = models.CharField(max_length=300)
created_at = models.DateTimeField(auto_now_add=True)
api/LeadListCreate.py :
from .models import Lead
from api import LeadSerializer
from rest_framework import generics
class LeadListCreate(generics.ListCreateAPIView):
queryset = Lead.objects.all()
serializer_class = LeadSerializer
api/LeadSerializer.py :
from rest_framework import serializers
from .models import Lead
class LeadSerializer(serializers.ModelSerializer):
class Meta:
model = Lead
fields = ('id', 'name', 'email', 'message')
api/urls.py :
from django.urls import path
from . import views
urlpatterns = [
path('api/lead/', views.LeadListCreate.as_view() ),
]
DjangoApp/urls.py :
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('api.urls')),
]
the error is very generic, and several things could be happening, I recommend running your application in debug mode and doing it step by step until you find where it is breaking.
vscode and pycharm have this tool
I am trying to implement Rest api using Django framework. But when I click on the url on the default index page it gives me an assertion error at/languages/ Class LanguageSerializer missing meta.model attribute
I made all the migrations after changes in models.py but it did nothing
urls.py
from django.urls import path, include
from . import views
from rest_framework import routers
router = routers.DefaultRouter()
router.register('languages', views.LanguageView)
urlpatterns = [
path('', include(router.urls))
]
models.py
from django.db import models
class Language(models.Model):
name = models.CharField(max_length=50)
paradigm = models.CharField(max_length=50)
serializers.py
from rest_framework import serializers
from .models import Language
class LanguageSerializer(serializers.ModelSerializer):
class Meta:
fields = ('id', 'name', 'paradigm')
views.py
from django.shortcuts import render
from rest_framework import viewsets
from .models import Language
from .serializers import LanguageSerializer
class LanguageView(viewsets.ModelViewSet):
queryset = Language.objects.all()
serializer_class = LanguageSerializer
I have no clue where am I going wrong
You need to specify what model you want to serialize in the Meta class of your serializer, like:
from rest_framework import serializers
from .models import Language
class LanguageSerializer(serializers.ModelSerializer):
class Meta:
model = Language # specify the model
fields = ('id', 'name', 'paradigm')
otherwise the serializer can not determine the fields of that model, and how it will serialize the data from these fields.
I've tried to use custom user model instead of default user.
My Django project structure is below.
Project name : project_rest
App name : app_rest
To make it happen, I refer https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#substituting-a-custom-user-model
[settings.py]
AUTH_USER_MODEL = 'app_rest.User'
[models.py]
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from django.conf import settings
from django.contrib.auth.models import AbstractUser
#receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
class User(AbstractUser):
username = models.CharField(unique=True, null=False, max_length=254)
password = models.CharField(max_length=200)
[serializers.py]
from app_rest.models import User
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'password')
[views.py]
from django.shortcuts import render
from app_rest.serializers import UserSerializer
from app_rest.models import User
from rest_framework import viewsets
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
[urls.py]
from django.conf.urls import url, include
from app_rest import views
from rest_framework import routers
from django.contrib import admin
from rest_framework.authtoken import views as rest_views
router = routers.DefaultRouter()
router.register(r'user', views.UserViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^token-auth/', rest_views.obtain_auth_token),
url(r'^admin/', admin.site.urls),
]
I seems work properly, But when I delete user, It throws error.
IntegrityError at /admin/app_rest/user/1/delete/ (1452, 'Cannot add or
update a child row: a foreign key constraint fails
('rest'.'django_admin_log', CONSTRAINT
'django_admin_log_user_id_c564eba6_fk_auth_user_id' FOREIGN KEY
('user_id') REFERENCES 'auth_user' ('id'))')
How can I solve this issue?
The error is pretty self explanatory. The record you are trying to delete is related to another one by a foreign key and it cannot be deleted as it would break referential integrity.
You need to alter that id with something like ON DELETE CASCADE or its equivalent, or allow the user to be null on the related table (if that's possible).
I am new to django so i want to know how to write urls.py for a project.
I want to make backend api for inventory management system.
When i type localhost:8000/inventory_backend/dep/, I am having following error:
**Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
The current path, inventory_backend/dep/, didn't match any of these.
My code for mysite/urls.py**
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^inventory_backend/', include('inventory_backend.urls')
),
url(r'^admin/', admin.site.urls) ,
]
inventory_backend/urls.py:
from inventory_backend.views import DepartmentsView,InventoriesView
from rest_framework import routers
router = routers.SimpleRouter()
router.register(r'dep/',DepartmentsView )
router.register(r'inv/',InventoriesView )
urlpatterns = router.urls
serializers.py
from rest_framework import serializers
from inventory_backend.models import Departments,Inventories
class DepartmentsSerializer(serializers.ModelSerializer):
class Meta:
model : Departments
fields: ('id','name')
class InventoriesSerializer(serializers.ModelSerializer):
dept = DepartmentsSerializer(many=True)
class Meta:
model : Inventories
fields : ('id','name','description','dept')
models.py
from django.db import models
class Departments(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class Inventories(models.Model):
name = models.CharField(max_length=200)
description = models.CharField(max_length=200)
dept = models.ManyToManyField(Departments)
def __str__(self):
return self.name
views.py
from rest_framework import viewsets
from inventory_backend.models import Inventories,Departments
from inventory_backend.serializers import InventoriesSerializer,
DepartmentsSerializer
class DepartmentsView(viewsets.ModelViewSet):
queryset = Departments.objects.all();
serializer_class = DepartmentsSerializer;
class InventoriesView(viewsets.ModelViewSet):
queryset = Inventories.objects.all();
serializer_class = InventoriesSerializer;
Change your inventory_backend.urls.py,
urlpatterns = [
url(r'^', include(router.urls))
]
I am new to Django Rest Framework and am struggling to get my serialisations to work correctly for a foreignkey relationship between two models. I have tried to reduce my setup down to be as simple as possible but I still can't understand how it is supposed to work. I am trying to use HyperlinkedModelSerializer so (from the docs) 'that it uses hyperlinks to represent relationships'. When I try to visit the url for either the list or detail view for {model X} on the test server I get:
'Could not resolve URL for hyperlinked relationship using view name
"{model Y}-detail". You may have failed to include the related model
in your API, or incorrectly configured the lookup_field attribute on
this field.'
What am I doing wrong?
My models:
from django.db import models
class Project(models.Model):
name = models.CharField(max_length=50)
description = models.TextField()
class ProjectPhoto(models.Model):
project = models.ForeignKey(
Project, related_name='photos', on_delete=models.CASCADE
)
image = models.ImageField()
caption = models.CharField(max_length=100)
date_added = models.DateTimeField(auto_now_add=True)
My serializers
class ProjectSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Project
fields = ('name', 'description', 'photos')
class ProjectPhotoSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = ProjectPhoto
fields = ('image', 'caption', 'date_added', 'project'))
My views:
from rest_framework import viewsets
from projects.models import Project, ProjectPhoto
from projects.serializers import ProjectSerializer, ProjectPhotoSerializer
class ProjectViewSet(viewsets.ModelViewSet):
queryset = Project.objects.all().order_by('name')
serializer_class = ProjectSerializer
class ProjectPhotoViewSet(viewsets.ModelViewSet):
queryset = ProjectPhoto.objects.all().order_by('date_added')
serializer_class = ProjectPhotoSerializer
EDIT:
My urls:
from django.conf.urls import url, include
from rest_framework import routers
from projects import views
router = routers.DefaultRouter()
router.register(r'^projects', views.ProjectViewSet)
router.register(r'^project-photos', views.ProjectPhotoViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
]
these are then added in my main app urls.py file. I don't think this is problem as if I change the serializer to ModelSerializer then everything works fine.
I think your problem is in your urls.py file, see the code and picture
rest/urls.py file
from django.conf.urls import url, include
from rest_framework import routers
from .views import ProjectViewSet, ProjectPhotoViewSet
router = routers.SimpleRouter()
router.register(r'project', ProjectViewSet)
router.register(r'project-photo', ProjectPhotoViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
]
Principal urls.py file:
from django.conf.urls import url, include
from django.contrib import admin
from rest import urls as urls_rest
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^rest/', include(urls_rest)),
]
and other option, try to use this code in your serializers.py file:
from rest_framework import serializers
from .models import Project, ProjectPhoto
class ProjectPhotoSerializer(serializers.ModelSerializer):
class Meta:
model = ProjectPhoto
fields = ('image', 'caption', 'date_added', 'project')
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = ('name', 'description', 'photos')
depth = 2
You have 3 options to use serializers (see picture below)