AttributeError: 'Post' object has no attribute 'post_image' - python

I am using DRF and Django(4.0) to make posts in a Instagram Clone. The models of the following are available below. I have successfully implemented post request, but am having problems implementing get request.
I have tried to nest two serializer inside the PostViewSerializer to serialize the data. However I am getting the following error when I do a get request.
Got AttributeError when attempting to get a value for field 'post_image' on serializer 'PostViewSerializer'.
The serializer field might be named incorrectly and not match any attribute or key on the `Post` instance.
Original exception text was: 'Post' object has no attribute 'post_image'.
Now, I should tell you that there is not requirement that the post should contain atleast one image or video it could contain entirely either videos or posts. So, could that be the cause of the above error. If so, how can I solve it?
#models.py
class Post(Authorable, Model):
created_at = models.DateTimeField(default=timezone.now)
caption = TextField(max_length=350)
class Images(Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
images = models.FileField(upload_to="images/")
class Videos(Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
videos = models.FileField(upload_to="videos/")
#behaviours.py
class Authorable(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
abstract = True
def get_user(self):
return self.user.id
#serializers.py
class ImageViewSerializer(serializers.ModelSerializer):
class Meta:
model = Images
fields = ['images']
class VideoViewSerializer(serializers.ModelSerializer):
class Meta:
model = Videos
fields = [ 'videos']
class PostViewSerializer(serializers.ModelSerializer):
post_image = ImageViewSerializer()
post_video = VideoViewSerializer()
class Meta:
model = Post
fields = ['post_image', 'post_video', 'caption','user']
class PostUpload(APIView):
permission_classes = [IsAuthenticated]
parser_classes = [MultiPartParser, FormParser]
serializer_class = PostSerializer
def get(self, request):
user = request.user
serializer = PostViewSerializer(Post.objects.filter(user=user), many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
Edit 1:(With Full Traceback Error)
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/api/user/post/
Django Version: 4.0
Python Version: 3.8.10
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework_simplejwt',
'core',
'authentication',
'socialuser']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\fields.py", line 457, in get_attribute
return get_attribute(instance, self.source_attrs)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\fields.py", line 97, in get_attribute
instance = getattr(instance, attr)
During handling of the above exception ('Post' object has no attribute 'images'), another exception occurred:
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\django\views\generic\base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\suyas\Desktop\Memestagram\socialuser\views.py", line 22, in get
return Response(serializer.data, status=status.HTTP_200_OK)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\serializers.py", line 768, in data
ret = super().data
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\serializers.py", line 253, in data
self._data = self.to_representation(self.instance)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\serializers.py", line 686, in to_representation
return [
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\serializers.py", line 687, in <listcomp>
self.child.to_representation(item) for item in iterable
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\serializers.py", line 509, in to_representation
attribute = field.get_attribute(instance)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\fields.py", line 490, in get_attribute
raise type(exc)(msg)
Exception Type: AttributeError at /api/user/post/
Exception Value: Got AttributeError when attempting to get a value for field `post_image` on serializer `PostViewSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Post` instance.
Original exception text was: 'Post' object has no attribute 'images'.
My Serializer
class PostViewSerializer(serializers.ModelSerializer):
# access ForeignKey in reverse 🖟
post_image = ImageViewSerializer(source='images', many=True)
post_video = VideoViewSerializer(source='videos', many=True)
class Meta:
model = Post
fields = ['post_image', 'post_video', 'caption','user']

There is no ImageField, ForeignKey, ManyToManyField, etc. with post_image as name. You can access the images with .images. This thus means that you use this as source:
class PostViewSerializer(serializers.ModelSerializer):
# access ForeignKey in reverse 🖟
post_image = ImageViewSerializer(source='images_set', many=True)
post_video = VideoViewSerializer(source='videos_set', many=True)
class Meta:
model = Post
fields = ['post_image', 'post_video', 'caption','user']

Related

Manager isn't available; 'auth.User' has been swapped for 'accounts.User'

I have created a custom user model 'User' and have declared in settings.py as AUTH_USER_MODEL
Also i have two other models consumer and workman which has an onetoone relation with my custom user.
i created two forms for registering customer and workman but as i fill form(it doesnt even check validation) and submit, it says: Manager isn't available; 'auth.User' has been swapped for 'accounts.User'
models.py:
from django.contrib.auth.models import AbstractUser
from django.contrib.auth import get_user_model
# Create your models here.
class User(AbstractUser):
class Types(models.TextChoices):
CONSUMER = "CONSUMER" , "Consumer"
WORKMAN = "WORKMAN" , "Workman"
type = models.CharField(max_length=20,choices=Types.choices,default=Types.WORKMAN)
is_consumer = models.BooleanField(default=False)
is_workman = models.BooleanField(default=False)
class Consumer(models.Model):
user = models.OneToOneField(get_user_model(),on_delete=models.CASCADE,primary_key=True)
location = models.CharField(max_length=100)
class Workman(models.Model):
user = models.OneToOneField(get_user_model(),on_delete=models.CASCADE,primary_key=True)
contact = models.CharField(max_length=100)
views.py:
from .forms import ConsumerCreationForm, WorkmanCreationForm
from .models import Workman,Consumer
class consumersignupview(CreateView):
model = Consumer
form_class = ConsumerCreationForm
template_name = 'accounts/register.html'
success_url = '/'
class workmansignupview(CreateView):
model = Workman
form_class = WorkmanCreationForm
template_name = 'accounts/register.html'
success_url = '/'
forms.py:
from django.contrib.auth.forms import UserCreationForm
from django import forms
from .models import Consumer,Workman
class ConsumerCreationForm(UserCreationForm):
location = forms.CharField( max_length=100, required=False)
class meta(UserCreationForm.Meta):
model = Consumer
class WorkmanCreationForm(UserCreationForm):
contact = forms.CharField(max_length=100)
class meta(UserCreationForm.Meta):
model = Workman
error:
full traceback:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/account/wregister/
Django Version: 3.2.9
Python Version: 3.8.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts.apps.AccountsConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "F:\Project Work\Proxy-Model\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "F:\Project Work\Proxy-Model\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "F:\Project Work\Proxy-Model\venv\lib\site-packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "F:\Project Work\Proxy-Model\venv\lib\site-packages\django\views\generic\base.py", line 98, in dispatch
return handler(request, *args, **kwargs)
File "F:\Project Work\Proxy-Model\venv\lib\site-packages\django\views\generic\edit.py", line 172, in post
return super().post(request, *args, **kwargs)
File "F:\Project Work\Proxy-Model\venv\lib\site-packages\django\views\generic\edit.py", line 141, in post
if form.is_valid():
File "F:\Project Work\Proxy-Model\venv\lib\site-packages\django\forms\forms.py", line 175, in is_valid
return self.is_bound and not self.errors
File "F:\Project Work\Proxy-Model\venv\lib\site-packages\django\forms\forms.py", line 170, in errors
self.full_clean()
File "F:\Project Work\Proxy-Model\venv\lib\site-packages\django\forms\forms.py", line 374, in full_clean
self._post_clean()
File "F:\Project Work\Proxy-Model\venv\lib\site-packages\django\contrib\auth\forms.py", line 117, in _post_clean
super()._post_clean()
File "F:\Project Work\Proxy-Model\venv\lib\site-packages\django\forms\models.py", line 413, in _post_clean
self.instance.full_clean(exclude=exclude, validate_unique=False)
File "F:\Project Work\Proxy-Model\venv\lib\site-packages\django\db\models\base.py", line 1223, in full_clean
self.clean()
File "F:\Project Work\Proxy-Model\venv\lib\site-packages\django\contrib\auth\models.py", line 371, in clean
self.email = self.__class__.objects.normalize_email(self.email)
File "F:\Project Work\Proxy-Model\venv\lib\site-packages\django\db\models\manager.py", line 187, in __get__
raise AttributeError(
Exception Type: AttributeError at /account/wregister/
Exception Value: Manager isn't available; 'auth.User' has been swapped for 'accounts.User'
This error is a repeat of this issue. You are likely importing the wrong user model somewhere.

django Type error 'Bank' model object is not iterbale

i am trying to create list and detail api view. I have database with over 100K object
model.py
from django.db import models
# Create your models here.
class Banks(models.Model):
name = models.CharField(max_length=49, blank=True, null=True)
id = models.BigIntegerField(primary_key=True)
class Meta:
managed = False
db_table = 'banks'
class Branches(models.Model):
ifsc = models.CharField(primary_key=True, max_length=11)
bank = models.ForeignKey(Banks, models.DO_NOTHING, blank=True, null=True)
branch = models.CharField(max_length=250, blank=True, null=True)
address = models.CharField(max_length=250, blank=True, null=True)
city = models.CharField(max_length=50, blank=True, null=True)
district = models.CharField(max_length=50, blank=True, null=True)
state = models.CharField(max_length=26, blank=True, null=True)
class Meta:
managed = False
db_table = 'branches'
serializers.py
from rest_framework import serializers
from .models import Branches, Banks
class BankSerializer(serializers.ModelSerializer):
class Meta:
model = Banks
fields= ['name', 'id']
class BranchSerializer(serializers.ModelSerializer):
bank = BankSerializer(many=True,read_only=True)
class Meta:
model = Branches
fields= ['ifsc','bank','branch','address','city','district','state']
views.py
from rest_framework import viewsets
from .serializers import BranchSerializer
from rest_framework import viewsets
class BankViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed.
"""
queryset = Branches.objects.all()
serializer_class = BranchSerializer
I tried using .get_queryset(), .filter() in place of .all() but its still throwing error
error datail
Request Method: GET
Request URL: http://127.0.0.1:8000/bankdetailapi/
Django Version: 3.2.3
Python Version: 3.9.5
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'api',
'rest_framework',
'corsheaders',
'django_filters']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "C:\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python39\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Python39\lib\site-packages\rest_framework\viewsets.py", line 125, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Python39\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "C:\Python39\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Python39\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "C:\Python39\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Python39\lib\site-packages\rest_framework\mixins.py", line 46, in list
return Response(serializer.data)
File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 745, in data
ret = super().data
File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 246, in data
self._data = self.to_representation(self.instance)
File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 663, in to_representation
return [
File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 664, in <listcomp>
self.child.to_representation(item) for item in iterable
File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 515, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 663, in to_representation
return [
Exception Type: TypeError at /bankdetailapi/
Exception Value: 'Banks' object is not iterable
i also made sure that i am not making any typo. and most of the solutions i found on stack is about replacing .all() method with .get_queryset or .filter which didnt work for me.
i registered my models in admin.py its visible through admin
Remove many=True in serializer. ForeignKey links to a single Banks instance, therefore it is not many.
class BranchSerializer(serializers.ModelSerializer):
bank = BankSerializer(read_only=True)
class Meta:
model = Branches
fields= ['ifsc','bank','branch','address','city','district','state']
extra_kwargs = {
'bank': {'allow_null': True, 'required': False},
}
The problem is in BankSerializer, which tries to fetch all banks with reference to Branch instance:
bank = BankSerializer(many=True,read_only=True)
Your Branch model has FK reference to Banks, so there can only be one. You can fix the error if you remove many=true:
bank = BankSerializer(read_only=True)

RelatedObjectDoesNotExist at /profiles/user-follow-feed/ User has no user

Well i am just trying to show feed back of the following users but got an error:RelatedObjectDoesNotExist at /profiles/user-follow-feed/
User has no user. I don't understand how can i fix it. Need help to fix it out. many thanks in advance.
views.py
class FolloweHomeView(View):
def get(self, request, *args, **kwargs):
user = request.user.userprofile
is_following_user_ids = [x.user.id for x in user.follower.all()]
qs = Post.objects.filter(username__id__in=is_following_user_ids).order_by("-create_date")[:3]
return render(request, "profiles/follower_home_feed.html", {'object_list': qs})
models.py
class ProfileManager(models.Manager):
def toggle_follow(self, request_user, username_to_toggle):
profile_ = UserProfile.objects.get(user__username__iexact=username_to_toggle)
user = request_user
is_following = False
if user in profile_.follower.all():
profile_.follower.remove(user)
else:
profile_.follower.add(user)
is_following = True
return profile_, is_following
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
follower = models.ManyToManyField(User, related_name ='is_following',blank=True,)
avatar = models.ImageField(("Avatar"), upload_to='displays', default = '1.jpg',height_field=None, width_field=None, max_length=None,blank = True)
create_date = models.DateField(auto_now_add=True,null=True)
objects = ProfileManager()
def __str__(self):
return f'{self.user.username}'
traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/profiles/user-follow-feed/
Django Version: 3.0.3
Python Version: 3.8.3
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bootstrap3',
'accounts',
'posts',
'profiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\AHMED\anaconda3\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\AHMED\anaconda3\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\AHMED\grapPub\grabpublic\profiles\views.py", line 99, in get
is_following_user_ids = [x.user.id for x in user.follower.all()]
File "C:\Users\AHMED\grapPub\grabpublic\profiles\views.py", line 99, in <listcomp>
is_following_user_ids = [x.user.id for x in user.follower.all()]
File "C:\Users\AHMED\anaconda3\lib\site-packages\django\db\models\fields\related_descriptors.py", line 420, in __get__
raise self.RelatedObjectDoesNotExist(
Exception Type: RelatedObjectDoesNotExist at /profiles/user-follow-feed/
Exception Value: User has no user.
if more detail is require than tell me i will update my question with that information
The follower is a ManyToManyField to the User model, so the x in the list comprehension is a User object:
is_following_user_ids = [x.id for x in user.follower.all()]
You however do not need to perform this kind of logic, you can directly filter with:
qs = Post.objects.filter(
username__user__is_following__user=request.user
).order_by('-create_date')[:3]
this will query the Post objects in a single query.
Note: A ForeignKey does not store the string representation (or name) of the
referenced object in the column, it stores the primary key of the record it
references in a column with an _id suffix to a ForeignKey field. Therefore
ForeignKeys usually do not end with a name suffix. You might want to
consider renaming the username field to author.
Note: You can limit views to a class-based view to authenticated users with the
LoginRequiredMixin mixin [Django-doc].

Django AssertionError at url

While learning Django rest framework, I got a AssertionError at /tasks/1 error
Expected view TaskDetail to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly.
My model.py
class Task(models.Model):
owner=models.ForeignKey('auth.User',related_name='tasks')
completed=models.BooleanField(default=False)
title=models.CharField(max_length=100)
description=models.TextField()
serializer.py
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
read_only=('owner.username',)
fields=('title','description','completed','owner.username')
permission.py
class IsOwnerOrReadOnly(BasePermission):
def has_object_permission(self, request, view, obj):
if request.method is SAFE_METHODS:
return True
return obj.owner==request.user
views.py
class TasksMixins(object):
queryset = Task.objects.all()
serializer_class=TaskSerializer
permission_classes=(IsOwnerOrReadOnly,)
def pre_save(self,obj):
obj.owner=self.request.user
class TaskList(TasksMixins,ListCreateAPIView):
pass
class TaskDetail(TasksMixins,RetrieveUpdateDestroyAPIView):
pass
Urls.py
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^tasks/$', views.TaskList.as_view(), name='task_list'),
url(r'^tasks/(?P<id>[0-9]+)$', views.TaskDetail.as_view(), name='task_detail')
]
Traceback
Traceback (most recent call last):
File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/rest_framework/views.py", line 466, in dispatch
response = self.handle_exception(exc)
File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/rest_framework/views.py", line 463, in dispatch
response = handler(request, *args, **kwargs)
File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/rest_framework/generics.py", line 286, in get
return self.retrieve(request, *args, **kwargs)
File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/rest_framework/mixins.py", line 56, in retrieve
instance = self.get_object()
File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/rest_framework/generics.py", line 93, in get_object
(self.__class__.__name__, lookup_url_kwarg)
AssertionError: Expected view TaskDetail to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly.
When ever I navigate to the link I get this error
Any help is much appreciated...Thanks in advace
error image
If you want to target by 'pk', just rename id -> pk into your url.py:
url(r'^tasks/(?P<pk>[0-9]+)$', views.TaskDetail.as_view(), name='task_detail')
If you want to target by other field than pk,, you have to adjust the url.py, the view.py AND the serializer.py precising a lookup_field (that can be Nested) for example, it could be for you.
url.py:
url(r'^tasks/(?P<owner__username>[0-9]+)$', views.TaskDetail.as_view(), name='task_detail')
view.py:
class TasksMixins(object):
queryset = Task.objects.all()
serializer_class=TaskSerializer
permission_classes=(IsOwnerOrReadOnly,)
lookup_field = 'owner__username'
serializer.py
class TaskSerializer(serializers.ModelSerializer):
owner = serializers.SlugRelatedField(slug_field='username',many=False, read_only=True)
class Meta:
model = Task
fields='__all__'
lookup_field = 'owner__username'

django 'Commande' object has no attribute '__name_

Hi stackoverflow people,
In my project i try to code a view which will manage am external api which will be used to fetch some datas, present them and store them in a database.
When i try to access to my view, i encounter the following error
Traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/commande/recherche
Django Version: 1.7.1
Python Version: 3.4.2
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'commands')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
87. response = middleware_method(request)
File "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/middleware/common.py" in process_request
72. if (not urlresolvers.is_valid_path(request.path_info, urlconf) and
File "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/core/urlresolvers.py" in is_valid_path
619. resolve(path, urlconf)
File "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/core/urlresolvers.py" in resolve
494. return get_resolver(urlconf).resolve(path)
File "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/core/urlresolvers.py" in resolve
345. sub_match = pattern.resolve(new_path)
File "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/core/urlresolvers.py" in resolve
345. sub_match = pattern.resolve(new_path)
File "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/core/urlresolvers.py" in resolve
224. return ResolverMatch(self.callback, args, kwargs, self.name)
File "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/core/urlresolvers.py" in callback
231. self._callback = get_callable(self._callback_str)
File "/home/user/.virtualenvs/commands-project/lib/python3.4/functools.py" in wrapper
434. result = user_function(*args, **kwds)
File "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/core/urlresolvers.py" in get_callable
97. mod = import_module(mod_name)
File "/home/user/.virtualenvs/commands-project/lib/python3.4/importlib/__init__.py" in import_module
109. return _bootstrap._gcd_import(name[level:], package, level)
File "/home/user/workspace/Python/commands-project/project/commands/views.py" in <module>
6. from .form import CommandesForm, CommandeForm
File "/home/user/workspace/Python/commands-project/project/commands/form.py" in <module>
11. class CommandeForm(forms.ModelForm):
File "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/forms/models.py" in __new__
293. opts.model.__name__)
Exception Type: AttributeError at /commande/recherche
Exception Value: 'Commande' object has no attribute '__name__'
My models.py :
from django.db import models
class Client(models.Model):
client = models.IntegerField(null=True)
class Commandes(models.Model):
date_debut = models.DateField()
date_fin = models.DateField()
id_groups = models.CharField(max_length=100)
id_client = models.ForeignKey(Client)
class Commande(models.Model):
id_flux = models.CharField(max_length=100, null=True, blank=True)
id_commande = models.CharField(max_length=100, null=True, blank=True)
id_client = models.ForeignKey(Client)
My views.py :
from django.shortcuts import render
from http.client import HTTPConnection
from urllib.parse import urlparse, urlunparse
from .form import CommandesForm, CommandeForm
import requests
def resultat(request):
return render(request, 'commands/resultat.html')
def recherche(request):
if request.method == 'POST':
if 'Commandes' in request.POST:
pass
if 'Commande' in request.POST:
pass
else:
formCommandes = CommandesForm()
formCommande = CommandeForm()
return render(request, 'commands/recherche.html', {'formCommandes': formCommandes })
And my form.py:
from django import forms
from .models import Commande, Commandes
class CommandesForm(forms.ModelForm):
class Meta:
model = Commandes()
fields = ('date_debut', 'date_fin', 'id_groups')
class CommandeForm(forms.ModelForm):
class Meta:
model = Commande()
fields = ('date_debut', 'date_fin', 'id_groups', 'id_client', 'id_flux',
'id_commande')
This is the following exception that i need to manage :
'Commande' object has no attribute 'name'
I know that the 'name' attribute is in the class not the instance.
The fact that i can't figure out is, why the exception is raise with 'Commande' object and not 'Commands' object

Categories