I am trying to send email is using django.core.mail.send_mail(). However I am getting the following error when I try submit the form.
Here is the error I am getting:
Request Method: POST
Request URL: http://127.0.0.1:8000/contact/
Django Version: 1.8.10
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'newsletter',
'Contact')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "/home/sumit/Desktop/Home/Django/local/lib/python2.7/site-packages/Django-1.8.10-py2.7.egg/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/sumit/Desktop/Home/Django/src/Contact/views.py" in contact
25. fail_silently=False
File "/home/sumit/Desktop/Home/Django/local/lib/python2.7/site-packages/Django-1.8.10-py2.7.egg/django/core/mail/__init__.py" in send_mail
62. return mail.send()
File "/home/sumit/Desktop/Home/Django/local/lib/python2.7/site-packages/Django-1.8.10-py2.7.egg/django/core/mail/message.py" in send
303. return self.get_connection(fail_silently).send_messages([self])
File "/home/sumit/Desktop/Home/Django/local/lib/python2.7/site-packages/Django-1.8.10-py2.7.egg/django/core/mail/backends/smtp.py" in send_messages
100. new_conn_created = self.open()
File "/home/sumit/Desktop/Home/Django/local/lib/python2.7/site-packages/Django-1.8.10-py2.7.egg/django/core/mail/backends/smtp.py" in open
58. self.connection = connection_class(self.host, self.port, **connection_params)
File "/usr/lib/python2.7/smtplib.py" in __init__
256. (code, msg) = self.connect(host, port)
File "/usr/lib/python2.7/smtplib.py" in connect
316. self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python2.7/smtplib.py" in _get_socket
291. return socket.create_connection((host, port), timeout)
File "/usr/lib/python2.7/socket.py" in create_connection
553. for res in getaddrinfo(host, port, 0, SOCK_STREAM):
Exception Type: gaierror at /contact/
Exception Value: [Errno -2] Name or service not known
This is my views.py file.
from django.shortcuts import render
from .forms import ContactUsForm
from django.core.mail import send_mail
from django.conf import settings
def contact(request):
form = ContactUsForm(request.POST or None)
context = {
"title" : "Contact",
"form" : form,
}
if form.is_valid():
form_email = form.cleaned_data.get("email")
form_full_name = form.cleaned_data.get("full_name")
subject = "Sent via django"
from_email = settings.EMAIL_HOST_USER
to_email = [form_email]
contact_message = "Thank you %s " %(form_full_name)
send_mail(subject,
contact_message,
from_email,
to_email,
fail_silently=False
)
context = {
"title" : "Thank you for your feedback ! "
}
form.save()
return render(request, "contact.html", context)
forms.py:
from django import forms
from .models import ContactUs
class ContactUsForm(forms.ModelForm):
class Meta:
model = ContactUs
fields = ["full_name", "email", "message"]
models.py
from django.db import models
# Create your models here.
class ContactUs(models.Model):
full_name = models.CharField(max_length=120, blank=True)
email = models.EmailField()
message = models.CharField(max_length=100, blank=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
def __unicode__(self):
return self.email
I have set proxy variables in my terminal using:
export https_proxy="https://username:password#myproxy:myport"
export http_proxy="http://username:password#myproxy:myport"
export socks_proxy="socks://username:password#myproxy:myport"
export ftp_proxy="ftp://username:password#myproxy:myport"
How do I fix this error? Please help.
Have you set required parameters in settings.py file?
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
And its gaierror In your HOST parameter it should be :
HOST = ' ' (without space)
Don't use with space HOST = ' '
Related
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.
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 new to Django and trying to add social login options to a project I am working on. I am currently using Django-Allauth for the same. Currently I have incorporated only Google login into my project. Everything works fine. I have created a custom user model for my project with email as the username. When a user tries to sign up using the Sign Up template I have provided, I can delete the user from the database without any problems. But if I try to delete any user from the admin panel who signed in using the Google option of django-allauth, I get __str__ returned non-string (type CustomUser) error. Only way for me to reset everything is to simply delete the model and redo everything. Below is how my model looks like. I am using Django 3.0 and the latest version of Django-Allauth. I am not sure how to solve this problem. Any help on this would be appreciated.
models.py
class CustomUser(AbstractBaseUser):
email = models.EmailField(unique=True, max_length=100)
first_name = models.CharField(max_length=35)
last_name = models.CharField(max_length=35)
mobile = models.CharField(max_length=11, blank=True, default='')
city = models.CharField(max_length=35, blank=True, default='')
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
objects = CustomUserManager()
def __str__(self):
return self.email
def get_full_name(self):
if self.first_name and self.last_name:
return self.first_name + " " + self.last_name
def get_short_name(self):
if self.first_name:
return self.first_name
def has_perm(self, perm, obj=None):
"""
Does the user have a specific permission?
"""
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"""
Does the user have permissions to view the app `app_label`?
"""
# Simplest possible answer: Yes, always
return True
def get_absolute_url(self):
return reverse('users-profile', args=[str(self.id)])
Settings.py
# Application definition
INSTALLED_APPS = [
# Default Apps
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites', # Added
# User Apps
'users.apps.UsersConfig',
'crispy_forms',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
]
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend', # Added
)
# Required for Django-Allauth
SITE_ID = 1
# Required for Django-Allauth
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_UNIQUE_EMAIL = True
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('users.urls')),
path('accounts/', include('allauth.urls')),
]
Below is the error traceback:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/users/customuser/
Django Version: 3.0
Python Version: 3.8.0
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'users.apps.UsersConfig',
'contacts.apps.ContactsConfig',
'API.apps.ApiConfig',
'crispy_forms',
'admin_honeypot',
'rest_framework',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google']
Installed Middleware:
('whitenoise.middleware.WhiteNoiseMiddleware',
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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',
'users.middleware.OneSessionPerUserMiddleware')
Traceback (most recent call last):
File "D:\Programs\Django\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "D:\Programs\Django\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "D:\Programs\Django\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\options.py", line 607, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "D:\Programs\Django\venv\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "D:\Programs\Django\venv\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\sites.py", line 231, in inner
return view(request, *args, **kwargs)
File "D:\Programs\Django\venv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "D:\Programs\Django\venv\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\options.py", line 1704, in changelist_view
response = self.response_action(request, queryset=cl.get_queryset(request))
File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\options.py", line 1390, in response_action
response = func(self, request, queryset)
File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\actions.py", line 28, in delete_selected
deletable_objects, model_count, perms_needed, protected = modeladmin.get_deleted_objects(queryset, request)
File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\options.py", line 1826, in get_deleted_objects
return get_deleted_objects(objs, request, self.admin_site)
File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\utils.py", line 151, in get_deleted_objects
to_delete = collector.nested(format_callback)
File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\utils.py", line 211, in nested
roots.extend(self._nested(root, seen, format_callback))
File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\utils.py", line 195, in _nested
children.extend(self._nested(child, seen, format_callback))
File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\utils.py", line 197, in _nested
ret = [format_callback(obj)]
File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\utils.py", line 126, in format_callback
no_edit_link = '%s: %s' % (capfirst(opts.verbose_name), obj)
Exception Type: TypeError at /admin/users/customuser/
Exception Value: __str__ returned non-string (type CustomUser)
AbstractBaseUser has a __str__ method, which returns the field specified on USERNAME_FIELD in the model. You can check the source code on Github.
So after you specify custom USERNAME_FIELD, you can remove your own __str__ method:
class CustomUser(AbstractBaseUser):
email = models.EmailField(unique=True, max_length=100)
first_name = models.CharField(max_length=35)
last_name = models.CharField(max_length=35)
mobile = models.CharField(max_length=11, blank=True, default='')
city = models.CharField(max_length=35, blank=True, default='')
USERNAME_FIELD = 'email'
Also make sure that you installed and configured the packaged properly.
i'm trying to get a contact form on a personal site to work.
i'm using the smtp outlook.
Right now it gives me the following error:
Traceback:
Environment:
Request Method: POST
Request URL: *******
Django Version: 1.8.1
Python Version: 3.4.0
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "/home/Nmaster88/Ngranja/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/Nmaster88/Ngranja/Ngranja/Ngranja/views.py" in sendmail
23. send_mail(request.POST['contactSubject'],"From: "+request.POST['contactEmail']+'\n\n'+request.POST['contactMessage'],request.POST['contactEmail'],['nunomaster_#hotmail.com'],)
File "/home/Nmaster88/Ngranja/lib/python3.4/site-packages/django/core/mail/__init__.py" in send_mail
62. return mail.send()
File "/home/Nmaster88/Ngranja/lib/python3.4/site-packages/django/core/mail/message.py" in send
303. return self.get_connection(fail_silently).send_messages([self])
File "/home/Nmaster88/Ngranja/lib/python3.4/site-packages/django/core/mail/backends/smtp.py" in send_messages
100. new_conn_created = self.open()
File "/home/Nmaster88/Ngranja/lib/python3.4/site-packages/django/core/mail/backends/smtp.py" in open
58. self.connection = connection_class(self.host, self.port, **connection_params)
File "/usr/lib/python3.4/smtplib.py" in __init__
242. (code, msg) = self.connect(host, port)
File "/usr/lib/python3.4/smtplib.py" in connect
321. self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python3.4/smtplib.py" in _get_socket
292. self.source_address)
File "/usr/lib/python3.4/socket.py" in create_connection
509. raise err
File "/usr/lib/python3.4/socket.py" in create_connection
500. sock.connect(sa)
Exception Type: ConnectionRefusedError at /
Exception Value: [Errno 111] Connection refused
my settings:
EMAIL_HOST = 'smtp-mail.outlook.com'
EMAIL_HOST_USER = 'myemail#hotmail.com'
EMAIL_HOST_PASSWORD = 'mypassword'
EMAIL_PORT = 25
EMAIL_USE_TLS = True
view file:
from django.http import HttpResponseRedirect
from django.core.mail import send_mail
from django.shortcuts import render
def sendmail(request):
errors=[]
if request.method == 'POST':
if not request.POST.get('contactName',''):
errors.append('Coloca um nome.')
if not request.POST.get('contactEmail',''):
errors.append('Coloca um email.')
if not request.POST.get('contactSubject',''):
errors.append('Coloca um assunto.')
if not request.POST.get('contactMessage',''):
errors.append('Coloca um assunto.')
if not errors:
subject=request.POST['contactSubject']
email=request.POST['contactEmail']
message=request.POST['contactMessage']
send_mail(subject,"From: "+email+'\n\n'+message,email,['myemail#hotmail.com'], fail_silently=False)
return HttpResponseRedirect('/thankyou/')
return render(request, "mypage.html", {'errors': errors})
Does anyone has a clue on what is wrong?
If necessary i can give more info on the app
[EDIT]
I'm hosting the page at pythonanywhere.com, does the error have something to do with the server?
[EDIT] SOLVED
Pythonanywhere for free users only works for Gmail, and i had to give it permission for less secure apps! Now it works fine.
Try using use_ssl=True in your SMTP settings and changing the port to 465.
You can directly refer to Django SMTP options for list of all the settings you can tweak.
Also please mention which Django version you are using for building your app?
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