Class-based view "has no attribute .as_view()" error - python

I'm following this tutorial, trying to make an API for my Products table.
Here's my .views/API/apitest.py view:
from my_app.views.API.serializers import ProductSerializer
from my_app.models import Product
from rest_framework import generics
class APITest(generics.ListAPIView):
model=Product
serializer_class=ProductSerializer
queryset = Product.objects.all()
The urls.py entry:
url(r'^API/products/$', views.API.apitest.as_view(), name='apitest')
That line gives an error: 'module' object has no attribute 'as_view'. I'm just trying to create a simple example for the moment, so there's no need for decorators. What causes this error? I'm using Django 1.9.2.

apitest is the module, you need to use as_view on the class
url(r'^API/products/$', views.API.apitest.APITest.as_view(), name='apitest')
Although it may be better to look into your imports
from myapp.views.API.apitest import APITest
url(r'^API/products/$', APITest.as_view(), name='apitest')

Related

Import models function

I created a models within my page but when I attempted to run the page I received an error response
celery_beat_1 | class ClassManager(models.Manager):
celery_beat_1 | NameError: name 'models' is not defined
I searched for fixes to this error online and most of the responses said to implement the
import from django.db import models
function. However, this is something I already have configured in my models page. Any idea on how to proceed forward?
You should import models from django in models.py.
from django.db import models
class MyModel(models.Model):
pass
You can check more information in django documentation itself:
https://docs.djangoproject.com/en/3.2/topics/db/models/#quick-example
You are importing the models in wrong way format, so you have to use -
from django.db import models
rather than using
import from django.db import models

Django Rest Framework ListCreateAPIView not checking has_object_permissions?

I've been trying to figure this out for almost a full day now, and I can't seem to figure out why has_object_permission method isn't called when the ListCreateAPIView is called in DRF. I've tried all the solutions I could find, but according to the docs check_object_permissions is called in this class already.
I know it has to be something stupid I'm missing. Code snippets are below, please help!
views.py:
from accountability.models import AccountabilityItem
from accountability.serializers import AccountabilityItemSerializer
from rest_framework import generics
from .permissions import InGroup
class AccountabilityItemListCreate(generics.ListCreateAPIView):
queryset = AccountabilityItem.objects.all()
serializer_class = AccountabilityItemSerializer
permission_classes = (InGroup,)
permissions.py:
from rest_framework import permissions
class InGroup(permissions.BasePermission):
"""
Custom permission to only allow owners of an object to edit it.
"""
def has_object_permission(self, request, view, obj):
print('Checking for object')
return False
Another note, I've added the has_permission method to the permissions.py file, and this method runs all the time no matter what.
Thanks!
Calling has_object_permission doesn't make sense for lists. It is intended for single instances.
What you want is to filter your list of objects so it only leaves those for which the user has some permissions. DjangoObjectPermissionsFilter does it but requires django-guardian. You might get a similar result but creating your own filtering class (sources for DjangoObjectPermissionsFilter)

FormFields for (Admin)Inlines || Can't import InlineModelAdmin

I want to catch up some extra information within my Django Admin through some extra Fields. I want to use inlines for that purpose.
I have:
class YourModelForm(forms.ModelForm):
slot_count_request = forms.IntegerField(label='#-slot-size', initial=4 )
class Card_Group_proxy_inline(admin.TabularInline):
model = SomeRandomModel
form = YourModelForm
This works fine for if I want to use a model within. I thought I can get rid of it, if I inherit from admin.InlineModelAdmin, but then I get an error:
AttributeError: module 'django.contrib.admin' has no attribute 'InlineModelAdmin'
The InlineModelAdmin class can be imported with:
from django.contrib.admin.options import InlineModelAdmin
However, I have not seen InlineModelAdmin used directly before. Usually, you would use admin.TabularInline or admin.StackedInline.

How to Lazy Load a model in a managers to stop circular imports?

In Django you can create managers for your models. I do this by added a new file called managers.py and in my model objects = MyManager().
To stop circular imports I do self.model. However, if I need to reference a different model in my manager i.e.
from models import SecondModel
second= SecondModel(name=test).save()
self.model(second=second)
I get the following error: ImportError: cannot import name SecondModel
So is there a way in Django to lazy load a model?
The currently accepted answer is deprecated as of Django 1.7; from this answer, you can adapt your code like this.
from django.apps import apps
class SomeModelManager(...):
...
def some_function(self):
model = apps.get_model(app_label='your_app', model_name='YourModel')
You have a few options:
1. Import by name
Django has a utility function for importing by string name so you don't need to import yourself. There are several methods available for this (see this question: Django: Get model from string?)
from django.db.models.loading import get_model
class SomeModelManager(...):
...
def some_function(self):
model = get_model('your_app', 'YourModel')
object = model()
2. Imports at the bottom
Add the import at the bottom of the managers.py file and make sure to simply import the module and not the models themselves.
So...
models.py:
import managers
class SomeModel(models.Model):
...
objects = managers.SomeModelManager()
managers.py
class SomeModelManager(...):
...
def some_function(self):
object = models.SomeOtherModel()
import models

Using Django JSON serializer for object that is not a Model

Is it possible to use Django serializer without a Model?
How it is done?
Will it work with google-app-engine?
I don't use Django framework, but since it is available, I would want to use its resources here and there.
Here is the code I tried:
from django.core import serializers
obj = {'a':42,'q':'meaning of life'}
serialised = serializers.serialize('json', obj)
this generates an error
ERROR ... __init__.py:385] 'str' object has no attribute '_meta'
Serializers are only for models. Instead you can use simplejson bundled with Django.
from django.utils import simplejson
json_str = simplejson.dumps(my_object)
Simplejson 2.0.9 docs are here.
The GQLEncoder class in this library can take a db.Model entity and serialize it. I'm not sure if this is what you're looking for, but it's been useful to me.

Categories