ValueError: too many values to unpack (expected 2) Django - django

Not sure why but my code is getting the following error:
ValueError: too many values to unpack (expected 2)
Here is my models.py:
class UserList(models.Model):
list_name = models.CharField(max_length=255)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.list_name
Here is my views.py
def otherUserList(request):
userName = request.GET.get('userName', None)
print(userName)
qs = UserList.objects.filter(user__username=userName)
return qs
Here is the traceback:
Internal Server Error: /electra/otheruserlist/
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/deprecation.py", line 116, in __call__
response = self.process_response(request, response)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/middleware/clickjacking.py", line 26, in process_response
if response.get('X-Frame-Options') is not None:
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 418, in get
clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 942, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 962, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 969, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1358, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1377, in _add_q
child_clause, needed_inner = self.build_filter(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1255, in build_filter
arg, value = filter_expr
ValueError: too many values to unpack (expected 2)
[02/Sep/2021 05:38:43] "GET /electra/otheruserlist/?userName=alice HTTP/1.1" 500 94227
I'd be very grateful for any assistance.

Your view is returning a QuerySet, but that does not make much sense: a view should return a HttpResponse. You can for example render a template, convert it to JSON, etc.
We can for example render a template with:
from django.shortcuts import render
def otherUserList(request):
userName = request.GET.get('userName', None)
qs = UserList.objects.filter(user__username=userName)
return render(request, 'some-template.html', {'lists': qs})
Or we can for example return a JsonResponse wit the list_name`s of user the user with the given username with:
from django.http import JsonField
def otherUserList(request):
userName = request.GET.get('userName', None)
qs = UserList.objects.filter(user__username=userName)
return JsonResponse({'listnames': [list.name for list in qs]})

The exception comes from a Django internal middleware, since it's trying to process your returned qs as a response.
You'll need to return a response, not just a queryset, e.g. this simple example to return a list of user IDs.
from django.http import JsonResponse
def otherUserList(request):
userName = request.GET.get('userName', None)
print(userName)
qs = UserList.objects.filter(user__username=userName)
return JsonResponse({"ids": [user.id for user in qs]})

Related

'int' object has no attribute 'user_list'. (Django Rest Framework)

I have a feature where user can remove an item from a list. The code below does successfully remove (delete) the item from the list but also returns the following error (and my AJAX call doesn't complete successfully):
Got AttributeError when attempting to get a value for field `user_list` on serializer `UserVenueSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `int` instance.
Original exception text was: 'int' object has no attribute 'user_list'.
I am not sure how to debug this/why this error is being thrown.
Here is my serializers:
class UserVenueSerializer(serializers.ModelSerializer):
venue = mapCafesSerializer()
class Meta:
model = UserVenue
fields = ['user_list', 'venue']
Here is my views
class RemoveVenueViewSet(viewsets.ModelViewSet):
serializer_class = serializers.UserVenueSerializer
authentication_classes = [CsrfExemptSession]
def get_queryset(self):
user_list = self.request.GET.get('user_list', None)
venue = self.request.GET.get('venue', None)
data = UserVenue.objects.filter(user_list = user_list, venue= venue)
print(data)
return data.delete()
Here is the traceback:
<QuerySet [<UserVenue: UserVenue object (142)>]>
Internal Server Error: /api/removevenue/
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/fields.py", line 457, in get_attribute
return get_attribute(instance, self.source_attrs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/fields.py", line 97, in get_attribute
instance = getattr(instance, attr)
AttributeError: 'int' object has no attribute 'user_list'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/viewsets.py", line 125, in view
return self.dispatch(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/mixins.py", line 46, in list
return Response(serializer.data)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/serializers.py", line 745, in data
ret = super().data
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/serializers.py", line 246, in data
self._data = self.to_representation(self.instance)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/serializers.py", line 663, in to_representation
return [
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/serializers.py", line 664, in <listcomp>
self.child.to_representation(item) for item in iterable
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/serializers.py", line 502, in to_representation
attribute = field.get_attribute(instance)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/relations.py", line 190, in get_attribute
return super().get_attribute(instance)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/fields.py", line 490, in get_attribute
raise type(exc)(msg)
AttributeError: Got AttributeError when attempting to get a value for field `user_list` on serializer `UserVenueSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `int` instance.
Original exception text was: 'int' object has no attribute 'user_list'
I'd be grateful for any advice!
you can try this method
class RemoveVenueViewSet(APIView):
serializer_class = serializers.UserVenueSerializer
authentication_classes = [CsrfExemptSession]
def delete(self, request, *args, **kwargs):
user_list = request.GET.get('user_list', None)
venue = request.GET.get('venue', None)
success = UserVenue.objects.filter(user_list=user_list, venue=venue).delete()
if success:
return Response("Question deleted", status=status.HTTP_204_NO_CONTENT)
return Response("Item does not exixt", status=status.HTTP_404_NOT_FOUND)
I ended up just using vanilla Django and it worked like a charm.
def remove_venue_from_list(request):
user_list = request.GET.get('user_list', None)
venue = request.GET.get('venue', None)
data = UserVenue.objects.filter(user_list = user_list, venue = venue)
data.delete()
return render(request, 'testingland/index3.html')

Field 'id' expected a number but got 'Henry' (AJAX & DRF)

I am trying to get a user's list with an AJAX request and DRF. But get this error:
Field 'id' expected a number but got 'Henry'.
I'd be grateful for any assistance.
AJAX:
const showUserLists = function(map){
let userName = "Henry";
$.ajax({
type: 'GET',
url: '/api/userlist/',
data: {
'username': userName
},
success: function (data) {
data.forEach(item => {
console.log(item.list_name)
$("#userLists").append("<li class=userlist data-name=\"" + item.list_name + "\">" + item.list_name + "</li>")
})
}
});
};
urls.py:
router = DefaultRouter() #need help understanding router register
router.register('userlist', views.UserListViewSet, basename= 'userlist')
views.py
#this shows all lists for a user
class UserListViewSet(viewsets.ModelViewSet):
serializer_class = UserListSerializer
def get_queryset(self):
name = self.request.GET.get('username', None)
return UserList.objects.filter(user=name)
Serializer:
class UserListSerializer(serializers.ModelSerializer): #this is what we worked on on October 1
class Meta:
model = UserList
fields = ['id', 'user', 'list_name']
class VenueListSerializer(serializers.ModelSerializer):
created = serializers.ReadOnlyField()
class Meta:
model = VenueList
fields = ['id', 'title']
Relevant model:
class UserList(models.Model):
list_name = models.CharField(max_length=255)
user = models.ForeignKey(User, on_delete=models.CASCADE) #is this okay?
def __str__(self):
return self.list_name
Traceback
Traceback (most recent call last):
File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1774, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'Henry'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/rest_framework/viewsets.py", line 114, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/rest_framework/views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/rest_framework/views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
raise exc
File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/rest_framework/views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/rest_framework/mixins.py", line 38, in list
queryset = self.filter_queryset(self.get_queryset())
File "/Users/x/Desktop/Coding/anybody/anybody1/api/views.py", line 33, in get_queryset
return UserList.objects.filter(user=name)
File "/Users/x/Desktop/Coding/anybody/avenv/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/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/db/models/query.py", line 942, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/db/models/query.py", line 962, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, *args, **kwargs)
File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/db/models/query.py", line 969, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1358, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1380, in _add_q
split_subq=split_subq, check_filterable=check_filterable,
File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1319, in build_filter
condition = self.build_lookup(lookups, col, value)
File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1165, in build_lookup
lookup = lookup_class(lhs, rhs)
File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/db/models/lookups.py", line 24, in __init__
self.rhs = self.get_prep_lookup()
File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/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 "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1778, in get_prep_value
) from e
ValueError: Field 'id' expected a number but got 'Henry'.
Your user is a ForeignKey to the User model, so if you filter on this, it expects the primary key of the User, not the username.
You can however filter on the username of the related User with:
class UserListViewSet(viewsets.ModelViewSet):
serializer_class = UserListSerializer
def get_queryset(self):
name = self.request.GET.get('username', None)
return UserList.objects.filter(user__username=name)
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Marshmallow for python giving ValueError: not enough values to unpack (expected 2, got 1)

I am using Marshmallow for serialization/deserialization purposes in the API I am building but I'm getting the above-stated error. Here are my Schema, Model, and Resource file for the same.
schemas/post.py
from marshmallow import Schema, fields, validate, post_dump
from schemas.user import UserSchema
class PostSchema(Schema):
class Meta:
ordered = True
id = fields.Int(dump_only=True)
body = fields.Str(required=True, validate=[validate.Length(max=500, min=1)])
created_at = fields.DateTime(dump_only=True)
updated_at = fields.DateTime(dump_only=True)
author = fields.Nested(UserSchema, attribute='user', dump_only=True, only=['id', 'username'])
#post_dump(pass_many=True)
def wrap_output_with_envelope(self, data, many, **kwargs):
if many:
return {'data': data}
return data
models/post.py
from database import db
class Post(db.Model):
__tablename__ = 'post'
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.String, nullable=False)
created_at = db.Column(db.DateTime(), nullable=False, server_default=db.func.now())
updated_at = db.Column(db.DateTime(), nullable=False, server_default=db.func.now(), onupdate=db.func.now())
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
#classmethod
def get_by_post_id(cls, id):
return cls.query.filter_by(id=id).first()
#classmethod
def get_all_posts(cls):
return cls.query.all()
def data(self):
return {'id': self.id, 'body': self.body, 'user_id': self.user_id}
def save(self):
db.session.add(self)
db.session.commit()
def delete(self):
db.session.delete(self)
db.session.commit()
and resources/post.py
from flask import request
from flask_restful import Resource
from http import HTTPStatus
from flask_jwt_extended import jwt_required, get_jwt_identity, jwt_optional
from models.post import Post
from schemas.post import PostSchema
post_schema = PostSchema()
post_list_schema = PostSchema(many=True)
class PostListResource(Resource):
def get(self):
posts = Post.get_all_posts()
return post_list_schema.dump(posts), HTTPStatus.OK
#jwt_required
def post(self):
json_data = request.get_json()
current_user = get_jwt_identity()
data, errors = post_schema.load(data=json_data)
if errors:
return {'message': "Validation errors", 'errors': errors}, HTTPStatus.BAD_REQUEST
post = Post(**data)
post.user_id = current_user
post.save()
return post_schema.dump(post), HTTPStatus.CREATED
I try sending the following JSON: {"body": "This is some text."} and the error I get is:
Traceback (most recent call last):
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask_restful\__init__.py", line 272, in error_router
return original_handler(e)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\_compat.py", line 38, in reraise
raise value.with_traceback(tb)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask_restful\__init__.py", line 272, in error_router
return original_handler(e)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\_compat.py", line 38, in reraise
raise value.with_traceback(tb)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask_restful\__init__.py", line 468, in wrapper
resp = resource(*args, **kwargs)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\views.py", line 89, in view
return self.dispatch_request(*args, **kwargs)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask_restful\__init__.py", line 583, in dispatch_request
resp = meth(*args, **kwargs)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask_jwt_extended\view_decorators.py", line 108, in wrapper
return fn(*args, **kwargs)
File "D:\blogposts\resources\post.py", line 23, in post
data, errors = post_schema.load(data=json_data)
ValueError: not enough values to unpack (expected 2, got 1)
Please help. Thanks!
You must have been following an outdated doc/tuto.
Since marshmallow 3, only data is returned. A ValidationError is raised in case of error.
Change
data, errors = post_schema.load(data=json_data)
if errors:
return {'message': "Validation errors", 'errors': errors}, HTTPStatus.BAD_REQUEST
into
try:
data = post_schema.load(data=json_data)
except ValidationError as exc:
return {'message': "Validation errors", 'errors': exc.messages}, HTTPStatus.BAD_REQUEST

Attribute error 'QueryDict' object has no attribute '_meta'

I'm trying to send a post request from PostMan into my Django view and I'm getting this error. "AttributeError: 'QueryDict' object has no attribute '_meta'"
From what I've gathered it has something to do with the form.save() as seen in traceba
I've searched all over to find a solution or even a better way to achieve an image post from a external web client to a Django server.
All help is very much appreciated.
Traceback
Capture.PNG
form is valid
Internal Server Error: /getimg/
Traceback (most recent call last):
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
raise exc
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\decorators.py", line 50, in handler
return func(*args, **kwargs)
File "C:\Users\Gedit\Desktop\django\indivproj\getimg\api\views.py", line 21, in getimg
form.save()
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\serializers.py", line 207, in save
self.instance = self.update(self.instance, validated_data)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\serializers.py", line 979, in update
info = model_meta.get_field_info(instance)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\utils\model_meta.py", line 35, in get_field_info
opts = model._meta.concrete_model._meta
AttributeError: 'QueryDict' object has no attribute '_meta'
[24/Mar/2020 13:39:25] "POST /getimg/ HTTP/1.1" 500 20251
Views.py
#api_view(['POST',])
def getimg(request):
if request.method == 'POST':
form = ImageSerializer(request.POST, request.FILES)
logger.warning(request.FILES['img'])
if form.is_valid():
#raise_exception=True
logger.warning('form is valid')
form.save()
logger.warning()
response_dict = {'post': 'success'}
return HttpResponse(simplejson.dumps(response_dict), content_type='application/javascript')
else:
logger.warning(form.errors)
else:
form = ImageSerializer()
return render(request, 'getimg.html', {'form': form})
Serializers.py
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Image
fields = '__all__'
Models.py
class Image(models.Model):
# name = models.CharField(default='name', max_length=30)
img = models.ImageField(upload_to='images/', max_length=1000)
Urls.py
app_name = 'getimg'
urlpatterns = [
# ex: /polls/
path('', views.getimg, name='getimg'),
path('gettext/', views.gettext, name='gettext'),
path('success', views.success, name = 'success'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Postman
so after looking around as a smart individual I realized i have not defined what save() function is... so now i do
The code that fixed the error but still not working
def save(self):
img = Image(
img =self.validated_data['img'],
)

Validate each value of an ArrayField of emails in Django

I am using PostgreSQL with Django and am trying to use ArrayField(models.EmailField(max_length=200)). But I am ending up with an 500 error code(TypeError) when giving invalid email address.
How can I validate each email in the ArrayField. I have tried writing validate method in both serializer and models. But nothing helped. What is the right way to validate ArrayFields? I am using Django 2.1 and Python 3.6
The traceback of the error is given below...please have a look
models.py
billing_emails = ArrayField(models.EmailField(max_length=200))
company = models.OneToOneField(Company, on_delete=models.CASCADE)
Traceback
Traceback (most recent call last):
File "/home/user/.local/share/virtualenvs/backend-Amy45Zrz/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/user/.local/share/virtualenvs/backend-Amy45Zrz/lib/python3.6/site-packages/django/core/handlers/base.py", line 156, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/user/.local/share/virtualenvs/backend-Amy45Zrz/lib/python3.6/site-packages/django/core/handlers/base.py", line 154, in _get_response
response = response.render()
File "/home/user/.local/share/virtualenvs/backend-Amy45Zrz/lib/python3.6/site-packages/django/template/response.py", line 106, in render
self.content = self.rendered_content
File "/home/user/.local/share/virtualenvs/backend-Amy45Zrz/lib/python3.6/site-packages/rest_framework/response.py", line 72, in rendered_content
ret = renderer.render(self.data, accepted_media_type, context)
File "/home/user/.local/share/virtualenvs/backend-Amy45Zrz/lib/python3.6/site-packages/djangorestframework_camel_case/render.py", line 8, in render
return super(CamelCaseJSONRenderer, self).render(camelize(data), *args,
File "/home/user/.local/share/virtualenvs/backend-Amy45Zrz/lib/python3.6/site-packages/djangorestframework_camel_case/util.py", line 17, in camelize
new_dict[new_key] = camelize(value)
File "/home/user/.local/share/virtualenvs/backend-Amy45Zrz/lib/python3.6/site-packages/djangorestframework_camel_case/util.py", line 16, in camelize
new_key = re.sub(r"[a-z]_[a-z]", underscoreToCamel, key)
File "/home/user/.local/share/virtualenvs/backend-Amy45Zrz/lib/python3.6/re.py", line 191, in sub
return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or bytes-like object
Thanks in advance.
If you are using Forms, use Form or Serializer, you can use the clean_<attribute_name> method to validate the data. For example:
from django.core.validators import email_re
from django.core.exceptions import ValidationError
class YourForm(forms.ModelForm): # serializers.ModelSerializer
def clean_billing_emails(self):
data = self.cleaned_data['billing_emails']
for email in data:
if not email_re.match(email):
raise ValidationError('Invalid email {}'.format(email) # or raise serializers.ValidationError
return data
Also you can use model's clean method.
class YourModel(models.Model):
...
def clean(self):
try:
for email in self.billing_emails:
if not email_re.match(email):
raise ValidationError('Invalid email {}'.format(email)
except (TypeError, Exception) as e:
# log error
# handle error
def save(self, *args, **kwargs):
self.full_clean()
return super(YourModel, self).save(*args, **kwargs)