Hi stackoverflow people,
In my project i try to code a view which will manage am external api which will be used to fetch some datas, present them and store them in a database.
When i try to access to my view, i encounter the following error
Traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/commande/recherche
Django Version: 1.7.1
Python Version: 3.4.2
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'commands')
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')
Traceback:
File "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
87. response = middleware_method(request)
File "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/middleware/common.py" in process_request
72. if (not urlresolvers.is_valid_path(request.path_info, urlconf) and
File "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/core/urlresolvers.py" in is_valid_path
619. resolve(path, urlconf)
File "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/core/urlresolvers.py" in resolve
494. return get_resolver(urlconf).resolve(path)
File "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/core/urlresolvers.py" in resolve
345. sub_match = pattern.resolve(new_path)
File "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/core/urlresolvers.py" in resolve
345. sub_match = pattern.resolve(new_path)
File "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/core/urlresolvers.py" in resolve
224. return ResolverMatch(self.callback, args, kwargs, self.name)
File "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/core/urlresolvers.py" in callback
231. self._callback = get_callable(self._callback_str)
File "/home/user/.virtualenvs/commands-project/lib/python3.4/functools.py" in wrapper
434. result = user_function(*args, **kwds)
File "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/core/urlresolvers.py" in get_callable
97. mod = import_module(mod_name)
File "/home/user/.virtualenvs/commands-project/lib/python3.4/importlib/__init__.py" in import_module
109. return _bootstrap._gcd_import(name[level:], package, level)
File "/home/user/workspace/Python/commands-project/project/commands/views.py" in <module>
6. from .form import CommandesForm, CommandeForm
File "/home/user/workspace/Python/commands-project/project/commands/form.py" in <module>
11. class CommandeForm(forms.ModelForm):
File "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/forms/models.py" in __new__
293. opts.model.__name__)
Exception Type: AttributeError at /commande/recherche
Exception Value: 'Commande' object has no attribute '__name__'
My models.py :
from django.db import models
class Client(models.Model):
client = models.IntegerField(null=True)
class Commandes(models.Model):
date_debut = models.DateField()
date_fin = models.DateField()
id_groups = models.CharField(max_length=100)
id_client = models.ForeignKey(Client)
class Commande(models.Model):
id_flux = models.CharField(max_length=100, null=True, blank=True)
id_commande = models.CharField(max_length=100, null=True, blank=True)
id_client = models.ForeignKey(Client)
My views.py :
from django.shortcuts import render
from http.client import HTTPConnection
from urllib.parse import urlparse, urlunparse
from .form import CommandesForm, CommandeForm
import requests
def resultat(request):
return render(request, 'commands/resultat.html')
def recherche(request):
if request.method == 'POST':
if 'Commandes' in request.POST:
pass
if 'Commande' in request.POST:
pass
else:
formCommandes = CommandesForm()
formCommande = CommandeForm()
return render(request, 'commands/recherche.html', {'formCommandes': formCommandes })
And my form.py:
from django import forms
from .models import Commande, Commandes
class CommandesForm(forms.ModelForm):
class Meta:
model = Commandes()
fields = ('date_debut', 'date_fin', 'id_groups')
class CommandeForm(forms.ModelForm):
class Meta:
model = Commande()
fields = ('date_debut', 'date_fin', 'id_groups', 'id_client', 'id_flux',
'id_commande')
This is the following exception that i need to manage :
'Commande' object has no attribute 'name'
I know that the 'name' attribute is in the class not the instance.
The fact that i can't figure out is, why the exception is raise with 'Commande' object and not 'Commands' object
Related
I am using DRF and Django(4.0) to make posts in a Instagram Clone. The models of the following are available below. I have successfully implemented post request, but am having problems implementing get request.
I have tried to nest two serializer inside the PostViewSerializer to serialize the data. However I am getting the following error when I do a get request.
Got AttributeError when attempting to get a value for field 'post_image' on serializer 'PostViewSerializer'.
The serializer field might be named incorrectly and not match any attribute or key on the `Post` instance.
Original exception text was: 'Post' object has no attribute 'post_image'.
Now, I should tell you that there is not requirement that the post should contain atleast one image or video it could contain entirely either videos or posts. So, could that be the cause of the above error. If so, how can I solve it?
#models.py
class Post(Authorable, Model):
created_at = models.DateTimeField(default=timezone.now)
caption = TextField(max_length=350)
class Images(Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
images = models.FileField(upload_to="images/")
class Videos(Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
videos = models.FileField(upload_to="videos/")
#behaviours.py
class Authorable(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
abstract = True
def get_user(self):
return self.user.id
#serializers.py
class ImageViewSerializer(serializers.ModelSerializer):
class Meta:
model = Images
fields = ['images']
class VideoViewSerializer(serializers.ModelSerializer):
class Meta:
model = Videos
fields = [ 'videos']
class PostViewSerializer(serializers.ModelSerializer):
post_image = ImageViewSerializer()
post_video = VideoViewSerializer()
class Meta:
model = Post
fields = ['post_image', 'post_video', 'caption','user']
class PostUpload(APIView):
permission_classes = [IsAuthenticated]
parser_classes = [MultiPartParser, FormParser]
serializer_class = PostSerializer
def get(self, request):
user = request.user
serializer = PostViewSerializer(Post.objects.filter(user=user), many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
Edit 1:(With Full Traceback Error)
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/api/user/post/
Django Version: 4.0
Python Version: 3.8.10
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework_simplejwt',
'core',
'authentication',
'socialuser']
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 (most recent call last):
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\fields.py", line 457, in get_attribute
return get_attribute(instance, self.source_attrs)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\fields.py", line 97, in get_attribute
instance = getattr(instance, attr)
During handling of the above exception ('Post' object has no attribute 'images'), another exception occurred:
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\django\views\generic\base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\suyas\Desktop\Memestagram\socialuser\views.py", line 22, in get
return Response(serializer.data, status=status.HTTP_200_OK)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\serializers.py", line 768, in data
ret = super().data
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\serializers.py", line 253, in data
self._data = self.to_representation(self.instance)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\serializers.py", line 686, in to_representation
return [
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\serializers.py", line 687, in <listcomp>
self.child.to_representation(item) for item in iterable
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\serializers.py", line 509, in to_representation
attribute = field.get_attribute(instance)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\fields.py", line 490, in get_attribute
raise type(exc)(msg)
Exception Type: AttributeError at /api/user/post/
Exception Value: Got AttributeError when attempting to get a value for field `post_image` on serializer `PostViewSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Post` instance.
Original exception text was: 'Post' object has no attribute 'images'.
My Serializer
class PostViewSerializer(serializers.ModelSerializer):
# access ForeignKey in reverse 🖟
post_image = ImageViewSerializer(source='images', many=True)
post_video = VideoViewSerializer(source='videos', many=True)
class Meta:
model = Post
fields = ['post_image', 'post_video', 'caption','user']
There is no ImageField, ForeignKey, ManyToManyField, etc. with post_image as name. You can access the images with .images. This thus means that you use this as source:
class PostViewSerializer(serializers.ModelSerializer):
# access ForeignKey in reverse 🖟
post_image = ImageViewSerializer(source='images_set', many=True)
post_video = VideoViewSerializer(source='videos_set', many=True)
class Meta:
model = Post
fields = ['post_image', 'post_video', 'caption','user']
I have created a custom user model 'User' and have declared in settings.py as AUTH_USER_MODEL
Also i have two other models consumer and workman which has an onetoone relation with my custom user.
i created two forms for registering customer and workman but as i fill form(it doesnt even check validation) and submit, it says: Manager isn't available; 'auth.User' has been swapped for 'accounts.User'
models.py:
from django.contrib.auth.models import AbstractUser
from django.contrib.auth import get_user_model
# Create your models here.
class User(AbstractUser):
class Types(models.TextChoices):
CONSUMER = "CONSUMER" , "Consumer"
WORKMAN = "WORKMAN" , "Workman"
type = models.CharField(max_length=20,choices=Types.choices,default=Types.WORKMAN)
is_consumer = models.BooleanField(default=False)
is_workman = models.BooleanField(default=False)
class Consumer(models.Model):
user = models.OneToOneField(get_user_model(),on_delete=models.CASCADE,primary_key=True)
location = models.CharField(max_length=100)
class Workman(models.Model):
user = models.OneToOneField(get_user_model(),on_delete=models.CASCADE,primary_key=True)
contact = models.CharField(max_length=100)
views.py:
from .forms import ConsumerCreationForm, WorkmanCreationForm
from .models import Workman,Consumer
class consumersignupview(CreateView):
model = Consumer
form_class = ConsumerCreationForm
template_name = 'accounts/register.html'
success_url = '/'
class workmansignupview(CreateView):
model = Workman
form_class = WorkmanCreationForm
template_name = 'accounts/register.html'
success_url = '/'
forms.py:
from django.contrib.auth.forms import UserCreationForm
from django import forms
from .models import Consumer,Workman
class ConsumerCreationForm(UserCreationForm):
location = forms.CharField( max_length=100, required=False)
class meta(UserCreationForm.Meta):
model = Consumer
class WorkmanCreationForm(UserCreationForm):
contact = forms.CharField(max_length=100)
class meta(UserCreationForm.Meta):
model = Workman
error:
full traceback:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/account/wregister/
Django Version: 3.2.9
Python Version: 3.8.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts.apps.AccountsConfig']
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 (most recent call last):
File "F:\Project Work\Proxy-Model\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "F:\Project Work\Proxy-Model\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "F:\Project Work\Proxy-Model\venv\lib\site-packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "F:\Project Work\Proxy-Model\venv\lib\site-packages\django\views\generic\base.py", line 98, in dispatch
return handler(request, *args, **kwargs)
File "F:\Project Work\Proxy-Model\venv\lib\site-packages\django\views\generic\edit.py", line 172, in post
return super().post(request, *args, **kwargs)
File "F:\Project Work\Proxy-Model\venv\lib\site-packages\django\views\generic\edit.py", line 141, in post
if form.is_valid():
File "F:\Project Work\Proxy-Model\venv\lib\site-packages\django\forms\forms.py", line 175, in is_valid
return self.is_bound and not self.errors
File "F:\Project Work\Proxy-Model\venv\lib\site-packages\django\forms\forms.py", line 170, in errors
self.full_clean()
File "F:\Project Work\Proxy-Model\venv\lib\site-packages\django\forms\forms.py", line 374, in full_clean
self._post_clean()
File "F:\Project Work\Proxy-Model\venv\lib\site-packages\django\contrib\auth\forms.py", line 117, in _post_clean
super()._post_clean()
File "F:\Project Work\Proxy-Model\venv\lib\site-packages\django\forms\models.py", line 413, in _post_clean
self.instance.full_clean(exclude=exclude, validate_unique=False)
File "F:\Project Work\Proxy-Model\venv\lib\site-packages\django\db\models\base.py", line 1223, in full_clean
self.clean()
File "F:\Project Work\Proxy-Model\venv\lib\site-packages\django\contrib\auth\models.py", line 371, in clean
self.email = self.__class__.objects.normalize_email(self.email)
File "F:\Project Work\Proxy-Model\venv\lib\site-packages\django\db\models\manager.py", line 187, in __get__
raise AttributeError(
Exception Type: AttributeError at /account/wregister/
Exception Value: Manager isn't available; 'auth.User' has been swapped for 'accounts.User'
This error is a repeat of this issue. You are likely importing the wrong user model somewhere.
i am trying to create list and detail api view. I have database with over 100K object
model.py
from django.db import models
# Create your models here.
class Banks(models.Model):
name = models.CharField(max_length=49, blank=True, null=True)
id = models.BigIntegerField(primary_key=True)
class Meta:
managed = False
db_table = 'banks'
class Branches(models.Model):
ifsc = models.CharField(primary_key=True, max_length=11)
bank = models.ForeignKey(Banks, models.DO_NOTHING, blank=True, null=True)
branch = models.CharField(max_length=250, blank=True, null=True)
address = models.CharField(max_length=250, blank=True, null=True)
city = models.CharField(max_length=50, blank=True, null=True)
district = models.CharField(max_length=50, blank=True, null=True)
state = models.CharField(max_length=26, blank=True, null=True)
class Meta:
managed = False
db_table = 'branches'
serializers.py
from rest_framework import serializers
from .models import Branches, Banks
class BankSerializer(serializers.ModelSerializer):
class Meta:
model = Banks
fields= ['name', 'id']
class BranchSerializer(serializers.ModelSerializer):
bank = BankSerializer(many=True,read_only=True)
class Meta:
model = Branches
fields= ['ifsc','bank','branch','address','city','district','state']
views.py
from rest_framework import viewsets
from .serializers import BranchSerializer
from rest_framework import viewsets
class BankViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed.
"""
queryset = Branches.objects.all()
serializer_class = BranchSerializer
I tried using .get_queryset(), .filter() in place of .all() but its still throwing error
error datail
Request Method: GET
Request URL: http://127.0.0.1:8000/bankdetailapi/
Django Version: 3.2.3
Python Version: 3.9.5
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'api',
'rest_framework',
'corsheaders',
'django_filters']
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 (most recent call last):
File "C:\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python39\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Python39\lib\site-packages\rest_framework\viewsets.py", line 125, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Python39\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "C:\Python39\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Python39\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "C:\Python39\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Python39\lib\site-packages\rest_framework\mixins.py", line 46, in list
return Response(serializer.data)
File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 745, in data
ret = super().data
File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 246, in data
self._data = self.to_representation(self.instance)
File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 663, in to_representation
return [
File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 664, in <listcomp>
self.child.to_representation(item) for item in iterable
File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 515, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 663, in to_representation
return [
Exception Type: TypeError at /bankdetailapi/
Exception Value: 'Banks' object is not iterable
i also made sure that i am not making any typo. and most of the solutions i found on stack is about replacing .all() method with .get_queryset or .filter which didnt work for me.
i registered my models in admin.py its visible through admin
Remove many=True in serializer. ForeignKey links to a single Banks instance, therefore it is not many.
class BranchSerializer(serializers.ModelSerializer):
bank = BankSerializer(read_only=True)
class Meta:
model = Branches
fields= ['ifsc','bank','branch','address','city','district','state']
extra_kwargs = {
'bank': {'allow_null': True, 'required': False},
}
The problem is in BankSerializer, which tries to fetch all banks with reference to Branch instance:
bank = BankSerializer(many=True,read_only=True)
Your Branch model has FK reference to Banks, so there can only be one. You can fix the error if you remove many=true:
bank = BankSerializer(read_only=True)
Hi All I faced this issue while getting API response. I am using django==2.1.7. Below I am adding my code snippet
models.py
The model contains topic names(en,bn), taglist(string), and Bucket_id or topic_id
class Topics(models.Model):
id = models.AutoField(primary_key=True)
name_en = models.CharField(max_length=70, blank=False, default='')
name_bn = models.CharField(max_length=70, blank=False, default='')
tags = models.TextField(blank=False, default='')
bucket_id = models.IntegerField()
def set_tags(self, x):
self.tags = json.dumps(x)
def get_tags(self):
return json.loads(self.tags)
class Meta:
managed = True
db_table = 'follow_topics'
serialize.py
TopicSeializer used for JSON serialize the model
from rest_framework import serializers
from .models import Topics
class TopicSerializer(serializers.ModelSerializer):
class Meta:
model = Topics
fields = ['name_en','name_bn','tags', 'bucket_id']
views.py
get_topic function gives me the list of the topic from the model
#api_view(('GET',))
def get_topics(requests):
topic_id = requests.GET.get('topic_id', None)
post_data = Topics.objects.filter(bucket_id=topic_id)
serialize_data = TopicSerializer(post_data, many=True)
return Response({"status": "success", "data": serialize_data})
I got serializable error. This error looks frustrating for me. Please help me share some useful resource or way that I can fix this error
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/feed/v1/get_topics?topic_id=2
Django Version: 2.1.7
Python Version: 3.6.8
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'debug_toolbar',
'rest_framework',
'feedv1']
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',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.BrokenLinkEmailsMiddleware',
'django.middleware.common.CommonMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware']
Traceback:
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
156. response = self.process_exception_by_middleware(e, request)
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
154. response = response.render()
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/django/template/response.py" in render
106. self.content = self.rendered_content
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/response.py" in rendered_content
72. ret = renderer.render(self.data, accepted_media_type, context)
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/renderers.py" in render
733. context = self.get_context(data, accepted_media_type, renderer_context)
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/renderers.py" in get_context
688. 'content': self.get_content(renderer, data, accepted_media_type, renderer_context),
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/renderers.py" in get_content
424. content = renderer.render(data, accepted_media_type, renderer_context)
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/renderers.py" in render
107. allow_nan=not self.strict, separators=separators
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/utils/json.py" in dumps
28. return json.dumps(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py" in dumps
238. **kw).encode(obj)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py" in encode
201. chunks = list(chunks)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py" in _iterencode
430. yield from _iterencode_dict(o, _current_indent_level)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py" in _iterencode_dict
404. yield from chunks
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py" in _iterencode
437. o = _default(o)
File "/Users/luo/tutorial-env/lib/python3.6/site-packages/rest_framework/utils/encoders.py" in default
68. return super(JSONEncoder, self).default(obj)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py" in default
180. o.__class__.__name__)
Exception Type: TypeError at /feed/v1/get_topics
Exception Value: Object of type 'TopicSerializer' is not JSON serializable
You need to access the .data property of the serializer
return Response({"status": "success", "data": serialize_data.data})
I am receiving this error when trying to login via google, I've tried just about everything I can think of and similar issues on SO don't seem to help. I have a custom user model setup as such:
models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
class Departments(models.Model):
name = models.CharField(max_length=255, unique=True)
def __str__(self):
return self.name
class AlluredUser(AbstractUser):
departments = models.ManyToManyField(Departments)
def __str__(self):
return self.username
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import AlluredUser
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = AlluredUser
fields = ('username', 'email')
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = AlluredUser
fields = ('username', 'email')
Social Auth Pipeline
SOCIAL_AUTH_PIPELINE = (
'social_core.pipeline.social_auth.social_details',
'social_core.pipeline.social_auth.social_uid',
'social_core.pipeline.social_auth.auth_allowed',
'social_core.pipeline.social_auth.social_user',
'social_core.pipeline.user.get_username',
'social_core.pipeline.social_auth.associate_by_email',
'social_core.pipeline.user.create_user',
'social_core.pipeline.social_auth.associate_user',
'social_core.pipeline.social_auth.load_extra_data',
'social_core.pipeline.user.user_details'
)
Error Traceback
AttributeError at /auth/complete/google-oauth2/
'NoneType' object has no attribute 'provider'
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/auth/complete/google-oauth2/?state=8XLcbxz6sPSPOwJfOIXWOud88UJ5YtL2&code=4/twHRVLHTMzBV99K-VvektvJfjGuJYGBvqi254dWTuA2dLmbNFw3fIp8l5pdYSqKK89ONPGrxInG39pH8Wf-fpas&scope=email%20profile%20https://www.googleapis.com/auth/userinfo.profile%20https://www.googleapis.com/auth/userinfo.email%20openid&authuser=0&hd=allured.com&session_state=2403f8348307b18b8ab460026d3c88b1b18d759f..5dbb&prompt=none
Django Version: 2.2.4
Python Version: 3.7.4
Installed Applications:
['user.apps.UserConfig',
'issue_tracker.apps.IssueTrackerConfig',
'ytd_reports.apps.YtdReportsConfig',
'stats.apps.StatsConfig',
'scheduler.apps.SchedulerConfig',
'submissions.apps.SubmissionsConfig',
'dash_app.apps.DashAppConfig',
'contact.apps.ContactConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.humanize',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'social_django']
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',
'social_django.middleware.SocialAuthExceptionMiddleware',
'dashboard.middleware.loginRequired.LoginRequiredMiddleware']
Traceback:
File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
44. response = view_func(request, *args, **kwargs)
File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\social_django\utils.py" in wrapper
49. return func(request, backend, *args, **kwargs)
File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\social_django\views.py" in complete
33. *args, **kwargs)
File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\social_core\actions.py" in do_complete
71. social_user.provider)
Exception Type: AttributeError at /auth/complete/google-oauth2/
Exception Value: 'NoneType' object has no attribute 'provider'
I'm guessing it has something to do with the custom user model I created since I didn't have this problem beforehand. Any help would be much appreciated.
The error on the link doesn't match what you mention in the title.
For the traceback, the solution is just to add this:
SESSION_COOKIE_SECURE = False