Serializer object has no attribute '_writable_fields' - django

I have started writing an app in django with mongodb (my first time). But I'm getting this error related to my DRF-mongoengine serializer. The error reads:
AttributeError: 'UserSerializer' object has no attribute '_writable_fields'
Full Traceback is as follows:
Traceback (most recent call last):
web_1 | File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response
web_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs)
web_1 | File "/usr/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
web_1 | return view_func(*args, **kwargs)
web_1 | File "/usr/local/lib/python2.7/site-packages/rest_framework/viewsets.py", line 85, in view
web_1 | return self.dispatch(request, *args, **kwargs)
web_1 | File "/usr/local/lib/python2.7/site-packages/rest_framework/views.py", line 407, in dispatch
web_1 | response = self.handle_exception(exc)
web_1 | File "/usr/local/lib/python2.7/site-packages/rest_framework/views.py", line 404, in dispatch
web_1 | response = handler(request, *args, **kwargs)
web_1 | File "/usr/local/lib/python2.7/site-packages/rest_framework/mixins.py", line 20, in create
web_1 | serializer.is_valid(raise_exception=True)
web_1 | File "/usr/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 186, in is_valid
web_1 | self._validated_data = self.run_validation(self.initial_data)
web_1 | File "/usr/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 364, in run_validation
web_1 | value = self.to_internal_value(data)
web_1 | File "/usr/local/lib/python2.7/site-packages/rest_framework_mongoengine/serializers.py", line 197, in to_internal_value
web_1 | for field in self._writable_fields:
web_1 | AttributeError: 'UserSerializer' object has no attribute '_writable_fields'
This seems to be some problem with the DRF-mongoengine version because when I was using 3.3.0, I had an error about no no attribute named "get_field_names". To resolve that, I moved to 3.3.1 which is the lastest version and I started getting this one. My requirements.txt file is:
blinker == 1.1
Django==1.8.0
django-rest-framework-mongoengine==3.3.1
gunicorn==19.6.0
django-admin-generator==2.0.0
pymongo==2.8
mongoengine==0.9.0
djangorestframework==3.0.4
And my serializers.py file is:
from rest_framework_mongoengine import serializers
from api.models import User
class UserSerializer(serializers.DocumentSerializer):
class Meta:
model = User
fields = '__all__'
My models are:
from mongoengine import *
class User(Document):
name = StringField(max_length=50, required=True)
email = EmailField(max_length=254, required=True)
password = StringField(max_length=100, required=True)
role = StringField(max_length=16, default='basic', required=True)
def __unicode__(self):
return self.name, self.email
Any idea as to what happens to be the problem?

Related

How to establish a One to One relation in django model in mongo db?

I am using mongo db with djongo in django. I have two models Employee and PresentEmployee.
Employee:
class Employee(models.Model):
employee_id = models.CharField(primary_key=True, max_length=10, null=False, blank=False)
employee_name = models.CharField(max_length=200, null=False, blank=False)
email = models.EmailField(max_length=500, null=True, blank=True)
def __str__(self):
return self.employee_name
PresentEmployee:
class PresentEmployee(models.Model):
employee_id = models.OneToOneField(Employee, on_delete=models.CASCADE)
present_id = models.IntegerField(null=False, blank=False)
id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False)
def __str__(self):
return str(self.employee_id)
when I try to add a new object to PresentEmployee, I am getting the error
web_1 | Traceback (most recent call last):
web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 808, in __iter__
web_1 | yield from iter(self._query)
web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 167, in __iter__
web_1 | yield self._align_results(doc)
web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 269, in _align_results
web_1 | if selected.table == self.left_table:
web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/sql_tokens.py", line 133, in table
web_1 | return alias2token[name].table
web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/sql_tokens.py", line 133, in table
web_1 | return alias2token[name].table
web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/sql_tokens.py", line 133, in table
web_1 | return alias2token[name].table
web_1 | [Previous line repeated 917 more times]
web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/sql_tokens.py", line 130, in table
web_1 | name = self.given_table
web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/sql_tokens.py", line 141, in given_table
web_1 | name = self._token.get_real_name()
web_1 | File "/usr/local/lib/python3.10/site-packages/sqlparse/sql.py", line 361, in get_real_name
web_1 | return self._get_first_name(dot_idx)
web_1 | File "/usr/local/lib/python3.10/site-packages/sqlparse/sql.py", line 386, in _get_first_name
web_1 | return token.get_name()
web_1 | File "/usr/local/lib/python3.10/site-packages/sqlparse/sql.py", line 355, in get_name
web_1 | return self.get_alias() or self.get_real_name()
web_1 | File "/usr/local/lib/python3.10/site-packages/sqlparse/sql.py", line 344, in get_alias
web_1 | _, ws = self.token_next_by(t=T.Whitespace)
web_1 | File "/usr/local/lib/python3.10/site-packages/sqlparse/sql.py", line 244, in token_next_by
web_1 | return self._token_matching(funcs, idx, end)
web_1 | File "/usr/local/lib/python3.10/site-packages/sqlparse/sql.py", line 223, in _token_matching
web_1 | if func(token):
web_1 | File "/usr/local/lib/python3.10/site-packages/sqlparse/sql.py", line 242, in <lambda>
web_1 | funcs = lambda tk: imt(tk, i, m, t)
web_1 | File "/usr/local/lib/python3.10/site-packages/sqlparse/utils.py", line 100, in imt
web_1 | elif types and any(token.ttype in ttype for ttype in types):
web_1 | File "/usr/local/lib/python3.10/site-packages/sqlparse/utils.py", line 100, in <genexpr>
web_1 | elif types and any(token.ttype in ttype for ttype in types):
web_1 | File "/usr/local/lib/python3.10/site-packages/sqlparse/tokens.py", line 19, in __contains__
web_1 | return item is not None and (self is item or item[:len(self)] == self)
web_1 | RecursionError: maximum recursion depth exceeded in comparison
web_1 |
web_1 | The above exception was the direct cause of the following exception:
web_1 |
web_1 | Traceback (most recent call last):
web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/cursor.py", line 76, in fetchone
web_1 | return self.result.next()
web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 797, in __next__
web_1 | result = next(self._result_generator)
web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 830, in __iter__
web_1 | raise exe from e
web_1 | djongo.exceptions.SQLDecodeError:
web_1 |
web_1 | Keyword: FAILED SQL: SELECT %(0)s AS "a" FROM "employees_employee" WHERE "employees_employee"."employee_id" = %(1)s LIMIT 1
web_1 | Params: (1, 'EMP1')
web_1 | Version: 1.3.6
web_1 | Sub SQL: None
web_1 | FAILED SQL: None
web_1 | Params: None
web_1 | Version: None
web_1 |
web_1 | The above exception was the direct cause of the following exception:
web_1 |
web_1 | Traceback (most recent call last):
web_1 | File "/usr/local/lib/python3.10/site-packages/django/db/utils.py", line 98, in inner
web_1 | return func(*args, **kwargs)
web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/cursor.py", line 81, in fetchone
web_1 | raise db_exe from e
web_1 | djongo.database.DatabaseError
web_1 |
web_1 | The above exception was the direct cause of the following exception:
web_1 |
web_1 | Traceback (most recent call last):
web_1 | File "/usr/local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
web_1 | response = get_response(request)
web_1 | File "/usr/local/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response
web_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs)
web_1 | File "/usr/local/lib/python3.10/site-packages/django/contrib/admin/options.py", line 686, in wrapper
web_1 | return self.admin_site.admin_view(view)(*args, **kwargs)
web_1 | File "/usr/local/lib/python3.10/site-packages/django/utils/decorators.py", line 133, in _wrapped_view
web_1 | response = view_func(request, *args, **kwargs)
web_1 | File "/usr/local/lib/python3.10/site-packages/django/views/decorators/cache.py", line 62, in _wrapped_view_func
web_1 | response = view_func(request, *args, **kwargs)
web_1 | File "/usr/local/lib/python3.10/site-packages/django/contrib/admin/sites.py", line 242, in inner
web_1 | return view(request, *args, **kwargs)
web_1 | File "/usr/local/lib/python3.10/site-packages/django/contrib/admin/options.py", line 1890, in add_view
web_1 | return self.changeform_view(request, None, form_url, extra_context)
web_1 | File "/usr/local/lib/python3.10/site-packages/django/utils/decorators.py", line 46, in _wrapper
web_1 | return bound_method(*args, **kwargs)
web_1 | File "/usr/local/lib/python3.10/site-packages/django/utils/decorators.py", line 133, in _wrapped_view
web_1 | response = view_func(request, *args, **kwargs)
web_1 | File "/usr/local/lib/python3.10/site-packages/django/contrib/admin/options.py", line 1750, in changeform_view
web_1 | return self._changeform_view(request, object_id, form_url, extra_context)
web_1 | File "/usr/local/lib/python3.10/site-packages/django/contrib/admin/options.py", line 1796, in _changeform_view
web_1 | form_validated = form.is_valid()
web_1 | File "/usr/local/lib/python3.10/site-packages/django/forms/forms.py", line 205, in is_valid
web_1 | return self.is_bound and not self.errors
web_1 | File "/usr/local/lib/python3.10/site-packages/django/forms/forms.py", line 200, in errors
web_1 | self.full_clean()
web_1 | File "/usr/local/lib/python3.10/site-packages/django/forms/forms.py", line 439, in full_clean
web_1 | self._post_clean()
web_1 | File "/usr/local/lib/python3.10/site-packages/django/forms/models.py", line 492, in _post_clean
web_1 | self.instance.full_clean(exclude=exclude, validate_unique=False)
web_1 | File "/usr/local/lib/python3.10/site-packages/django/db/models/base.py", line 1464, in full_clean
web_1 | self.clean_fields(exclude=exclude)
web_1 | File "/usr/local/lib/python3.10/site-packages/django/db/models/base.py", line 1516, in clean_fields
web_1 | setattr(self, f.attname, f.clean(raw_value, self))
web_1 | File "/usr/local/lib/python3.10/site-packages/django/db/models/fields/__init__.py", line 755, in clean
web_1 | self.validate(value, model_instance)
web_1 | File "/usr/local/lib/python3.10/site-packages/django/db/models/fields/related.py", line 1090, in validate
web_1 | if not qs.exists():
web_1 | File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 1225, in exists
web_1 | return self.query.has_results(using=self.db)
web_1 | File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/query.py", line 592, in has_results
web_1 | return compiler.has_results()
web_1 | File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1363, in has_results
web_1 | return bool(self.execute_sql(SINGLE))
web_1 | File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1406, in execute_sql
web_1 | val = cursor.fetchone()
web_1 | File "/usr/local/lib/python3.10/site-packages/django/db/utils.py", line 97, in inner
web_1 | with self:
web_1 | File "/usr/local/lib/python3.10/site-packages/django/db/utils.py", line 91, in __exit__
web_1 | raise dj_exc_value.with_traceback(traceback) from exc_value
web_1 | File "/usr/local/lib/python3.10/site-packages/django/db/utils.py", line 98, in inner
web_1 | return func(*args, **kwargs)
web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/cursor.py", line 81, in fetchone
web_1 | raise db_exe from e
web_1 | django.db.utils.DatabaseError
How can I establish a One to One relation from Employee model to PresentEmployee model. Like a OneToOneField in sql db like postgresql.
note: never mind the web_1 |, it is because I am using docker.
If you are using djongo, you can create EmbeddedField class:
class EmbeddedField(MongoField):
def __init__(
self,
model_container: typing.Type[Model],
model_form_class: typing.Type[forms.ModelForm] = None,
model_form_kwargs: dict = None,
*args,
**kwargs
):
After that, with your example you can create something like this
class Employee(models.Model):
employee_id = models.ObjectIdField()
employee_name = models.CharField(max_length=200, null=False, blank=False)
email = models.EmailField(max_length=500, null=True, blank=True)
def __str__(self):
return self.employee_name
class PresentEmployee(models.Model):
present_id = models.ObjectIdField()
employee = models.EmbeddedField(model_container=Employee)
id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False)
def __str__(self):
return str(self.employee_id)

why is Django not accepting the file sending from React Native app?

I am using Django for the Backend Server and React Native for a mobile app I am trying to upload an image from there but it is giving a 500 server error.
Views.py form Django
#api_view(['POST'])
def setFakeProfile(request):
if request.method=='POST':
user = Token.objects.get(key = request.META.get('HTTP_AUTHORIZATION').split(' ')[1]).user
profile = Profile.objects.get(user=user)
fakeProfiles = profile.fakeProfiles.filter(isProfileReadyToUse=False)
print(request.data)
print(request.FILES)
if fakeProfiles.exists():
fakeProfile = fakeProfiles[0]
fakeProfile.displayName = request.data["displayName"]
fakeProfile.profilePicture = request.FILES.get('profilePicture')
fakeProfile.isProfileReadyToUse = True
fakeProfile.save()
return Response({'status':'success', 'id':fakeProfile.id})
else:
return Response({'status':'failed', "message":"First select the chating platform."})
return Response({
'status':'success',
})
return Response({'status':'failed'})
The error that I am getting is there. I knew about the error and I also tried a lot of ways to resolve it but not still don't know how to fix it.
{'_parts': [['displayName', 'name'], ['profilePicture', {'cancelled': False, 'type': 'image', 'uri': 'file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540sumit2232%252FUnknownChats/ImagePicker/584abe5b-7f5e-45cb-81bd-fcb5751e3ed4.png', 'width': 1692, 'height': 1692}]]}
app_1 | <MultiValueDict: {}>
app_1 | Internal Server Error: /setFakeProfile/
app_1 | Traceback (most recent call last):
app_1 | File "/py/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
app_1 | response = get_response(request)
app_1 | File "/py/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
app_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs)
app_1 | File "/py/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
app_1 | return view_func(*args, **kwargs)
app_1 | File "/py/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view
app_1 | return self.dispatch(request, *args, **kwargs)
app_1 | File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch
app_1 | response = self.handle_exception(exc)
app_1 | File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception
app_1 | self.raise_uncaught_exception(exc)
app_1 | File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
app_1 | raise exc
app_1 | File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch
app_1 | response = handler(request, *args, **kwargs)
app_1 | File "/py/lib/python3.9/site-packages/rest_framework/decorators.py", line 50, in handler
app_1 | return func(*args, **kwargs)
app_1 | File "/app/core/views.py", line 318, in setFakeProfile
app_1 | fakeProfile.displayName = request.data["displayName"]
app_1 | KeyError: 'displayName'
app_1 | [03/May/2022 12:32:32] "POST /setFakeProfile/ HTTP/1.1" 500 91167
app_1 | {'_parts': [['displayName', 'name'], ['profilePicture', 'file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540sumit2232%252FUnknownChats/ImagePicker/584abe5b-7f5e-45cb-81bd-fcb5751e3ed4.png']]}
app_1 | <MultiValueDict: {}>
app_1 | Internal Server Error: /setFakeProfile/
app_1 | Traceback (most recent call last):
app_1 | File "/py/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
app_1 | response = get_response(request)
app_1 | File "/py/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
app_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs)
app_1 | File "/py/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
app_1 | return view_func(*args, **kwargs)
app_1 | File "/py/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view
app_1 | response = self.handle_exception(exc)
app_1 | File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception
app_1 | self.raise_uncaught_exception(exc)
app_1 | File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
app_1 | raise exc
app_1 | File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch
app_1 | response = handler(request, *args, **kwargs)
app_1 | File "/py/lib/python3.9/site-packages/rest_framework/decorators.py", line 50, in handler
app_1 | return func(*args, **kwargs)
app_1 | File "/app/core/views.py", line 318, in setFakeProfile
app_1 | fakeProfile.displayName = request.data["displayName"]
app_1 | KeyError: 'displayName'
app_1 | [03/May/2022 12:32:52] "POST /setFakeProfile/ HTTP/1.1" 500 91167
Let's see the React Native code.
const [displayName, setDisplayName] = useState("");
const [displayImage, setDisplayImage] = useState(null);
const [error, setError] = useState('');
const pickImage = async () => {
// No permissions request is necessary for launching the image library
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [1, 1],
quality: 1,
});
console.log(result);
if (!result.cancelled) {
setDisplayImage({
...result,
uri: Platform.OS === 'ios' ? result.uri.replace('file://', '') : result.uri,
});
}
};
const onSubmit = async () =>{
console.log("submit");
const formData = new FormData();
formData.append('displayName', displayName);
formData.append('profilePicture', displayImage);
await axios.post(
`${baseUrl}setFakeProfile/`,
formData,
{
headers: {
// 'Content-Type': 'multipart/form-data',
// 'Accept': 'multipart/form-data',
'Content-Type': 'application/json',
'Accept': "application/json",
'Authorization': `Token ${await getData('token')}`
}
}
).then(res=>{
if (res.data.status==="success"){
dispatch(setFakeProfileIdToOpen(res.data.id));
navigation.navigate('FakeAccount');
}else{
setError(res.data.message);
console.log(res.data.message);
}
}).catch(err=>console.log(err));
}
I also tried with the commented code (means 'Content-Type': 'multipart/form-data' ) but it is still not working.

(Wagtail) Field defines a relation with model 'wagtailimages.Images', which is either not installed, or is abstract

I'm having an issue with Wagtail/Django.
I have the file app/models/abstract_card_snippet.py which contains:
from django.db import models
from wagtail.admin.edit_handlers import FieldPanel
from wagtail.documents.edit_handlers import DocumentChooserPanel
# Abstract Card Snippet
class AbstractCardSnippet(models.Model):
title = models.CharField(max_length=255)
text = models.CharField(max_length=255, null=True, blank=True)
url = models.URLField(max_length=255, null=True, blank=True,)
image = models.ForeignKey(
'wagtailimages.Images',
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name='+'
)
panels = [
FieldPanel('title'),
FieldPanel('text'),
FieldPanel('url'),
ImageChooserPanel('image'),
]
def __str__(self):
return '{}'.format(self.title)
class Meta:
abstract = True
Then in app/models/generic_card_snippet.py is:
from wagtail.snippets.models import register_snippet
from .abstract_card_snippet import AbstractCardSnippet
#register_snippet
class GenericCard(AbstractCardSnippet):
pass
But when I run the project or try to make migrations this error comes up:
web_1 | Exception in thread django-main-thread:
web_1 | Traceback (most recent call last):
web_1 | File "/usr/local/lib/python3.6/threading.py", line 916, in _bootstrap_inner
web_1 | self.run()
web_1 | File "/usr/local/lib/python3.6/threading.py", line 864, in run
web_1 | self._target(*self._args, **self._kwargs)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper
web_1 | fn(*args, **kwargs)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
web_1 | self.check(display_num_errors=True)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 436, in check
web_1 | raise SystemCheckError(msg)
web_1 | django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
web_1 |
web_1 | ERRORS:
web_1 | app_snippets.GenericCard.image: (fields.E300) Field defines a relation with model 'wagtailimages.Images', which is either not installed, or is abstract.
web_1 | app_snippets.GenericCard.image: (fields.E307) The field app_snippets.GenericCard.image was declared with a lazy reference to 'wagtailimages.images', but app 'wagtailimages' doesn't provide model 'images'.
Im clueless as to what the issue is, couldn't find anything relevant to the issue.

Django authlib MismatchingStateError on authorize_access_token

I have some issue on django authlib client https://docs.authlib.org/en/latest/client/django.html. On redirect url, authorize_access_token raise raise MismatchingStateError().
This is my code:
def login(request):
# google = oauth.create_client('google')
authservice = oauth.create_client('authservice')
redirect_uri = 'http://localhost:8050/authorize'
authservice.save_authorize_data(request)
return authservice.authorize_redirect(request, redirect_uri)
def authorize(request):
token = oauth.authservice.authorize_access_token(request)
userinfo = oauth.authservice.parse_id_token(request, token)
resp = oauth.authservice.userinfo(token=token)
return JsonResponse(token, safe=False)
And the stacktrace :
Internal Server Error: /authorize/
app_1 | Traceback (most recent call last):
app_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
app_1 | response = get_response(request)
app_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
app_1 | response = self.process_exception_by_middleware(e, request)
app_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
app_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs)
app_1 | File "/opt/project/access/views.py", line 141, in authorize
app_1 | token = oauth.authservice.authorize_access_token(request)
app_1 | File "/usr/local/lib/python3.7/site-packages/authlib/integrations/django_client/integration.py", line 66, in authorize_access_token
app_1 | params = self.retrieve_access_token_params(request)
app_1 | File "/usr/local/lib/python3.7/site-packages/authlib/integrations/base_client/base_app.py", line 144, in retrieve_access_token_params
app_1 | params = self._retrieve_oauth2_access_token_params(request, params)
app_1 | File "/usr/local/lib/python3.7/site-packages/authlib/integrations/base_client/base_app.py", line 126, in _retrieve_oauth2_access_token_params
app_1 | raise MismatchingStateError()
app_1 | authlib.integrations.base_client.errors.MismatchingStateError: mismatching_state: CSRF Warning! State not equal in request and response.
If someone has an idea on how to fix it, it will be great.
Thank you guys :)
I believe the error may be happening since the url configured in your app is not the same as 'http://localhost:8050/authorize'
Check and verify if they are the same or not. Also, see this.

Django: sending email causes OSError

I'm setting up registration proces for my Django REST API. I use "email.send()" function in my SignUpView. When I create new user, it should send him activation link. Unfortunately i get "OSError: [Errno 99] Cannot assign requested address".
I was looking for some solutions, but all was conected to some problems with sockets. Despite this I tried to change my ports in settings.
My email settings in settings.py:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'myemail#gmail.com'
EMAIL_HOST_PASSWORD= 'mypassword'
EMAIL_PORT = 587
View i used to signup:
class SignUp(APIView):
def post(self, request, format=None):
serializer = SignUpSerializer(data=request.data)
if serializer.is_valid():
user = serializer.save(is_active=False)
current_site = get_current_site(request)
mail_subject = 'Aktywuj swoje konto w serwisie Podwoozka.'
message = 'user: ', user.username,'domain', current_site.domain,'uid',urlsafe_base64_encode(force_bytes(user.pk)).decode(),'token', account_activation_token.make_token(user),
to_email = user.email
email = EmailMessage(
mail_subject, message, to=[to_email]
)
email.send()
return HttpResponse('Potwierdz email aby zakonczyc rejestracje.')
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
And finally entire Traceback when i use this function:
Traceback (most recent call last):
api_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
api_1 | response = get_response(request)
api_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response
api_1 | response = self.process_exception_by_middleware(e, request)
api_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response
api_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs)
api_1 | File "/usr/local/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
api_1 | return view_func(*args, **kwargs)
api_1 | File "/usr/local/lib/python3.7/site-packages/django/views/generic/base.py", line 68, in view
api_1 | return self.dispatch(request, *args, **kwargs)
api_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 495, in dispatch
api_1 | response = self.handle_exception(exc)
api_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 455, in handle_exception
api_1 | self.raise_uncaught_exception(exc)
api_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 492, in dispatch
api_1 | response = handler(request, *args, **kwargs)
api_1 | File "/Dback/races/views.py", line 264, in post
api_1 | email.send()
api_1 | File "/usr/local/lib/python3.7/site-packages/django/core/mail/message.py", line 291, in send
api_1 | return self.get_connection(fail_silently).send_messages([self])
api_1 | File "/usr/local/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 103, in send_messages
api_1 | new_conn_created = self.open()
api_1 | File "/usr/local/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 63, in open
api_1 | self.connection = self.connection_class(self.host, self.port, **connection_params)
api_1 | File "/usr/local/lib/python3.7/smtplib.py", line 251, in __init__
api_1 | (code, msg) = self.connect(host, port)
api_1 | File "/usr/local/lib/python3.7/smtplib.py", line 336, in connect
api_1 | self.sock = self._get_socket(host, port, self.timeout)
api_1 | File "/usr/local/lib/python3.7/smtplib.py", line 307, in _get_socket
api_1 | self.source_address)
api_1 | File "/usr/local/lib/python3.7/socket.py", line 727, in create_connection
api_1 | raise err
api_1 | File "/usr/local/lib/python3.7/socket.py", line 716, in create_connection
api_1 | sock.connect(sa)
api_1 | OSError: [Errno 99] Cannot assign requested address
I don't know if its important, but im using docker in this project. I heard sometimes there are some problems with outgoing connections from container.
EDIT: I tried to run it in pipenv instead of docker, still not working.
This time its "ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it"
First, make sure that you enabled POP access in Gmail:
https://support.google.com/mail/answer/7104828?hl=en&visit_id=637244831918669326-2427073497&rd=1
Then, if you receive Application-specific password required error, set up an app password for your account:
https://support.google.com/accounts/answer/185833?p=InvalidSecondFactor&visit_id=637244831918669326-2427073497&rd=1
In my case, this problem has been resolved with set SMTP_BLCOK = off.
in ssh or terminal
You must run the 3 commands in your ssh or terminal:
vi /etc/csf/csf.conf
SMTP_BLOCK = "0"
csf -r
in cpanel
You must follow this path:
WHM >‌ Plugins > ConfigServer Security & Firewall > Firewall Configuration > SMTP_BLCOK
and set SMTP_BLCOK = OFF