search using django filter - django

I am trying to perform search on name and email field.
For email field its giving an error "invalid literal for int() with base 10: 'abc#xyz.com'". but when I am using the user.id its giving correct result.
For name field, its giving Cannot resolve keyword 'first_name' into field.
How do i get it to work. Any help will be highly appreciated.
my two models are:
class publication(models.Model):
title = models.CharField(max_length=500)
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
....
class MyUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), max_length=254,
unique=True)
first_name = models.CharField(_('first name'), max_length=30,
blank=True)
last_name = models.CharField(_('last name'), max_length=30,
blank=True)
.....
My view:
def search(request):
result = publication.objects.all()
query = request.GET.get("query")
if query:
result = result.filter(
Q(title__icontains=query) |
Q(user__first_name__icontains=query) |
Q(user__email=query)
).distinct()
user_filter = UserFilter(request.GET, queryset=result)
return render(request, "search.html", {'filter': user_filter})
My filter:
class UserFilter(filters.FilterSet):
title = filters.CharFilter(lookup_expr='icontains')
first_name = filters.CharFilter(lookup_expr='iexact')
user = filters.CharFilter(lookup_expr='exact')
class Meta:
model = publication
fields = ['title', 'first_name', 'user']
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/views/generic/base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django_filters/views.py", line 66, in get
self.object_list = self.filterset.qs
File "/usr/local/lib/python2.7/dist-packages/django_filters/filterset.py", line 214, in qs
qs = filter_.filter(qs, value)
File "/usr/local/lib/python2.7/dist-packages/django_filters/filters.py", line 171, in filter
qs = self.get_method(qs)(**{'%s__%s' % (self.name, lookup): value})
File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/query.py", line 781, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/query.py", line 799, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/sql/query.py", line 1260, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/sql/query.py", line 1286, in _add_q
allow_joins=allow_joins, split_subq=split_subq,
File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/sql/query.py", line 1216, in build_filter
condition = lookup_class(lhs, value)
File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/lookups.py", line 24, in __init__
self.rhs = self.get_prep_lookup()
File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/fields/related_lookups.py", line 110, in get_prep_lookup
self.rhs = target_field.get_prep_value(self.rhs)
File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/fields/__init__.py", line 962, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'abc#xyz.com'

If you need to filter by relation model's field you can use name argument of filed class:
class UserFilter(filters.FilterSet):
title = filters.CharFilter(lookup_expr='icontains')
first_name = filters.CharFilter(name='user__first_name', lookup_expr='iexact')
user = filters.CharFilter(name='user__email', lookup_expr='exact')
See details here.
UPD
To filter full name try to implement custom method:
full_name = CharFilter(method='my_custom_filter')
def my_custom_filter(self, queryset, name, value):
first_name, last_name = value.split()
return queryset.filter(Q(user__first_name__icontains=first_name) | Q(user__last_name__icontains=last_name))

I use on my views.py for case search query on table blognews, for this code use for form post method search with name input keyword:
def list_content(request):
shelf = content.objects.all()
if(request.method=="POST"):
keyword=request.POST.get('keyword')
shelf=blogsnews.objects.filter(judul__icontains=keyword)
return render(request,'homepage/list_news.html',{'shelf':shelf})
for function filter "icontains or contains please visit docs django manual

Related

Django multiupload error: 'list' object has no attribute 'name'

I'm trying to use multiupload in django form for upload several images at once.
I'm using django ModelForm but when i'm calling form.is_valid() in function-base view or using generic.FormView, i'm getting 'list' object has no attribute 'name' error. in generic.FormView neither of form_valid and form_invalid methods aren't called. although when I use request.POST.get(some_data) it works without any errors but I want to use generic.FormView for some validations. I think the validation of the form makes the error happen.
so what should I do?
here is my code.
models.py
class Post(models.Model):
post_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True)
profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name="posts")
text = models.TextField(max_length=1000)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
...
class Image(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="images")
image = models.ImageField(upload_to="images/posts/")
forms.py
class PostForm(forms.ModelForm):
images = MultiImageField(min_num=1, max_num=3)
class Meta:
model = models.Post
fields = ("text", "images")
views.py
class CreatePostView(LoginRequiredMixin, generic.FormView):
template_name = "posts/post_create.html"
form_class = forms.PostForm
def get_success_url(self):
return redirect("profile", slug=self.request.kwargs.slug)
def form_valid(self, form):
...
# some codes
...
return super(CreatePostView, self).form_valid(form)
error:
Traceback (most recent call last):
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\generic\base.py", line 84, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\auth\mixins.py", line 73, in dispatch
return super().dispatch(request, *args, **kwargs)
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\generic\base.py", line 119, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\generic\edit.py", line 152, in post
if form.is_valid():
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\forms.py", line 205, in is_valid
return self.is_bound and not self.errors
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\forms.py", line 200, in errors
self.full_clean()
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\forms.py", line 433, in full_clean
self._clean_fields()
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\forms.py", line 443, in _clean_fields
value = field.clean(value, bf.initial)
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\fields.py", line 670, in clean
return super().clean(data)
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\fields.py", line 200, in clean
self.run_validators(value)
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\fields.py", line 185, in run_validators
v(value)
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\validators.py", line 611, in validate_image_file_extension
return FileExtensionValidator(allowed_extensions=get_available_image_extensions())(
File "C:\Users\asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\validators.py", line 576, in __call__
extension = Path(value.name).suffix[1:].lower()
Exception Type: AttributeError at /profile/ehsanadmin/post/create/
Exception Value: 'list' object has no attribute 'name'

Cannot resolve keyword 'user' into field. Choices are: create_account, email, full_name

Im Created 2 Models.
Account
UserProfil
First Of All, User Register email, fullname, password1, password2. The data Sending To Database in table Account.
Second, User Will Login, if success, he will go to dashboard. in dashboard have a profil Form.
In The Profil Form, He Will input data profil, likes number phone, birth date. etc. and will store in table UserProfil
All of data in UserProfil relationship with Account.
Im Try to create 'Profil Form'. Like This.
my Question is How To Put the data Full_Name in this form ?
i got Error Cannot resolve keyword 'user' into field. Choices are: create_account, email, full_name ...
authentication/models.py
class Account(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True)
full_name = models.CharField(max_length=150)
create_account = models.DateTimeField(default=timezone.now)
is_active = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_reviewer = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
objects = CustomAccountManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['full_name']
def __str__(self):
return self.full_name
dashboard/models.py
class UserProfil(models.Model):
jenis_kelamin_choice = (
('Pria', 'Pria'),
('Wanita', 'Wanita' ),
)
user = models.OneToOneField(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,)
nik = models.CharField(max_length=11, null=True, unique=True)
nidn = models.CharField(max_length=11, null=True, unique=True)
def __str__(self):
return str(self.user)
dashboard/views.py
class UserProfilFormView(CreateView):
template_name = 'dashboard/profil.html'
form_class = UserProfilForm
def form_valid(self, form):
userPofil = form.save(commit=False)
userPofil.user = Account.objects.get(user__full_name=self.request.user)
userPofil.save()
messages.success(self.request, 'Data Profil Berhasil Disimpan.')
print(self.request.user)
return super().form_valid(form)
File Traceback :
Internal Server Error: /dashboard/profil
Traceback (most recent call last):
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\views\generic\base.py", line 98, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\views\generic\edit.py", line 172, in post
return super().post(request, *args, **kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\views\generic\edit.py", line 142, in post
return self.form_valid(form)
File "D:\Project\hibahinternal\dashboard\views.py", line 26, in
form_valid
userPofil.user = Account.objects.get(user__full_name=self.request.user)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\query.py", line 424, in get
clone = self._chain() if self.query.combinator else self.filter(*args,
**kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\query.py", line 941, in filter
return self._filter_or_exclude(False, args, kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\query.py", line 961, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, args, kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\query.py", line 968, in
_filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\sql\query.py", line 1393, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\sql\query.py", line 1412, in _add_q
child_clause, needed_inner = self.build_filter(
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\sql\query.py", line 1286, in build_filter
lookups, parts, reffed_expression = self.solve_lookup_type(arg)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\sql\query.py", line 1112, in solve_lookup_type
_, field, _, lookup_parts = self.names_to_path(lookup_splitted,
self.get_meta())
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\sql\query.py", line 1539, in names_to_path
raise FieldError("Cannot resolve keyword '%s' into field. "
django.core.exceptions.FieldError: Cannot resolve keyword 'user' into
field. Choices are: create_account, email, full_name, groups, id,
is_active, is_admin, is_reviewer, is_staff, is_superuser, last_login,
logentry, password, user_permissions, userprofil
[20/Dec/2021 19:31:48] "POST /dashboard/profil HTTP/1.1" 500 136397
Thanks
Your Account has no user field, this also would not make much sense, since that is the user account. You do not need to make a query to the Account model anyway: request.user works with the user model, here account, so you can use request.user directly:
from django.contrib.auth.mixins import LoginRequiredMixin
class UserProfilFormView(LoginRequiredMixin, CreateView):
template_name = 'dashboard/profil.html'
form_class = UserProfilForm
def form_valid(self, form):
form.instance.user = request.user
messages.success(self.request, 'Data Profil Berhasil Disimpan.')
print(self.request.user)
return super().form_valid(form)
Note: You can limit views to a class-based view to authenticated users with the
LoginRequiredMixin mixin [Django-doc].

Django Rest Framework showing ValueError:Cannot use QuerySet for "Post": Use a QuerySet for "Account"

I am trying to list and paginate favourite post of users. I got a custom pagination snippet from so, which I am using here, But I am getting this error.
ValueError:Cannot use QuerySet for "Post": Use a QuerySet for "Account".
I guess, there are problems with my serializer or views. can anyone please help me fix this issue?
These are the codes:
serializers:
class PostSerializer(serializers.ModelSerializer):
user = serializers.ReadOnlyField(source='user.username')
post_date = serializers.ReadOnlyField()
comment_set = CommentSerializer(many=True)
class Meta:
model = Post
fields = ['id','title', 'post_date', 'user', 'image', 'comment_set']
class PostFavouriteListSerializer(serializers.ModelSerializer):
favourite = PostSerializer(many=True, read_only=True)
class Meta:
model = Post
fields = ['favourite',]
views
class CustomPaginator(PageNumberPagination):
page_size = 3
def generate_response(self, query_set, serializer_obj, request):
try:
page_data = self.paginate_queryset(query_set, request)
except NotFoundError:
return Response({"error": "No results found for the requested page"}, status=status.HTTP_400_BAD_REQUEST)
serialized_page = serializer_obj(page_data, many=True)
return self.get_paginated_response(serialized_page.data)
class FavouritePostAPIView(APIView):
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)
def get(self, request):
user = self.request.user
favourite_posts = Post.objects.filter(favourite=user.post_favourite.all())
paginator = CustomPaginator()
response = paginator.generate_response(post, PostFavouriteListSerializer, request)
return response
This is the Post model:
class Post(models.Model):
title = models.TextField(max_length=5000, blank=False, null=False)
image = models.ImageField(upload_to='posts/postimage/', null=True)
post_date = models.DateTimeField(auto_now_add=True, verbose_name="Date Posted")
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
slug = models.SlugField(blank=True, unique=True, max_length=255)
favourite = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='post_favourite', blank=True)
Traceback:
File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\views.py" in dispatch
505. response = self.handle_exception(exc)
File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\views.py" in handle_exception
465. self.raise_uncaught_exception(exc)
File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\views.py" in raise_uncaught_exception
476. raise exc
File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\views.py" in dispatch
502. response = handler(request, *args, **kwargs)
File "C:\danny\Project\posts\api\views.py" in get
186. favourite_posts = Post.objects.filter(favourite=user.post_favourite.all())
File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\manager.py" in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py" in filter
892. return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py" in _filter_or_exclude
910. clone.query.add_q(Q(*args, **kwargs))
File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\query.py" in add_q
1290. clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\query.py" in _add_q
1315. child_clause, needed_inner = self.build_filter(
File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\query.py" in build_filter
1224. self.check_related_objects(join_info.final_field, value, join_info.opts)
File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\query.py" in check_related_objects
1079. raise ValueError(
Exception Type: ValueError at /api/posts/posts/favourites/
Exception Value: Cannot use QuerySet for "Post": Use a QuerySet for "Account".
replace :
favourite_posts = Post.objects.filter(favourite=user.post_favourite.all())
paginator = CustomPaginator()
response = paginator.generate_response(post, PostFavouriteListSerializer, request)
by :
favourite_posts = user.post_favourite.all()
paginator = CustomPaginator()
response = paginator.generate_response(favourite_posts, PostSerializer, request)
the related m2m post_favourite is a queryset of post , not need to filter/get this, so you dont need PostFavouriteListSerializer
alternative can be this:
favourite_posts = Post.objects.filter(favourite=user)
you get all post with favourite have your user

Adding context to a Class Based View (detail view) geting an error get_context_data() got an unexpected keyword argument 'object'

I am trying to learn how to add a 2nd Context to a Class-Based view which has always been an issue for me and I can't get it right from the first time.
In my current project, I am trying to add a comment section to item detail view.
I am currently getting an error of get_context_data() got an unexpected keyword argument 'object'
which is from the item detail view as I indicated and I don't know who to fix it
Here is the item model:
class Item(models.Model):
title = models.CharField(max_length=100)
def __str__(self):
return self.title
here is the comment model:
class Comment(models.Model):
STATUS = (
('New', 'New'),
('True', 'True'),
('False', 'False'),
)
item = models.ForeignKey(Item, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="ItemComments")
subject = models.CharField(max_length=50, blank=True)
comment = models.CharField(max_length=250, blank=True)
status = models.CharField(max_length=10, choices=STATUS, default='New')
create_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '{} by {}'.format(self.subject, str(self.user.username))
class CommentForm(ModelForm):
class Meta:
model = Comment
fields = ['subject', 'comment']
here is the view:
class ItemDetailView(DetailView):
model = Item
template_name = "product.html"
def get_context_data(request, id):
context = super(ItemDetailView, request).get_context_data() <---------------- error from this line
context["comments"] = Comment.objects.filter(item_id=id, status='True')
return context
here is the add coment view
def addcomment(request,id):
url = request.META.get('HTTP_REFERER') # get last url
# return HttpResponse(url)
if request.method == 'POST': # check post
form = CommentForm(request.POST)
if form.is_valid():
data = Comment() # create relation with model
data.subject = form.cleaned_data['subject']
data.comment = form.cleaned_data['comment']
data.item_id = id
current_user = request.user
data.user_id = current_user.id
data.save() # save data to table
messages.success(request, "Your review has ben sent. Thank you for your interest.")
return HttpResponseRedirect(url)
return HttpResponseRedirect(url)
Here is the traceback
Traceback (most recent call last):
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\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\Desktop\Project 4.3\venv\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\Desktop\Project 4.3\venv\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\views\generic\detail.py", line 107, in get
context = self.get_context_data(object=self.object)
File "C:\Users\Ahmed\Desktop\Project 4.3\core\views.py", line 113, in get_context_data
context["comments"] = Comment.objects.filter(item_id=id, status='True')
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\query.py", line 892, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\query.py", line 910, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\sql\query.py", line 1290, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\sql\query.py", line 1315, in _add_q
child_clause, needed_inner = self.build_filter(
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\sql\query.py", line 1251, in build_filter
condition = self.build_lookup(lookups, col, value)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\sql\query.py", line 1116, in build_lookup
lookup = lookup_class(lhs, rhs)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\lookups.py", line 20, in __init__
self.rhs = self.get_prep_lookup()
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\fields\related_lookups.py", line 115, in get_prep_lookup
self.rhs = target_field.get_prep_value(self.rhs)
File "C:\Users\Ahmed\Desktop\Project 4.3\venv\lib\site-packages\django\db\models\fields\__init__.py", line 966, in get_prep_value
return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method'
The signature of get_context_data(...) method is wrong in your view. It should be as follows,
class ItemDetailView(DetailView):
model = Item
template_name = "product.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["comments"] = Comment.objects.filter(item=self.object, status='True')
return context

Added Many2Many now getting "ValueError: XXX needs to have a value for field "id" before this many-to-many relationship can be used"

I've read a bunch of similar sounding questions of SO, but somehow none of them have helped me solve my particular case. I added a ManyToManyField to represent "Likes" to my Photo model:
class Photo(TimestampModerated):
owner = models.ForeignKey('auth.User', related_name='photos', on_delete=models.CASCADE)
uuid = models.UUIDField(default=uuid4, editable=False)
slug = models.SlugField(max_length=80, editable=False)
title = models.CharField(max_length=80, blank=False, null=False)
description = models.TextField(verbose_name='description of entity', blank=True, null=True)
photo = models.ImageField(upload_to=user_directory_path, height_field="height", width_field="width", blank=True)
height = models.IntegerField(blank=True)
width = models.IntegerField(blank=True)
tags = TaggableManager(blank=True)
hash = models.CharField(max_length=64, unique=True, null=True)
size = models.BigIntegerField('size of file in bytes', blank=True, null=True)
likes = models.ManyToManyField('auth.User', blank=True, null=True)
class Meta:
verbose_name_plural = "photos"
def __str__(self):
return self.title
def delete(self, using=None, keep_parents=False):
default_storage.delete("{}".format(self.photo))
super().delete()
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Photo, self).save(*args, **kwargs)
Here is the view (at least the part that should matter for creating):
class PhotoViewSet(viewsets.ModelViewSet):
queryset = Photo.objects.all()
serializer_class = PhotoSerializer
authentication_classes = (TokenAuthentication,)
permission_classes = (IsOwnerOrReadOnly, permissions.AllowAny,)
parser_classes = (MultiPartParser, FormParser)
def perform_create(self, serializer):
serializer.save(owner=self.request.user, likes=[])
And here is the serializer:
class PhotoSerializer(serializers.ModelSerializer, TaggitSerializer):
owner = serializers.CharField(source='owner.username', read_only=True)
tags = TagListSerializerField()
photo = Base64ImageField(
max_length=None, use_url=True,
)
class Meta:
model = Photo
fields = ('photo', 'height', 'width', 'owner', 'slug', 'uuid', 'title', 'id', 'created', 'updated',
'moderation_code', 'tags', 'hash', 'description', 'size', 'likes')
def create(self, validated_data):
photo = Photo.objects.create(owner=validated_data.pop('owner'),
**validated_data)
p = Photo.objects.get(uuid=photo.uuid)
[p.tags.add(tag) for tag in validated_data['tags']]
return photo
To be clear, the only thing that has been added is the likes field in the model. Also, I should note that I am able to actually POST new likes to photos that already existed in the DB before the migration. I'm just having issues creating new instances. Any ideas?
Here is the full error traceback:
Internal Server Error: /api/photos/
Traceback (most recent call last):
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/rest_framework/viewsets.py", line 86, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/rest_framework/views.py", line 489, in dispatch
response = self.handle_exception(exc)
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/rest_framework/views.py", line 449, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/rest_framework/views.py", line 486, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/rest_framework/mixins.py", line 21, in create
self.perform_create(serializer)
File "/Users/xxxxxx/_/photos/views.py", line 24, in perform_create
serializer.save(owner=self.request.user, likes=[])
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/rest_framework/serializers.py", line 215, in save
self.instance = self.create(validated_data)
File "/Users/xxxxxx/_/photos/serializers.py", line 88, in create
**validated_data)
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/django/db/models/query.py", line 392, in create
obj = self.model(**kwargs)
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/django/db/models/base.py", line 566, in __init__
_setattr(self, prop, kwargs[prop])
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 536, in __set__
manager = self.__get__(instance)
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 513, in __get__
return self.related_manager_cls(instance)
File "/Users/xxxxxx/_/.virtualenv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 830, in __init__
(instance, self.pk_field_names[self.source_field_name]))
ValueError: "<Photo: photo-260561.jpeg>" needs to have a value for field "id" before this many-to-many relationship can be used.
Well, I solved this with one seemingly very simple line of code:
def create(self, validated_data):
validated_data.pop('likes') ## adding this line solved the issue
photo = Photo.objects.create(owner=validated_data.pop('owner'),
**validated_data)
p = Photo.objects.get(uuid=photo.uuid)
[p.tags.add(tag) for tag in validated_data['tags']]
return photo
If anyone can explain why this works, I'd be interested to know. I should point out that for this use case a photo would never be initiated with likes.