Related
I'm looking for a solution to this error in Django. I sent you my forms and my view, and the error is as follows in my app . According to what appears to me in the tracer back, I would mark an error in the views line if form.is_valid() I already looked at a lot of things, but the truth is I'm already lost. I need help with the damn error.
The CargaForm object has no attribute 'get
Traceback
Request Method: POST
Request URL: http://127.0.0.1:8000/tienda/cargar/
Django Version: 3.2.13
Python Version: 3.10.6
Installed Applications:
['django.contrib.sites',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'captcha',
'productos.apps.ProductosConfig',
'web.apps.WebConfig',
'contacto.apps.ContactoConfig',
'tienda.apps.TiendaConfig',
'debug_toolbar']
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',
'debug_toolbar.middleware.DebugToolbarMiddleware']
Traceback (most recent call last):
File "C:\Users\PY310\diplo\lib\site-packages\django\core\handlers\exception.py", line 47,
in inner
response = get_response(request)
File "C:\Users\PY310\diplo\lib\site-packages\django\core\handlers\base.py", line 181, in
_get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\PY310\diplo\Proyectos\cerverzeria\cerverzeria\tienda\views.py", line 13, in
cargar_imagen
if form.is_valid():
File "C:\Users\PY310\diplo\lib\site-packages\django\forms\forms.py", line 175, in is_valid
return self.is_bound and not self.errors
File "C:\Users\PY310\diplo\lib\site-packages\django\forms\forms.py", line 170, in errors
self.full_clean()
File "C:\Users\PY310\diplo\lib\site-packages\django\forms\forms.py", line 372, in full_clean
self._clean_fields()
File "C:\Users\PY310\diplo\lib\site-packages\django\forms\forms.py", line 384, in
_clean_fields
value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
File "C:\Users\PY310\diplo\lib\site-packages\django\forms\widgets.py", line 263, in
value_from_datadict
return data.get(name)
Exception Type: AttributeError at /tienda/cargar/
Exception Value: 'CargaForm' object has no attribute 'get'
Forms------------------------------
from django.forms import ModelForm
from productos.models import Producto
class CargaForm(ModelForm):
class Meta:
model= Producto
fields = ['Producto', 'Marca', 'fecha_publicacion', 'imagen']
def __init__(self, *args, **Kwargs):
super(CargaForm, self).__init__(self, *args, **Kwargs)
Views--------------------------------
from django.shortcuts import render
from django.shortcuts import redirect
from tienda.forms import CargaForm
from productos.models import Producto
def cargar_imagen(request):
params={}
if request.method =='POST':
form = CargaForm(request.POST, request.FILES)
params['form'] = form
if form.is_valid():
producto = form.cleaned_data['producto']
fecha_publicacion = form.cleaned_data['fecha_publicacion']
imagen = form.cleaned_data['imagen']
nuevo_producto = Producto(producto=producto, fecha_publicacion=fecha_publicacion, imagen=imagen)
nuevo_producto.save()
return redirect('index')
else:
form= CargaForm()
params['form'] = form
return render(request, 'tienda/formulario.html', params)
your mistake is in the file 'widgets.py',and i suggest you should change like this.
change
return data.get(name)
into:
return data.POST.get(name)
Hello everyone! I'm working on a big project with Django Rest and I'm totally stuck with this one.
The project is something like Social network and I don't know why but everything seems to be correct, but every time I do "POST" method in the browser while debugging I see this error. I can provide you more information if you need it.
urls.py
from rest_framework import routers
from auth2.api.views import SendCodeView, VerifyCodeView
router = routers.DefaultRouter()
urlpatterns = []
router.register(r'code_send', SendCodeView, basename='code_send')
urlpatterns += router.urls
views.py
from django.contrib.auth import get_user_model
from django.utils import timezone
from rest_framework.authentication import get_authorization_header
from rest_framework import generics, status, views
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from auth2.api.serializers import SendCodeSerializer, VerifyCodeSerializer
from auth2.models import VerificationSMSCode
from core.api.serializers import UserSerializer
User = get_user_model()
logger = logging.getLogger('logzio')
class SendCodeView(ModelViewSet):
queryset = VerificationSMSCode.objects.all()
serializer_class = SendCodeSerializer
permission_classes = (AllowAny, )
def post(self, request, **kwargs):
print('DEBUG ' + request.data)
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
logger.info(f'send code log', extra=request.data)
VerificationSMSCode.create(serializer.user)
return Response(status=status.HTTP_204_NO_CONTENT)
models.py
from django.db import models
from django.utils.translation import gettext_lazy as _
from auth2.utils import get_random_code
from core.models import User
class VerificationSMSCode(models.Model):
STATUS_PENDING = 'pending'
STATUS_DELIVERED = 'delivered'
STATUS_ON_THE_WAY = 'on_the_way'
user = models.ForeignKey('core.User', related_name='verification_sms_codes', on_delete=models.CASCADE)
code = models.IntegerField(default=get_random_code)
created_at = models.DateTimeField(_("Created"), auto_now_add=True)
code_sent_at = models.DateTimeField(null=True, blank=True)
code_sent_error = models.TextField(blank=True)
sms_id = models.CharField(max_length=200, blank=True)
sms_status = models.CharField(default=STATUS_ON_THE_WAY, max_length=200, blank=True)
delivered_at = models.DateTimeField(null=True, blank=True)
code_used_at = models.DateTimeField(null=True, blank=True)
#classmethod
def create(cls, user):
old_code = cls.objects.filter(user=user, phone=user.phone, code_used_at__isnull=True)
if old_code:
old_code.update(code_sent_at=None)
return old_code.first()
else:
obj = cls.objects.create(user=user, phone=user.phone)
return obj
serializers.py
from rest_framework import serializers
from auth2.api import consts
from auth2.models import VerificationSMSCode
from chat.models import Chat
from core.models import User
class SendCodeSerializer(serializers.Serializer):
phone = serializers.IntegerField()
default_error_messages = {
"invalid_credentials": consts.INVALID_CREDENTIALS_ERROR,
"inactive_account": consts.INACTIVE_ACCOUNT_ERROR,
"invalid_code": consts.INVALID_CODE_ERROR,
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.user = None
def validate(self, attrs):
self.user, user_created = User.objects.get_or_create(phone=attrs['phone'])
if user_created:
chat = Chat.objects.create(title='Поддержка')
chat.users.add(self.user)
support_user = User.objects.filter(is_support=True).first()
if support_user:
chat.users.add(support_user)
if not self.user.is_active:
self.fail('inactive_account')
return attrs
def create(self, validated_data):
return VerificationSMSCode.objects.create(**validated_data)
I am trying to send a phone number which is where I'm sending random 4-digit code to and it fails.
If you have any ideas about how to fix this, please share.
UPD1
Here is the full Traceback:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/api/auth/code_send/
Django Version: 2.2.12
Python Version: 3.8.5
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'drf_yasg',
'mptt',
'django_mptt_admin',
'django_extensions',
'auth2',
'bcard',
'chat',
'core',
'filestorage',
'ckeditor',
'fcm_django',
'dbbackup']
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',
'core.middleware.RequestLoggerMiddleware',
'core.middleware.UpdateLastOnlineMiddleware']
Traceback:
File "D:\Projects\backend\venv\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "D:\Projects\backend\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "D:\Projects\backend\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Projects\backend\venv\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "D:\Projects\backend\venv\lib\site-packages\rest_framework\viewsets.py" in view
114. return self.dispatch(request, *args, **kwargs)
File "D:\Projects\backend\venv\lib\site-packages\rest_framework\views.py" in dispatch
505. response = self.handle_exception(exc)
File "D:\Projects\backend\venv\lib\site-packages\rest_framework\views.py" in handle_exception
465. self.raise_uncaught_exception(exc)
File "D:\Projects\backend\venv\lib\site-packages\rest_framework\views.py" in raise_uncaught_exception
476. raise exc
File "D:\Projects\backend\venv\lib\site-packages\rest_framework\views.py" in dispatch
502. response = handler(request, *args, **kwargs)
File "D:\Projects\backend\venv\lib\site-packages\rest_framework\mixins.py" in create
19. self.perform_create(serializer)
File "D:\Projects\backend\venv\lib\site-packages\rest_framework\mixins.py" in perform_create
24. serializer.save()
File "D:\Projects\backend\venv\lib\site-packages\rest_framework\serializers.py" in save
212. self.instance = self.create(validated_data)
File "D:\Projects\backend\auth2\api\serializers.py" in create
39. return VerificationSMSCode.objects.create(**validated_data)
File "D:\Projects\backend\venv\lib\site-packages\django\db\models\manager.py" in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "D:\Projects\backend\venv\lib\site-packages\django\db\models\query.py" in create
420. obj = self.model(**kwargs)
File "D:\Projects\backend\venv\lib\site-packages\django\db\models\base.py" in __init__
501. raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg))
Exception Type: TypeError at /api/auth/code_send/
Exception Value: VerificationSMSCode() got an unexpected keyword argument 'phone'
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
I'm trying to add a REST framework to my existing project. However, whenever I add 'groups' to the fields in my UserSerializer class, I get this traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/api/users/
Django Version: 1.10.7
Python Version: 3.6.3
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'crispy_forms',
'allauth',
'allauth.account',
'allauth.socialaccount',
'blended_learning_portal.users.apps.UsersConfig',
'blended_learning_portal.taskapp.celery.CeleryConfig',
'blended_learning_portal.unit.apps.UnitConfig',
'blended_learning_portal.data.apps.DataConfig',
'debug_toolbar',
'django_extensions',
'graphos',
'ckeditor',
'ckeditor_uploader',
'webpack_loader',
'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.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.locale.LocaleMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware']
Traceback:
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/relations.py" in to_representation
378. url = self.get_url(value, self.view_name, request, format)
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/relations.py" in get_url
316. return self.reverse(view_name, kwargs=kwargs, request=request, format=format)
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/reverse.py" in reverse
50. url = _reverse(viewname, args, kwargs, request, format, **extra)
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/reverse.py" in _reverse
63. url = django_reverse(viewname, args=args, kwargs=kwargs, **extra)
File "/home/michael/blportal/lib/python3.6/site-packages/django/urls/base.py" in reverse
91. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
File "/home/michael/blportal/lib/python3.6/site-packages/django/urls/resolvers.py" in _reverse_with_prefix
392. (lookup_view_s, args, kwargs, len(patterns), patterns)
During handling of the above exception (Reverse for 'group-detail' with arguments '()' and keyword arguments '{'pk': 2}' not found. 0 pattern(s) tried: []), another exception occurred:
File "/home/michael/blportal/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
42. response = get_response(request)
File "/home/michael/blportal/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/home/michael/blportal/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/michael/blportal/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/viewsets.py" in view
90. return self.dispatch(request, *args, **kwargs)
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
489. response = self.handle_exception(exc)
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception
449. self.raise_uncaught_exception(exc)
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
486. response = handler(request, *args, **kwargs)
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/mixins.py" in list
48. return Response(serializer.data)
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/serializers.py" in data
738. ret = super(ListSerializer, self).data
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/serializers.py" in data
262. self._data = self.to_representation(self.instance)
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/serializers.py" in to_representation
656. self.child.to_representation(item) for item in iterable
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/serializers.py" in <listcomp>
656. self.child.to_representation(item) for item in iterable
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/serializers.py" in to_representation
500. ret[field.field_name] = field.to_representation(attribute)
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/relations.py" in to_representation
520. for value in iterable
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/relations.py" in <listcomp>
520. for value in iterable
File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/relations.py" in to_representation
393. raise ImproperlyConfigured(msg % self.view_name)
Exception Type: ImproperlyConfigured at /api/users/
Exception Value: Could not resolve URL for hyperlinked relationship using view name "group-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.
The error seems to be coming from the UserSerializer, not the GroupSerializer. It obviously doesn't know where to look for group-detail (since I have that in the namespace api_v1. I'm not sure how to specify that, however.
api/views.py:
from django.contrib.auth.models import Group
from rest_framework import viewsets
from .serializers import UserSerializer, GroupSerializer
# We're using a modified User model
try:
from django.contrib.auth import get_user_model
except ImportError: # Django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all()
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
api/serializers.py:
from django.contrib.auth.models import Group
from rest_framework import serializers
try:
from django.contrib.auth import get_user_model
except ImportError: # Django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
extra_kwargs = {'url': {'view_name': 'api_v1:user-detail'}}
model = User
fields = ('url', 'username', 'email', 'groups')
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
extra_kwargs = {'url': {'view_name': 'api_v1:group-detail'}}
model = Group
lookup_field = 'id'
fields = ('url', 'id', 'name')
api/urls.py:
from django.conf.urls import url, include
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
]
I expect it's just a matter of telling Django where to look for group-detail. Any help would be greatly appreciated, this is driving me crazy.
I guess I overlooked that you could add a kwarg samespace for each field. I'm a bit silly. Anyway, changing this in my serializers.py was the solution:
extra_kwargs = {
'url': {'view_name': 'api_v1:user-detail'},
# Added this line:
'groups': {'view_name': 'api_v1:group-detail'},
}
By the way, this is necessary because rest_framework.routers.DefaultRouter doesn't handle namespaces at all. See this issue on Git.
Environment:
Request Method: GET
Request URL: http://www.qiuqingyu.cn/cnki_spider/todolist/
Django Version: 1.9
Python Version: 3.6.0
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'pagination',
'myapp']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'myapp.middleware.CheckSoureMiddware']
>
> Traceback:
File "/root/anaconda3/lib/python3.6/site-packages/django/template/utils.py" in __getitem__
86. return self._engines[alias]
During handling of the above exception ('django'), another exception occurred:
File "/root/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/root/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "./myapp/views.py" in todolist
29. return render(request, 'todolist.html', context=locals())
File "/root/anaconda3/lib/python3.6/site-packages/django/shortcuts.py" in render
67. template_name, context, request=request, using=using)
File "/root/anaconda3/lib/python3.6/site-packages/django/template/loader.py" in render_to_string
96. template = get_template(template_name, using=using)
File "/root/anaconda3/lib/python3.6/site-packages/django/template/loader.py" in get_template
26. engines = _engine_list(using)
File "/root/anaconda3/lib/python3.6/site-packages/django/template/loader.py" in _engine_list
143. return engines.all() if using is None else [engines[using]]
File "/root/anaconda3/lib/python3.6/site-packages/django/template/utils.py" in all
110. return [self[alias] for alias in self]
File "/root/anaconda3/lib/python3.6/site-packages/django/template/utils.py" in <listcomp>
110. return [self[alias] for alias in self]
File "/root/anaconda3/lib/python3.6/site-packages/django/template/utils.py" in __getitem__
101. engine = engine_cls(params)
File "/root/anaconda3/lib/python3.6/site-packages/django/template/backends/django.py" in __init__
31. options['libraries'] = self.get_templatetag_libraries(libraries)
File "/root/anaconda3/lib/python3.6/site-packages/django/template/backends/django.py" in get_templatetag_libraries
49. libraries = get_installed_libraries()
File "/root/anaconda3/lib/python3.6/site-packages/django/template/backends/django.py" in get_installed_libraries
131. for name in get_package_libraries(pkg):
File "/root/anaconda3/lib/python3.6/site-packages/django/template/backends/django.py" in get_package_libraries
144. module = import_module(entry[1])
File "/root/anaconda3/lib/python3.6/importlib/__init__.py" in import_module
126. return _bootstrap._gcd_import(name[level:], package, level)
Exception Type: SyntaxError at /cnki_spider/todolist/
Exception Value: invalid syntax (pagination_tags.py, line 225)
is there anybody met this question? How can i fix it?
I met this on CentOS, django is 1.9, I used uwsgi
python is 3.6
is there anybody met this question? How can i fix it?
I met this on CentOS, django is 1.9, I used uwsgi
python is 3.6
thank you!
The views.py is here:
import os
from django.http import HttpResponse, HttpResponseRedirect
from django.http import StreamingHttpResponse
from django.shortcuts import render, render_to_response
from myapp.forms import TodolistaddForm
from myapp.models import Todolist
import datetime
from django.core.paginator import Paginator
from django.core.paginator import EmptyPage
from django.core.paginator import PageNotAnInteger
import datetime
from .tasks import cnki_spider
# Create your views here.
def todolist(request):
todolist_lists = Todolist.objects.order_by("-id")
limit = 10
paginator = Paginator(todolist_lists, limit)
page = request.GET.get('page')
try:
todolist_lists = paginator.page(page)
except PageNotAnInteger:
todolist_lists = paginator.page(1)
except EmptyPage:
todolist_lists = paginator.page(paginator.num_pages)
return render(request, 'todolist.html', locals()) #error!!!!!!!!
def add_todolist(request):
if request.method == "POST":
body = request.POST['body']
add_date = datetime.datetime.now()
tag_type = 0
print(add_date)
print(body)
#add.delay(5,6)
cnki_spider.delay(body)
if body:
Todolist.objects.create(
body=body,
add_date=add_date,
tag_type=tag_type,
)
return HttpResponseRedirect('/todolist/')
else:
return HttpResponseRedirect('/todolist/')
def del_todolist(request):
rowid = request.GET['rowid']
body = Todolist.objects.filter(id=rowid)[0].body
Todolist.objects.filter(id=rowid).delete()
the_file_name = "data_out_" + body + ".xls"
os.remove(the_file_name)
print(the_file_name)
os.remove('data-detail-'+ body +'.txt')
return HttpResponse('{"code":0}')
def edit_todolist(request):
rowid = request.POST['rowid']
todolist_id = Todolist.objects.get(id=rowid)
todolist_id.body = request.POST['body']
todolist_id.save()
return HttpResponseRedirect('/todolist/')
def download_todolist(request):
rowid = request.POST['rowid']
todolist_id = Todolist.objects.get(id=rowid)
todolist_id.body = request.POST['body']
def readFile(fn, buf_size=262144):#大文件下载,设定缓存大小
f = open(fn, "rb")
while True:#循环读取
c = f.read(buf_size)
if c:
yield c
else:
break
f.close()
the_file_name = "data_out_"+todolist_id.body+".xls"
response = StreamingHttpResponse(readFile(the_file_name))
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="{0}"'.format(the_file_name)
return response
def chk_todolist(request):
rowid = request.GET['rowid']
todolist_id = Todolist.objects.get(id=rowid)
todolist_id.tag_type = request.GET['status']
todolist_id.save()
return HttpResponse('{"code":0}')
The latest django-pagination 1.0.7 was released on 2010-05-06. (Also Django 1.9 no longer supported I suggest you upgrade to a newer version or use a LTS version.) But Django 1.9 has it's own built in Pagination https://docs.djangoproject.com/en/1.9/topics/pagination/ as does Django 1.8 LTS and Django 1.11. I suggest you use the built in django.core.paginator and stop using the 2010 release of django-pagination.
remove pagination from installed apps from settings.py:
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'pagination', //remove this line
'phone_field',
]