ValueError with Django form initial - python

I'm building a reservation app with Django and I want to allow users to use one reservation as template for another. My idea is that I add ?prefill=<reservation_id> to url and then prefill empty form with data from reservation in prefill id.
My CreateView looks like this:
class ReservationCreateView(LoginRequiredMixin, CreateUpdateMixin, CreateView):
model = Reservation
form_class = ReservationForm
success_url = '/'
def get_context_data(self, **kwargs):
ctx = super(ReservationCreateView, self).get_context_data()
r = Reservation.objects.filter(pk=self.request.GET.get('prefill'))
ctx['form'] = ReservationForm(initial=r.values(), request=self.request)
return ctx
This gives me: dictionary update sequence element #0 has length 30; 2 is required
Error stack:
Environment:
Request Method: GET
Request URL: http://localhost:8000/r/create/?prefill=56cc36bd-c766-4e45-8a1b-cdde3cd87dc4
Django Version: 1.10.3
Python Version: 2.7.10
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'tags',
'profiles',
'reservations',
'drivers',
'import_export',
'src',
'crispy_forms',
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
'anymail',
'wf',
'storages',
'djangoformsetjs']
Installed Middleware:
['corsheaders.middleware.CorsMiddleware',
'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',
'htmlmin.middleware.HtmlMinifyMiddleware',
'htmlmin.middleware.MarkRequestMiddleware']
Traceback:
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/contrib/auth/mixins.py" in dispatch
56. return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "/Users/jhotujec/Documents/projects/optilimo/reservations/mixins.py" in get
68. route_formset=route_formset))
File "/Users/jhotujec/Documents/projects/optilimo/reservations/views.py" in get_context_data
108. ctx['form'] = ReservationForm(initial=r.values(), request=self.request)
File "/Users/jhotujec/Documents/projects/optilimo/reservations/forms.py" in __init__
30. super(ReservationForm, self).__init__(*args, **kwargs)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/forms/models.py" in __init__
285. object_data.update(initial)
Exception Type: ValueError at /r/create/
Exception Value: dictionary update sequence element #0 has length 30; 2 is required

filter() always returns a queryset, and values() is then basically a list of dicts, whereas the form is expecting a single dict.
You could fix this by using r.values()[0] instead, but this is really the wrong approach. This is a model form; you should populate it by passing an actual model instance as the instance argument.

The problem is initial=r.values() where r is a QuerySet. values returns a list of dicts, initial expects a dict. You could get the Reservation instance and use the instance parameter of the form constructor instead:
# first() will return None if the QS is empty
r = Reservation.objects.get(pk=self.request.GET.get('prefill')).first()
ctx['form'] = ReservationForm(instance=r, request=self.request)

Related

Django - 'User' object has no attribute 'session_set'

I want to add a Sessions tabs to my Django project:
navbar.html
<li>Sessions</li>
But i keep getting the following error:
'User' object has no attribute 'session_set''User' object has no attribute 'session_set'
Exception Location: C:\Users\User\lib\site-packages\django\utils\functional.py in inner, line 214
I don't know where this error comes from, i did not find any other reference online, can anyone help me?
Here is the login view that i'm using: https://github.com/Bouke/django-two-factor-auth/blob/master/two_factor/views/core.py
Full traceback
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/account/sessions/
Django Version: 2.1.7
Python Version: 3.7.0
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'main.apps.MainConfig',
'tinymce',
'captcha',
'django.contrib.sites',
'django_otp',
'django_otp.plugins.otp_static',
'django_otp.plugins.otp_totp',
'two_factor']
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',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django_otp.middleware.OTPMiddleware']
Traceback:
File "C:\Users\User\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\User\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = self.process_exception_by_middleware(e, request)
File "C:\Users\User\lib\site-packages\django\core\handlers\base.py" in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\User\lib\site-packages\django\views\generic\base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "C:\Users\User\lib\site-packages\django\utils\decorators.py" in _wrapper
45. return bound_method(*args, **kwargs)
File "C:\Users\User\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
21. return view_func(request, *args, **kwargs)
File "C:\Users\User\lib\site-packages\user_sessions\views.py" in dispatch
22. **kwargs)
File "C:\Users\User\lib\site-packages\django\views\generic\base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "C:\Users\User\lib\site-packages\django\views\generic\list.py" in get
142. self.object_list = self.get_queryset()
File "C:\Users\User\lib\site-packages\user_sessions\views.py" in get_queryset
14. return self.request.user.session_set\
File "C:\Users\User\lib\site-packages\django\utils\functional.py" in inner
214. return func(self._wrapped, *args)
File "C:\Users\User\lib\site-packages\django\utils\functional.py" in inner
214. return func(self._wrapped, *args)
Exception Type: AttributeError at /account/sessions/
Exception Value: 'User' object has no attribute 'session_set'
You need to replace django.contrib.sessions in your INSTALLED_APPS with user_sessions if you want to use django-user-sessions. This will setup its models correctly.
Furthermore make sure you have also followed all other installation instructions.

Django: writing text from uploaded file to text field

I have the following model:
class Clean(models.Model):
name = models.CharField(max_length=100)
cv = models.TextField(max_length=10000)
cvfile = models.FileField()
I am trying to write the contents of cvfile to cv when the user submits the name and file from the form. I'm sure this can be done as the file and text field will be in the same object. The file will always be .txt so I assume a simple .read() can be performed.
Should I have a function that the form calls to perform this? If so how can this be done?
def writeCV(self):
get_text = cvfile.open().read()
#write to cv field somehow
return self.cv
I am using django 1.9
Traceback from Messaoud's answer:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/cleaner/clean/add/
Django Version: 1.9
Python Version: 3.6.4
Installed Applications:
['cleaner.apps.CleanerConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "C:\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python\Python36-32\lib\site-packages\django\views\generic\base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "C:\Python\Python36-32\lib\site-packages\django\views\generic\base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "C:\Python\Python36-32\lib\site-packages\django\views\generic\edit.py" in post
255. return super(BaseCreateView, self).post(request, *args, **kwargs)
File "C:\Python\Python36-32\lib\site-packages\django\views\generic\edit.py" in post
221. return self.form_valid(form)
File "C:\Python\Python36-32\lib\site-packages\django\views\generic\edit.py" in form_valid
200. self.object = form.save()
File "C:\Python\Python36-32\lib\site-packages\django\forms\models.py" in save
451. self.instance.save()
File "C:\Users\barry\Desktop\College\Year 4\Semester 2\cvCleaner\cvcleaner\cleaner\models.py" in save
11. get_text = self.cvfile.open().read()
Exception Type: AttributeError at /cleaner/clean/add/
Exception Value: 'NoneType' object has no attribute 'read'
You can do this by overriding save method in your Model
class Clean(models.Model):
name = models.CharField(max_length=100)
cv = models.TextField(max_length=10000, blank = True, null = True)
cvfile = models.FileField()
def save(self, *args, **kwargs):
get_text = self.cvfile.open().read()
self.cv = get_text
super(Clean, self).save(*args, **kwargs) # Call the "real" save() method.
Or by Using post_save signal
def writeCV(sender, instance, **kwargs):
get_text = instance.cvfile.open().read()
instance.cv = get_text
instance.save()
post_save.connect(writeCV, sender=Clean)

Django - get_queryset() missing 1 required positional argument: 'request'

I was trying to make an API using REST Framework for uploading a file to the server and my codes are below.
If you have any other easy method to do the same please post your code.
models.py
from django.db import models
# Create your models here.
class FileUploader(models.Model):
file = models.FileField()
name = models.CharField(max_length=100) #name is filename without extension
version = models.IntegerField(default=0)
upload_date = models.DateTimeField(auto_now=True, db_index=True)
owner = models.ForeignKey('auth.User', related_name='uploaded_files')
size = models.IntegerField(default=0)
def __str__(self):
return self.name
serializers.py
class FileUploaderSerializer(serializers.ModelSerializer):
class Meta:
model=FileUploader
fields='__all__'
read_only_fields = '__all__'
def validate(self, validated_data):
validated_data['owner'] = self.context['request'].user
validated_data['name'] = os.path.splitext(validated_data['file'].name)[0]
validated_data['size'] = validated_data['file'].size
return validated_data
def create(self,validated_data):
return FileUploader.objects.create(**validated_data)
views.py
class FileUploaderViewSet(viewsets.ModelViewSet):
serializer_class = FileUploaderSerializer
parser_classes=(MultiPartParser,FormParser)
def get_queryset(self,request, *args, **kwargs):
qs = super(FileUploaderViewSet, self).get_queryset(self,request, *args, **kwargs)
qs = qs.filter(owner=self.request.user)
return qs
urls.py
from django.conf.urls import url
from django.conf.urls import url,include
from django.contrib import admin
from rest_framework import routers
from rest_framework.authtoken.views import obtain_auth_token
from rest_framework.urlpatterns import format_suffix_patterns
from webapp import views
from webapp.views import(
UserCreateAPIView,
UserLoginAPIView,
FileUploaderViewSet,
)
router = routers.DefaultRouter()
router.register(r'upload', views.FileUploaderViewSet,base_name='file-view')
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include(router.urls)),
#url(r'^upload/$',FileUploaderViewSet.as_view()),
]
My requirement is that i need to upload a file to the server and the details of the uploaded file is to be shown.
This is the error i am getting!
Environment:
Request Method: GET Request URL: http://127.0.0.1:8000/upload/
Django Version: 1.11.7 Python Version: 3.6.3 Installed Applications:
['django.contrib.admin', 'django.contrib.auth',
'django.contrib.contenttypes', 'django.contrib.sessions',
'django.contrib.messages', 'django.contrib.staticfiles',
'rest_framework', 'webapp'] 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:
File "F:\proj\env\lib\site-packages\django\core\handlers\exception.py"
in inner
41. response = get_response(request)
File "F:\proj\env\lib\site-packages\django\core\handlers\base.py" in
_get_response
187. response = self.process_exception_by_middleware(e, request)
File "F:\proj\env\lib\site-packages\django\core\handlers\base.py" in
_get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "F:\proj\env\lib\site-packages\django\views\decorators\csrf.py"
in wrapped_view
58. return view_func(*args, **kwargs)
File "F:\proj\env\lib\site-packages\rest_framework\viewsets.py" in
view
90. return self.dispatch(request, *args, **kwargs)
File "F:\proj\env\lib\site-packages\rest_framework\views.py" in
dispatch
489. response = self.handle_exception(exc)
File "F:\proj\env\lib\site-packages\rest_framework\views.py" in
handle_exception
449. self.raise_uncaught_exception(exc)
File "F:\proj\env\lib\site-packages\rest_framework\views.py" in
dispatch
486. response = handler(request, *args, **kwargs)
File "F:\proj\env\lib\site-packages\rest_framework\mixins.py" in list
40. queryset = self.filter_queryset(self.get_queryset())
Exception Type: TypeError at /upload/ Exception Value: get_queryset()
missing 1 required positional argument: 'request'
Updated views.py file as follows
from django.shortcuts import render
from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework import viewsets
from rest_framework.status import HTTP_200_OK,HTTP_400_BAD_REQUEST
from .models import employees
from .serializers import (
employeesSerializer,
FileUploaderSerializer,
)
from django.contrib.auth import get_user_model
from rest_framework.generics import (
CreateAPIView,
DestroyAPIView,
ListAPIView,
RetrieveAPIView,
RetrieveUpdateAPIView,
)
from rest_framework.permissions import(
AllowAny,
IsAuthenticated,
IsAdminUser,
IsAuthenticatedOrReadOnly,
)
class employeeList(APIView):
def get(self,request):
employees1=employees.objects.all()
serializer=employeesSerializer(employees1,many=True)
return Response(serializer.data)
def post(self):
pass
User=get_user_model()
from .serializers import(
UserCreateSerializer,
UserLoginSerializer,
)
class UserCreateAPIView(CreateAPIView):
serializer_class=UserCreateSerializer
queryset=User.objects.all()
class UserLoginAPIView(APIView):
permission_classes=[AllowAny]
serializer_class=UserLoginSerializer
def post(self,request,*args,**kwargs):
data=request.data
serializer=UserLoginSerializer(data=data)
if serializer.is_valid(raise_exception=True):
new_data=serializer.data
return Response(new_data,status=HTTP_200_OK)
return Response(serializer.errors,status=HTTP_400_BAD_REQUEST)
class FileUploaderViewSet(viewsets.ModelViewSet):
serializer_class = FileUploaderSerializer
parser_classes=(MultiPartParser,FormParser)
# overriding default query set
#queryset = LayerFile.objects.all()
def get_queryset(self, *args, **kwargs):
qs = super(FileUploaderViewSet, self).get_queryset(self, *args, **kwargs)
qs = qs.filter(owner=self.request.user)
return qs
Traceback:
Environment:
Request Method: GET Request URL: http://127.0.0.1:8000/upload/
Django Version: 1.11.7 Python Version: 3.6.3 Installed Applications:
['django.contrib.admin', 'django.contrib.auth',
'django.contrib.contenttypes', 'django.contrib.sessions',
'django.contrib.messages', 'django.contrib.staticfiles',
'rest_framework', 'webapp'] 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:
File "F:\proj\env\lib\site-packages\django\core\handlers\exception.py"
in inner
41. response = get_response(request)
File "F:\proj\env\lib\site-packages\django\core\handlers\base.py" in
_get_response
187. response = self.process_exception_by_middleware(e, request)
File "F:\proj\env\lib\site-packages\django\core\handlers\base.py" in
_get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "F:\proj\env\lib\site-packages\django\views\decorators\csrf.py"
in wrapped_view
58. return view_func(*args, **kwargs)
File "F:\proj\env\lib\site-packages\rest_framework\viewsets.py" in
view
90. return self.dispatch(request, *args, **kwargs)
File "F:\proj\env\lib\site-packages\rest_framework\views.py" in
dispatch
489. response = self.handle_exception(exc)
File "F:\proj\env\lib\site-packages\rest_framework\views.py" in
handle_exception
449. self.raise_uncaught_exception(exc)
File "F:\proj\env\lib\site-packages\rest_framework\views.py" in
dispatch
486. response = handler(request, *args, **kwargs)
File "F:\proj\env\lib\site-packages\rest_framework\mixins.py" in list
40. queryset = self.filter_queryset(self.get_queryset())
File "F:\proj\env\myproject\webapp\views.py" in get_queryset
74. qs = super(FileUploaderViewSet, self).get_queryset(self, *args, **kwargs)
Exception Type: TypeError at /upload/ Exception Value: get_queryset()
takes 1 positional argument but 2 were given
New Traceback after changeing get query set
class FileUploaderViewSet(viewsets.ModelViewSet):
serializer_class = FileUploaderSerializer
parser_classes=(MultiPartParser,FormParser)
# overriding default query set
def get_queryset(self):
qs = super(FileUploaderViewSet, self).get_queryset()
qs = qs.filter(owner=self.request.user)
return qs
Environment:
Request Method: GET Request URL: http://127.0.0.1:8000/upload/
Django Version: 1.11.7 Python Version: 3.6.3 Installed Applications:
['django.contrib.admin', 'django.contrib.auth',
'django.contrib.contenttypes', 'django.contrib.sessions',
'django.contrib.messages', 'django.contrib.staticfiles',
'rest_framework', 'webapp'] 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:
File "F:\proj\env\lib\site-packages\django\core\handlers\exception.py"
in inner
41. response = get_response(request)
File "F:\proj\env\lib\site-packages\django\core\handlers\base.py" in
_get_response
187. response = self.process_exception_by_middleware(e, request)
File "F:\proj\env\lib\site-packages\django\core\handlers\base.py" in
_get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "F:\proj\env\lib\site-packages\django\views\decorators\csrf.py"
in wrapped_view
58. return view_func(*args, **kwargs)
File "F:\proj\env\lib\site-packages\rest_framework\viewsets.py" in
view
90. return self.dispatch(request, *args, **kwargs)
File "F:\proj\env\lib\site-packages\rest_framework\views.py" in
dispatch
489. response = self.handle_exception(exc)
File "F:\proj\env\lib\site-packages\rest_framework\views.py" in
handle_exception
449. self.raise_uncaught_exception(exc)
File "F:\proj\env\lib\site-packages\rest_framework\views.py" in
dispatch
486. response = handler(request, *args, **kwargs)
File "F:\proj\env\lib\site-packages\rest_framework\mixins.py" in list
40. queryset = self.filter_queryset(self.get_queryset())
File "F:\proj\env\myproject\webapp\views.py" in get_queryset
74. qs = super(FileUploaderViewSet, self).get_queryset()
File "F:\proj\env\lib\site-packages\rest_framework\generics.py" in
get_queryset
68. % self.class.name
Exception Type: AssertionError at /upload/ Exception Value:
'FileUploaderViewSet' should either include a queryset attribute, or
override the get_queryset() method.
get_queryset does not expect the request parameter, and it will not be passed by the DRF base class. It is however available as an instance attribute. You should remove it from the method signature and the super call, and access it via self.request.
def get_queryset(self, *args, **kwargs):
qs = super(FileUploaderViewSet, self).get_queryset(*args, **kwargs)
qs = qs.filter(owner=self.request.user)
return qs
As Sayse said, it only requires self. but you don't have to pass self to get_queryset(). self is just an instance, super itself is self-instance.
So just change your following line from
super(FileUploaderViewSet, self).get_queryset(self, *args, **kwargs)
to
super(FileUploaderViewSet, self).get_queryset()
look at the code snippet here
Update:
Are you sure, your get_queryset is in the same class?
Did you try just writing queryset = Model.objects.all()?
I do not see model = ModelName in your view.
view class should have following fields.
def get_queryset(self):
return queryset
serializer_class = SerializerClass
model = ModelName
get_queryset only requires self as a parameter.
Simply remove the other args.
The get_queryset() does not expect a 'request'. Maybe remove the 'request' argument from the get_queryset(). For reference you can check:
get_queryset()
Maybe something like this:
def get_queryset(self, *args, **kwargs):
qs = your_model.objects.all()
qs = qs.filter(owner=self.request.user)
return qs

In DRF(django-rest-framework), AttributeError 'str' object has no attribute '~~' How to solve it?

I'm using DRF and be front of AttributeError 'str' object has no attribute '~~'.
my error page and code
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/blog/
Django Version: 1.9.7
Python Version: 3.5.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'blog',
'account',
'taggit',
'friendship',
'rest_framework']
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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
466. response = self.handle_exception(exc)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
463. response = handler(request, *args, **kwargs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/decorators.py" in handler
52. return func(*args, **kwargs)
File "/home/keepair/djangogirls/blog/views.py" in post_list
37. return Response(serializer.data)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in data
700. ret = super(ListSerializer, self).data
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in data
239. self._data = self.to_representation(self.instance)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in to_representation
618. self.child.to_representation(item) for item in iterable
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in <listcomp>
618. self.child.to_representation(item) for item in iterable
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in to_representation
463. attribute = field.get_attribute(instance)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/relations.py" in get_attribute
157. return get_attribute(instance, self.source_attrs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/fields.py" in get_attribute
83. instance = getattr(instance, attr)
Exception Type: AttributeError at /blog/
Exception Value: 'str' object has no attribute 'author'
I wonder how to make serializers.py codes.
I already studied : http://www.django-rest-framework.org/api-guide/relations/
But I don't understand what I should do. Where should I put serializers.py?
And how to make my serializers code? Or maybe models.ForienKey is unavailable on using DRF?
blog/views.py
#api_view(['GET'])
def post_list(request, format=None):
"""
List all snippets, or create a new snippet.
"""
if request.method == 'GET':
lat = request.POST.get('user_lat', '13')
lon = request.POST.get('user_lon', '15')
userpoint = GEOSGeometry('POINT(' + lat + ' ' + lon + ')', srid=4326)
i=1
while i:
list_i = Post.objects.filter(point__distance_lte = (userpoint, D(km=i)))
list_total = str(',' + ' list_i')
post_list = list(chain(list_total))
if len(post_list) >= 0 :
break
serializer = PostSerializer(post_list, many=True)
return Response(serializer.data)
This has nothing to do with your serializer, or where you put it. The error traceback is telling you that the error happens in the view.
So, in your post_list view, you build up a list (also called post_list) which is populated by a list of strings. Then you try and put it through the PostSerializer, which of course is expecting a queryset of Posts.
I'm not sure what the point of the list is; seems like you should be passing the Posts directly to the serializer.

Django UUIDField issue

I am trying to get the UUIDField to work in python django using the following model:
class Ticket(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=50)
However when I try adding an instance of the model to the database it returns the following error:
TypeError at /tickets/
coercing to Unicode: need string or buffer, UUID found
The documentation of UUIDField is really short and doesn't really help me.
edit: I did import uuid and here is the full traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/tickets/
Django Version: 1.8.5
Python Version: 2.7.9
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'events',
'rest_framework')
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',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/viewsets.py" in view
87. return self.dispatch(request, *args, **kwargs)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
466. response = self.handle_exception(exc)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
463. response = handler(request, *args, **kwargs)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/mixins.py" in list
48. return Response(serializer.data)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/serializers.py" in data
663. ret = super(ListSerializer, self).data
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/serializers.py" in data
228. self._data = self.to_representation(self.instance)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/serializers.py" in to_representation
603. self.child.to_representation(item) for item in iterable
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/serializers.py" in to_representation
461. ret[field.field_name] = field.to_representation(attribute)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/relations.py" in to_representation
356. name = self.get_name(value)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/relations.py" in get_name
276. return six.text_type(obj)
Exception Type: TypeError at /tickets/
Exception Value: coercing to Unicode: need string or buffer, UUID found
Edit 2: My serializer looks like this:
class TicketSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Ticket
fields = ('url', 'id', 'name')
Edit 3:
I found the error. I made a mistake in my model. My unicode looked like this:
def __unicode__(self):
return self.id
And of course this does not work.
Probably you should use something like this:
def __unicode__(self):
return str(self.id)

Categories

Resources