简体   繁体   English

Django - [Errno 111] 连接被拒绝

[英]Django - [Errno 111] Connection refused

when I post a comment, do not save, crashes (error: [Errno 111] Connection refused), why?当我发表评论时,不保存,崩溃(错误:[Errno 111] Connection denied),为什么?

views.py视图.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模型.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)

Admin行政

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

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

thanks!谢谢!

Looks like you are trying to send a mail ( send_mail() ) and your mail settings in your settings.py are not correct.看起来您正在尝试发送邮件( send_mail() )并且您的settings.py 中的邮件设置settings.py正确。

You should check the docs for sending emails .您应该查看发送电子邮件的文档。


For debugging purposes you could setup a local smtpserver with this command:出于调试目的,您可以使用以下命令设置本地 smtpserver:

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

and adjust your mail settings accordingly:并相应地调整您的邮件设置:

EMAIL_HOST = 'localhost'
EMAIL_PORT = 1025

This is documented here:Testing e-mail sending这在此处记录:测试电子邮件发送

As an alternative to starting a dedicated debugging server you could use the console.EmailBackend which was added to Django recently.作为启动专用调试服务器的替代方法,您可以使用最近添加到 Django 的console.EmailBackend

For Development and Testing:对于开发和测试:

In Django 1.6+ we can just add this line in settings.py在 Django 1.6+ 中,我们可以在 settings.py 中添加这一行

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

This will display the mail on the console for Easy Verification.这将在控制台上显示邮件以进行轻松验证。

Note: Mail will not be sent to the specified recipient in Msg.Its just for Development and Testing.注意:邮件不会发送到 Msg.It 中指定的收件人,仅用于开发和测试。

For that you need to configure SMTP server which is given in the Doc.为此,您需要配置文档中给出的 SMTP 服务器。

For Reference: Django Documentation for Sending Email供参考: Django 发送文档 Email

Install postfix package on your server and it works.在您的服务器上安装后缀 package 并且它可以工作。 If is ubuntu, try it:如果是ubuntu,试试看:

sudo apt-get install postfix

In your settings, put:在您的设置中,输入:

EMAIL_HOST = 'localhost'

We recently moved away from the Python debugging email server to use a program called Mailcatcher.我们最近从 Python 调试 email 服务器转移到使用名为 Mailcatcher 的程序。 Mailcatcher runs as a daemon to intercept all of your test email messages to port 1025, and is integrated with a web server so that you can then view the intercepted emails from a browser. Mailcatcher 作为一个守护进程运行,以拦截所有测试 email 到端口 1025 的消息,并与 web 服务器集成,以便您可以从浏览器查看拦截的电子邮件。 Advantages优点

  • you can view test emails as HTML if needed如果需要,您可以查看测试电子邮件为 HTML
  • central management of all test emails -- they stay around until you clear them所有测试电子邮件的集中管理——它们一直存在,直到你清除它们
  • view test emails from any browser, instead of scrolling through terminal window从任何浏览器查看测试电子邮件,而不是滚动终端 window

You can read more and download it here: http://rubygems.org/gems/mailcatcher您可以在此处阅读更多内容并下载: http://rubygems.org/gems/mailcatcher

If you don't like Ruby, a co-worker of mine has ported the functionality of Mailcatcher to node.js -- check out MailDev here: http://djfarrelly.github.io/MailDev/ If you don't like Ruby, a co-worker of mine has ported the functionality of Mailcatcher to node.js -- check out MailDev here: http://djfarrelly.github.io/MailDev/

additionally the following will help:此外,以下内容将有所帮助:

put the following minimal settings in the settings.py or local_settings.py file on your server.将以下最小设置放在服务器上的 settings.py 或 local_settings.py 文件中。

EMAIL_HOST = 'localhost'
EMAIL_PORT = 587
EMAIL_USE_TLS = True

instead of using smtp.gmail.com which imposes lot many limitations, you can have your own mail server.而不是使用 smtp.gmail.com 会带来很多限制,您可以拥有自己的邮件服务器。

you can do it by installing your own mailserver:您可以通过安装自己的邮件服务器来做到这一点:

sudo apt-get install sendmail

I also run into this error.我也遇到了这个错误。 Instead of using gmail, I decided to setup my own mailserver using postfix.我决定使用 postfix 设置自己的邮件服务器,而不是使用 gmail。 See my reasons here. 在这里查看我的原因。

To setup postfix on Ubuntu 12.04:在 Ubuntu 12.04 上设置后缀:

sudo apt-get install postfix

Then, copy the config file to /etc/postfix/:然后,将配置文件复制到 /etc/postfix/:

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

Add the following lines to main.cf :将以下行添加到main.cf

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

Reload the config file:重新加载配置文件:

/etc/init.d/postfix reload

To test and see if postfix is working:要测试并查看 postfix 是否正常工作:

telnet localhost 25

Then enter the following line by line:然后逐行输入以下内容:

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)

If it works, you should see something like this:如果它有效,您应该会看到如下内容:

250 2.0.0 Ok: queued as CC732427AE

Next, put the following line in your Django's settings.py :接下来,将以下行放入 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>'

To test if Django can send email via postfix, open Django shell:要测试 Django 是否可以通过后缀发送 email,请打开 Django Z2591C98B701194FE62418ZB1E

./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)

Check your spam inbox and you should see the email above shown.检查您的垃圾邮件收件箱,您应该会看到上面显示的 email。

installing postfix did it for me.安装后缀为我做了。

There seemed to be no answer here that was suitably upvoted, so this page can be a bit confusing.这里似乎没有合适的答案,所以这个页面可能有点混乱。 Notice in the documentation:https://docs.djangoproject.com/en/1.3/ref/settings/#std:setting-EMAIL_HOST文档中的注意事项:https://docs.djangoproject.com/en/1.3/ref/settings/#std:setting-EMAIL_HOST

the parameters settings.py have default values.参数 settings.py 有默认值。

When I installed postfix it fixed the problem, locally at least.当我安装 postfix 时,它至少在本地解决了这个问题。

Hope this helps another confused soul!希望这可以帮助另一个困惑的灵魂!

EMailDump is usable and useful local server smtp, easy installation, this developed in python https://github.com/ThiefMaster/maildump EMailDump 是可用且有用的本地服务器 smtp,易于安装,此开发于 python https://github.com/ThiefMaster/maildump

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM