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
Related
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.
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 am using djoser's create token end point to login user but i am getting following error.
I have tried google search but could not find any useful answer.
UPDATE
I have customized user model to add an extra field while registering user.
here is my models.py
from django.db import models
from custom_user.models import AbstractEmailUser
class UserProfile(AbstractEmailUser):
account_address = models.CharField(max_length=100, blank=True)
name = models.CharField(max_length=30, blank=True)
and this is my serializer.py
from djoser.serializers import UserCreateSerializer as BaseUserRegistrationSerializer
from rest_framework import serializers
class UserRegistrationSerializer(BaseUserRegistrationSerializer):
advertisements = serializers.HyperlinkedRelatedField(many=True, view_name='advertisement-detail', read_only=True)
class Meta(BaseUserRegistrationSerializer.Meta):
fields = ('id', 'email', 'advertisements', 'name', 'account_address', 'password')
and urls.py
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
urlpatterns = [
url(r'^account/', include('djoser.urls')),
url(r'^account/', include('djoser.urls.authtoken'))
]
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)