Django - [Errno 111]连接被拒绝

时间:2011-04-27 09:50:52

标签: django

当我发表评论时,不要保存,崩溃(错误:[Errno 111]连接被拒绝),为什么?

views.py

import time
from calendar import month_name

from django.http import HttpResponseRedirect, HttpResponse  
from django.shortcuts import get_object_or_404, render_to_response  
from django.contrib.auth.decorators import login_required  
from django.core.context_processors import csrf  
from django.core.paginator import Paginator, InvalidPage, EmptyPage  
from django.core.urlresolvers import reverse  

from dbe.blog.models import *  
from django.forms import ModelForm  


class CommentForm(ModelForm):  
    class Meta:  
        model = Comment  
        exclude = ["post"]  


def post(request, pk):  
    post = Post.objects.get(pk=pk)  
    comments = Comment.objects.filter(post=post)  
    d = dict(post=post, comments=comments, form=CommentForm(), user=request.user)  
    d.update(csrf(request))  
    return render_to_response("post.html", d)  

def delete_comment(request, post_pk, pk=None):  
    if request.user.is_staff:  
        if not pk: pklst = request.POST.getlist("delete")  
        else: pklst = [pk]  

        for pk in pklst:  
            Comment.objects.get(pk=pk).delete()  
        return HttpResponseRedirect(reverse("dbe.blog.views.post", args=[post_pk]))  

def add_comment(request, pk):  
    p = request.POST  

    if p.has_key("body") and p["body"]:  
        author = "Anonymous"  
        if p["author"]: author = p["author"]  
        comment = Comment(post=Post.objects.get(pk=pk))  

        cf = CommentForm(p, instance=comment)  
        cf.fields["author"].required = False  
        comment = cf.save(commit=False)  

        comment.author = author  
        notify = True  
        if request.user.username == "ak": notify = False  
        comment.save(notify=notify)  
    return HttpResponseRedirect(reverse("dbe.blog.views.post", args=[pk]))  

def mkmonth_lst():  
    if not Post.objects.count(): return []  

    # set up vars  
    year, month = time.localtime()[:2]  
    first = Post.objects.order_by("created")[0]  
    fyear = first.created.year  
    fmonth = first.created.month  
    months = []  

    for y in range(year, fyear-1, -1):  
        start, end = 12, 0  
        if y == year: start = month  
        if y == fyear: end = fmonth-1  

        for m in range(start, end, -1):  
            months.append((y, m, month_name[m]))  
    return months  

def month(request, year, month):  
    posts = Post.objects.filter(created__year=year, created__month=month)  
    return render_to_response("list.html", dict(post_list=posts, user=request.user,  
                                                months=mkmonth_lst(), archive=True))  

def main(request):  
    posts = Post.objects.all().order_by("-created")  
    paginator = Paginator(posts, 10)  
    try: page = int(request.GET.get("page", '1'))  
    except ValueError: page = 1  

    try:  
        posts = paginator.page(page)  
    except (InvalidPage, EmptyPage):  
        posts = paginator.page(paginator.num_pages)  

    return render_to_response("list.html", dict(posts=posts, user=request.user,  
                                                post_list=posts.object_list,   months=mkmonth_lst()))

models.py

from django.db import models  
from django.contrib.auth.models import User  
from django.contrib import admin  
from django.core.mail import send_mail  


class Post(models.Model):  
    title = models.CharField(max_length=60)  
    body = models.TextField()  
    created = models.DateTimeField(auto_now_add=True)  

    def __unicode__(self):  
        return self.title  


class Comment(models.Model):  
    created = models.DateTimeField(auto_now_add=True)  
    author = models.CharField(max_length=60)  
    body = models.TextField()  
    post = models.ForeignKey(Post)  

    def __unicode__(self):  
        return unicode("%s: %s" % (self.post, self.body[:60]))  

    def save(self, *args, **kwargs):  
       if "notify" in kwargs and kwargs["notify"] == True:  
       message = "Comment was was added to '%s' by '%s': \n\n%s" % (self.post,   self.author,  
                                                                         self.body)  
            from_addr = "no-reply@mydomain.com"  
            recipient_list = ["myemail@mydomain.com"]  
            send_mail("New comment added", message, from_addr, recipient_list)  

        if "notify" in kwargs: del kwargs["notify"]  
        super(Comment, self).save(*args, **kwargs)

管理

class PostAdmin(admin.ModelAdmin):  
    search_fields = ["title"]  
    display_fields = ["title", "created"]  

class CommentAdmin(admin.ModelAdmin):  
    display_fields = ["post", "author", "created"] 

谢谢!

8 个答案:

答案 0 :(得分:97)

您似乎正在尝试发送邮件(send_mail())并且settings.py中的mail settings不正确。

您应该查看sending emails的文档。


出于调试目的,您可以使用以下命令设置本地smtpserver:

python -m smtpd -n -c DebuggingServer localhost:1025

并相应地调整您的邮件设置:

EMAIL_HOST = 'localhost'
EMAIL_PORT = 1025

此处记录了这些内容:Testing e-mail sending

作为启动专用调试服务器的替代方法,您可以使用最近添加到Django的console.EmailBackend

答案 1 :(得分:23)

开发和测试:

在Django 1.6+中,我们可以在settings.py

中添加此行
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

这将在控制台上显示用于轻松验证的邮件。

注意: 邮件不会被发送到Msg.Its中的指定收件人,仅用于开发和测试。

为此,您需要配置Doc。

中提供的SMTP服务器

供参考:Django Documentation for Sending Email

答案 2 :(得分:10)

在您的服务器上安装postfix软件包,它可以运行。如果是ubuntu,请尝试:

sudo apt-get install postfix

在您的设置中,输入:

EMAIL_HOST = 'localhost'

答案 3 :(得分:7)

我们最近离开了Python调试电子邮件服务器,使用了一个名为Mailcatcher的程序。 Mailcatcher作为守护进程运行,拦截所有测试电子邮件到端口1025,并与Web服务器集成,以便您可以从浏览器查看截获的电子邮件。优点

  • 如果需要,您可以将测试电子邮件视为HTML
  • 所有测试电子邮件的集中管理 - 它们会一直存在,直到您清除它们
  • 查看来自任何浏览器的测试电子邮件,而不是滚动终端窗口

您可以阅读更多内容并在此处下载: http://rubygems.org/gems/mailcatcher

如果您不喜欢Ruby,我的同事已将Mailcatcher的功能移植到node.js - 请在此处查看MailDev:http://djfarrelly.github.io/MailDev/

答案 4 :(得分:5)

另外,以下内容将有所帮助:

将以下最小设置放在服务器上的settings.py或local_settings.py文件中。

EMAIL_HOST = 'localhost'
EMAIL_PORT = 587
EMAIL_USE_TLS = True

而不是使用smtp.gmail.com,它有很多限制,你可以拥有自己的邮件服务器。

您可以通过安装自己的邮件服务器来实现:

sudo apt-get install sendmail

答案 5 :(得分:3)

我也遇到了这个错误。我没有使用gmail,而是决定使用postfix设置自己的邮件服务器。 See my reasons here.

在Ubuntu 12.04上设置postfix:

sudo apt-get install postfix

然后,将配置文件复制到/ etc / postfix /:

cp /usr/share/postfix/main.cf.debian /etc/postfix/main.cf

将以下行添加到 main.cf

mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mydestination = localhost

重新加载配置文件:

/etc/init.d/postfix reload

测试并查看postfix是否正常工作:

telnet localhost 25

然后逐行输入以下内容:

mail from: whatever@whatever.com
rcpt to: your_real_email_addr@blah.com
data (press enter)
type whatever content you feel like to type
. (put an extra period on the last line and then press enter again)

如果有效,你应该看到这样的东西:

250 2.0.0 Ok: queued as CC732427AE

接下来,将以下行放在Django的 settings.py 中:

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'localhost'
EMAIL_PORT = 25
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_USE_TLS = False
DEFAULT_FROM_EMAIL = 'Server <server@whatever.com>'

要测试Django是否可以通过postfix发送电子邮件,请打开Django shell:

./manage.py shell

>>> from django.core.mail import send_mail
>>> send_mail('Subject here', 'Here is the message.', 'from@example.com',
    ['to@example.com'], fail_silently=False)

检查垃圾邮件收件箱,您应该会看到上面显示的电子邮件。

答案 6 :(得分:1)

安装postfix为我做了。

这里似乎没有任何答案可以适当地投票,所以这个页面可能有点令人困惑。请注意文档:https://docs.djangoproject.com/en/1.3/ref/settings/#std:setting-EMAIL_HOST

参数settings.py具有默认值。

当我安装postfix时,它至少在本地修复了问题。

希望这有助于另一个迷茫的灵魂!

答案 7 :(得分:0)

EMailDump可用且有用本地服务器smtp,安装方便,这是在python中开发的  https://github.com/ThiefMaster/maildump