Django - [Errno 111]连接拒绝 [英] Django - [Errno 111] Connection refused

查看:162
本文介绍了Django - [Errno 111]连接拒绝的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



views.py



  import time 
from calendar import month_name

from django.http import HttpResponseRedirect,HttpResponse
from django.shortcuts导入get_object_or_404,render_to_response
从django.contrib.auth.decorators导入login_required
从django.core.context_processors导入csrf
从django.core.paginator import Paginator,InvalidPage,EmptyPage $来自django.forms导入的
$ d

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


class CommentForm(ModelForm):
class Meta:
model =注释
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):
如果request.user.is_staff:
如果不是pk:pklst = request.POST.getlist(delete)
else:pklst = [ pk]

pklst中的pk
Comment.objects.get(pk = pk).delete()
返回HttpResponseRedirect(reverse(dbe.blog.views.post ,args = [post_pk]))

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

如果p.has_key(body)和p [body]:
author =Anonymous
如果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
如果request.user.username ==ak:notify = False
comment.save(notify = notify)
返回HttpResponseRedirect(reverse(dbe.blog.views。 post,args = [pk]))

def mkmonth_lst():
如果不是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
如果y == year:start = month
如果y == fyear:end = fmonth-1

for m in range(start,end,-1) :
months.append((y,m,month_name [m]))
返回月份

def月(请求,年,月):
posts = Post.objects.filter(created__year = year,created__month = month)
return render_to_response(list.htm l,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' )
除了ValueError:page = 1

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

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



models.py



<来自django.db导入模型的pre> 从django.contrib.auth.models导入
来自django.contrib的用户
从django.core导入admin
。邮件进口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注释(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):
如果通知在kwargs和kwargs [notify] == True:
message =评论被添加到'%s''%s':\\\
\\\
%s%(self.post,self.author,
self.body)
from_addr =no-reply@mydomain.com
r ecipient_list = [myemail@mydomain.com]
send_mail(添加新评论,消息,from_addr,recipient_list)

如果通知在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]

谢谢!

解决方案

看起来您正在尝试发送邮件( send_mail())和您的 settings.py 中的设置/#电子邮件主机rel =noreferrer>邮件设置是不正确的。



您应该检查文档发送电子邮件






为了进行调试,您可以使用以下命令设置本地smtpserver:

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

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

  EMAIL_HOST ='localhost'
EMAIL_PORT = 1025

这里记录了:测试电子邮件发送



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


when I post a comment, do not save, crashes (error: [Errno 111] Connection refused), why?

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)

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.

You should check the docs for sending emails.


For debugging purposes you could setup a local smtpserver with this command:

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 - [Errno 111]连接拒绝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆