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'],
)
Related
I am trying to grab a user's list using Django Rest Framework and an Ajax request. However, I get the following error
AttributeError: 'UserListViewSet' object has no attribute 'GET'
Not sure what I am doing wrong - I am newer to DRF than vanilla Django.
Ajax call:
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()
router.register('userlist', views.UserListViewSet, basename= 'userlist')
router.register('uservenue', views.UserVenueViewSet, basename= 'uservenue')
views.py
#this shows all lists for a user
class UserListViewSet(viewsets.ModelViewSet):
serializer_class = UserListSerializer
def get_queryset(request):
name = request.GET.get('username', None)
return UserList.objects.filter(user=name)
Traceback:
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
name = request.GET.get('username', None)
AttributeError: 'UserListViewSet' object has no attribute 'GET'
The first parameter of get_queryset is not a request, but the UserListViewSet, so the self, you can obtain the request with self.request:
class UserListViewSet(viewsets.ModelViewSet):
serializer_class = UserListSerializer
def get_queryset(self):
name = self.request.GET.get('username', None)
return UserList.objects.filter(user=name)
Notification are already working in the view class. But not working in admin.py
I do send the puh notification after the save record in save_model. but not working here is my method
class EventAdmin(admin.ModelAdmin):
list_display = ('event_name', 'event_type', 'event_city', 'event_organizer', 'start_date',
'start_time', 'end_date', 'end_time', 'is_approved', 'is_active', 'created_at')
fields = ('main_image', 'event_name', 'event_organizer', 'event_type', 'event_city', 'event_tag', 'event_address', 'event_description',
'event_notes', 'start_date', 'start_time', 'end_date', 'end_time', 'age_max', 'age_min', 'event_lat', 'event_lng', 'website', 'is_approved', 'is_active', 'created_at')
def save_model(self, request, instance, form, change):
user = request.user
instance = form.save(commit=False)
if not change or not instance.created_by:
instance.created_by = user
# Here is notification class
notifiClass = Notifications()
notifiClass.sendNotifications(instance)
else:
instance.is_updated = True
instance.modified_by = user
instance.save()
form.save_m2m()
return instance
here is my Notification class in admin.py
class Notifications(object):
def sendNotifications(self, data):
users = models.NewEventNotification.objects.all().filter(is_notify=1)
serializer = NewEventNotificationSerializer(users, many=True)
tokens = []
for user in serializer.data:
tokens.append(user['user_token'])
if tokens:
push_service = FCMNotification(api_key=api_key)
message_title = "New Event"
message_body = data
result = push_service.notify_multiple_devices(
registration_ids=tokens, message_title=message_title, message_body=message_body)
print(result)
this shows the result in browser
TypeError at /admin/events/event/add/
Object of type Event is not JSON serializable
Request Method: POST
Request URL: http://192.168.0.104:8000/admin/events/event/add/
Django Version: 2.1.5
Exception Type: TypeError
Exception Value:
Object of type Event is not JSON serializable
Exception Location: C:\Python\Python37-32\lib\json\encoder.py in default, line 179
Python Executable: C:\Python\Python37-32\python.exe
Python Version: 3.7.4
Python Path:
['D:\\python\\emsbackend',
'C:\\Python\\Python37-32\\python37.zip',
'C:\\Python\\Python37-32\\DLLs',
'C:\\Python\\Python37-32\\lib',
'C:\\Python\\Python37-32',
'C:\\Users\\laptop '
'genration\\AppData\\Roaming\\Python\\Python37\\site-packages',
'C:\\Python\\Python37-32\\lib\\site-packages',
'C:\\Python\\Python37-32\\lib\\site-packages\\pip-19.2.3-py3.7.egg']
Server time: Fri, 20 Dec 2019 18:32:51 +0500
and in console
Internal Server Error: /admin/events/event/add/
Traceback (most recent call last):
File "C:\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python\Python37-32\lib\site-packages\django\contrib\admin\options.py", line 604, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Python\Python37-32\lib\site-packages\django\utils\decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Python\Python37-32\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "C:\Python\Python37-32\lib\site-packages\django\contrib\admin\sites.py", line 223, in inner
return view(request, *args, **kwargs)
File "C:\Python\Python37-32\lib\site-packages\django\contrib\admin\options.py", line 1637, in add_view
return self.changeform_view(request, None, form_url, extra_context)
File "C:\Python\Python37-32\lib\site-packages\django\utils\decorators.py", line 45, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Python\Python37-32\lib\site-packages\django\utils\decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Python\Python37-32\lib\site-packages\django\contrib\admin\options.py", line 1525, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "C:\Python\Python37-32\lib\site-packages\django\contrib\admin\options.py", line 1564, in _changeform_view
self.save_model(request, new_object, form, not add)
File "D:\python\emsbackend\events\admin.py", line 296, in save_model
notifiClass.sendNotifications(instance)
File "D:\python\emsbackend\events\admin.py", line 382, in sendNotifications
registration_id=tokens[0], message_title=message_title, message_body=message_body)
File "C:\Python\Python37-32\lib\site-packages\pyfcm\fcm.py", line 113, in notify_single_device
**extra_kwargs
File "C:\Python\Python37-32\lib\site-packages\pyfcm\baseapi.py", line 299, in parse_payload
return self.json_dumps(fcm_payload)
File "C:\Python\Python37-32\lib\site-packages\pyfcm\baseapi.py", line 120, in json_dumps
ensure_ascii=False
File "C:\Python\Python37-32\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "C:\Python\Python37-32\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Python\Python37-32\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Python\Python37-32\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Event is not JSON serializable
after searching got this solution. on notification class
# Here is notification class
notifiClass = Notifications()
notifiClass.sendNotifications(instance)
change to this
# make serializer class of that event
serializer = eventSerializer(instance)
notifiClass = Notifications()
notifiClass.sendNotifications(serializer)
I tried to pass the user( i.e, request.user) to my modelform constructor as given in this link.But i am getting
TypeError: __init__() got an unexpected keyword argument 'us'
error. Here's my view
class dealAdd(generic.CreateView):
form_class = dealForm
template_name='deals/deal_Add.html'
def get_context_data(self,**kwargs):
context=super(dealAdd,self).get_context_data(**kwargs)
llist=lead.objects.all()
clist=contacts.objects.all()
context.update({'leadob':llist,'contob':clist})
return context
def get_form_kwargs(self, *args, **kwargs):
kwargs = super(dealAdd, self).get_form_kwargs()
kwargs.update({'us': self.request.user})
return kwargs
and my form constructor
def __init__(self,*args,**kwargs):
usr=kwargs.pop('us')
super(dealForm,self).__init__(*args, **kwargs)
print(usr)
# print(self)
the traceback says that i have error at
context=super(dealAdd,self).get_context_data(**kwargs)
So is there a problem in my view?
Traceback:
Internal Server Error: /deals/dealAdd
Traceback (most recent call last):
File "C:\Users\CapC\Desktop\Django\env\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
response = get_response(request)
File "C:\Users\CapC\Desktop\Django\env\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\CapC\Desktop\Django\env\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\CapC\Desktop\Django\env\lib\site-packages\django\views\generic\base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\CapC\Desktop\Django\env\lib\site-packages\django\views\generic\base.py", line 89, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\CapC\Desktop\Django\env\lib\site-packages\django\views\generic\edit.py", line 168, in get
return super().get(request, *args, **kwargs)
File "C:\Users\CapC\Desktop\Django\env\lib\site-packages\django\views\generic\edit.py", line 133, in get
return self.render_to_response(self.get_context_data())
File "C:\Users\CapC\Desktop\Sabith\crm1\deals\views.py", line 21, in get_context_data
context=super(dealAdd,self).get_context_data(**kwargs)
File "C:\Users\CapC\Desktop\Django\env\lib\site-packages\django\views\generic\edit.py", line 66, in get_context_data
kwargs['form'] = self.get_form()
File "C:\Users\CapC\Desktop\Django\env\lib\site-packages\django\views\generic\edit.py", line 33, in get_form
return form_class(**self.get_form_kwargs())
TypeError: __init__() got an unexpected keyword argument 'us'
[06/Oct/2018 15:18:41] "GET /deals/dealAdd HTTP/1.1" 500 91563
my form
class dealForm(forms.ModelForm):
class Meta:
model=deals
fields= '__all__'
widgets={
'refno':forms.TextInput(attrs={'class':'input-sm form-
control ember-view ember-text-field'}),
'status':forms.Select(choices=stat,attrs={'class':'btn btn-deals'}),
'transaction_price':forms.TextInput(attrs={'class':'input-sm form-
control ember-view ember-text-field'}),
'estimated_closing_date':forms.TextInput(attrs={'class':'input-sm
form-control ember-view ember-text-field'}),
Maybe it's because of the order.
Your CreateView call get_context_data first before get_form_kwargs. It means it 'pop' your 'us' before it updated it.
Just change usr=kwargs.pop('us', None) to avoid error or use try/except for it.
I'm trying to create a form that submits a model with a foreign key but i got this error :
Traceback (most recent call last):
File "C:\Users\~\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
response = get_response(request)
File "C:\Users\~\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\~\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\~\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "~.py", line 21, in wrap
return function(request, *args, **kwargs)
File "~.py", line 32, in wrap
return function(request, *args, **kwargs)
File "~.py", line 428, in example
PostFormSet = inlineformset_factory(User, Post, fields=('longitude', 'latitude', 'placename', 'explanation', ))
File "C:\Users\~\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\forms\models.py", line 1038, in inlineformset_factory
fk = _get_foreign_key(parent_model, model, fk_name=fk_name)
File "C:\Users\~\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\forms\models.py", line 980, in _get_foreign_key
opts = model._meta
AttributeError: 'function' object has no attribute '_meta'
model.py
class Post(models.Model):
owner = models.ForeignKey(User,on_delete=models.CASCADE,related_name="posts",blank=False,null=False)
</other fields>...
class PostImage(models.Model):
owner = models.ForeignKey(Post,on_delete=models.CASCADE,related_name="images",blank=False,null=False)
views.py
def example(request):
context = {
'hellow we':"qfqf"
}
print(request.user)
PostFormSet = inlineformset_factory(User, Post, fields=('longitude', 'latitude', 'placename', 'explanation', ))
print("------------------------------------------------------------")
print(frm.errors)
return JsonResponse(context, encoder=JSONEncoder)
I found the problem. There was another function named Post in the views
I have created a class based view
class MyLibrary(generic.DetailView):
context_object_name = 'data'
def get_template_names(self):
request = self.request
template_name = 'my_library.html'
return [template_name]
def get_queryset(self):
request = self.request
user = request.user
context = {}
mainData = []
userIssuedBooks = BooksIssued.objects.filter(user=user)
print(userIssuedBooks)
if user.is_authenticated():
context['issuedBooks'] = userIssuedBooks
return context
I am getting following error when the view is getting called
Internal Server Error: /mylibrary/1/admin
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\django\core\handlers\base.py", line 149,
in get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python34\lib\site-packages\django\core\handlers\base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python34\lib\site-packages\django\contrib\auth\decorators.py", line 2
3, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Python34\lib\site-packages\django\views\generic\base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Python34\lib\site-packages\django\views\generic\base.py", line 88, in
dispatch
return handler(request, *args, **kwargs)
File "C:\Python34\lib\site-packages\django\views\generic\detail.py", line 117,
in get
self.object = self.get_object()
File "C:\Python34\lib\site-packages\django\views\generic\detail.py", line 38,
in get_object
queryset = queryset.filter(pk=pk)
AttributeError: 'dict' object has no attribute 'filter'
I have no clue why this error is getting generated. Can someone help to find what is wrong here?
In django DetailView, get_queryset expects user to return a queryset(as the name implies) but you returned a dict context. You need to do your current stuff in get_context_data instead.
Django doc about adding extra context.