Django 个人博客 - 文章评论和注册登录 - step 9

1 评论显示

模板使用for嵌套的方式输出评论的内容【article.html】

<ol class="commentlist">
    {% for comment in comment_list %}
    <li id="comment-59418">
        <div class="top"><a href='{{ comment.url }}' rel='external nofollow' class='url'>{{ comment.username }}</a><span
                class="time"> @ <a href="#comment-59418" title="">{{ comment.date_publish | date:'Y-m-d H:i:s' }}</a></span></div>
        <div>![]({% static 'images/default.jpg' %})
        </div>

        <div class="body">
            <p>{{ comment.content }}</p>
        </div>
    </li>
        {% for children_comment in comment.children_comment %}
        <li id="comment-59542">
            <div class="reply">
                <div class="top"><a href="{{ children_comment.url }}" rel="external nofollow" class="url">{{ children_comment.username }}</a><span class="time"> @ <a href="#comment-59543" title="">{{ children_comment.date_publish | date:'Y-m-d H:i:s' }}</a></span></div>
                <div>![]({% static 'images/default.jpg' %})</div>
                <div class="body">
                    {{ children_comment.content }}
                </div>
            </div>
        </li>
        {% endfor %}
    {% endfor %}
</ol>

【views.py】


# 获取评论信息
def article(request):
    comments = Comment.objects.filter(article=article).order_by('id')
    comment_list = []
    for comment in comments:
        for item in comment_list:
            if not hasattr(item, 'children_comment'):
                setattr(item, 'children_comment', [])
            if comment.pid == item:
                item.children_comment.append(comment)
                break
        if comment.pid is None:
            comment_list.append(comment)

2 评论提交

<div id="commentform">
    <form action="{% url 'comment_post' %}" method="post">
        {% csrf_token %}
        <p>{{ comment_form.author }}<label for="author">Name (required)</label></p>
        <p>{{ comment_form.email }}<label for="email">Email (Will NOT be published) (required)</label></p>
        <p>{{ comment_form.url }}<label for="url">URL</label></p>
        <p>{{ comment_form.comment }}</p>
        <p>{{ comment_form.article }}<input name="submit" type="submit" id="submit" tabindex="5" value="Submit" class="button"/></p>
    </form>
</div>

【forms.py】

class CommentForm(forms.Form):
    '''
    评论表单
    '''
    author = forms.CharField(widget=forms.TextInput(attrs={"id": "author", "class": "comment_input", "required": "required", "size": "25", "tabindex": "1"}), max_length=50, error_messages={"required": "username不能为空",})
    email = forms.EmailField(widget=forms.TextInput(attrs={"id": "email", "type": "email", "class": "comment_input","required": "required", "size": "25", "tabindex": "2"}),max_length=50, error_messages={"required": "email不能为空",})
    url = forms.URLField(widget=forms.TextInput(attrs={"id": "url", "type": "url", "class": "comment_input","size": "25", "tabindex": "3"}),max_length=100, required=False)
    comment = forms.CharField(widget=forms.Textarea(attrs={"id": "comment", "class": "message_input","required": "required", "cols": "25","rows": "5", "tabindex": "4"}),error_messages={"required": "评论不能为空",})
    article = forms.CharField(widget=forms.HiddenInput())

【urls.py】

urlpatterns = [
    url(r'^comment/post/$', comment_post, name='comment_post'),
]

【views.py】

def article(request):
    # 评论表单
    comment_form = CommentForm({'author': request.user.username,
                                'email': request.user.email,
                                'url': request.user.url,
                                'article': id} if request.user.is_authenticated() else{'article': id})
# 提交评论
def comment_post(request):
    try:
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            # 获取表单信息
            comment = Comment.objects.create(username=comment_form.cleaned_data["author"],
                                             email=comment_form.cleaned_data["email"],
                                             url=comment_form.cleaned_data["url"],
                                             content=comment_form.cleaned_data["comment"],
                                             article_id=comment_form.cleaned_data["article"],
                                             user=request.user )
            comment.save()
        else:
            return render(request, 'failure.html', {'reason': comment_form.errors})
    except Exception as e:
        logging.error(e)
    return redirect(request.META['HTTP_REFERER'])

3 用户注册于登陆

【forms.py】

class LoginForm(forms.Form):
    '''
    登录Form
    '''
    username = forms.CharField(widget=forms.TextInput(attrs={"placeholder": "Username", "required": "required",}), max_length=50, error_messages={"required": "username不能为空",})
    password = forms.CharField(widget=forms.PasswordInput(attrs={"placeholder": "Password", "required": "required",}), max_length=20, error_messages={"required": "password不能为空",})


class RegForm(forms.Form):
    '''
    注册表单
    '''
    username = forms.CharField(widget=forms.TextInput(attrs={"placeholder": "Username", "required": "required",}), max_length=50, error_messages={"required": "username不能为空",})
    email = forms.EmailField(widget=forms.TextInput(attrs={"placeholder": "Email", "required": "required",}), max_length=50, error_messages={"required": "email不能为空",})
    url = forms.URLField(widget=forms.TextInput(attrs={"placeholder": "Url",}), max_length=100, required=False)
    password = forms.CharField(widget=forms.PasswordInput(attrs={"placeholder": "Password", "required": "required",}), max_length=20, error_messages={"required": "password不能为空",})

【urls.py】

urlpatterns = [
    url(r'^logout$', do_logout, name='logout'),
    url(r'^reg', do_reg, name='reg'),
    url(r'^login', do_login, name='login'),
]

【atricle.html】

{% if not request.user.is_authenticated %}
<div class='login_info'>还没有登陆?可以登录后再评论哦。<b><a href="{% url 'login' %}">»去登录</a> <a href="{% url 'reg' %}">»去注册</a></b></div>
{% else %}
<div class='login_info'><b>{{ request.user.username }}</b>,快来写点评论吧! <a href="{% url 'logout' %}">注销</a></div>
{% endif %

【views.py】

from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.hashers import make_password

# 注销
def do_logout(request):
    try:
        logout(request)
    except Exception as e:
        print e
        logging.error(e)
    return redirect(request.META['HTTP_REFERER'])


# 注册
def do_reg(request):
    try:
        if request.method == 'POST':
            reg_form = RegForm(request.POST)
            if reg_form.is_valid():
                # 注册
                user = User.objects.create(username=reg_form.cleaned_data["username"],
                                           email=reg_form.cleaned_data["email"],
                                           url=reg_form.cleaned_data["url"],
                                           password=make_password(reg_form.cleaned_data["password"]), )
                user.save()

                # 登录
                user.backend = 'django.contrib.auth.backends.ModelBackend'  # 指定默认的登录验证方式
                login(request, user)
                return redirect(request.POST.get('source_url'))
            else:
                return render(request, 'failure.html', {'reason': reg_form.errors})
        else:
            reg_form = RegForm()
    except Exception as e:
        logging.error(e)
    return render(request, 'reg.html', locals())


# 登录
def do_login(request):
    try:
        if request.method == 'POST':
            login_form = LoginForm(request.POST)
            if login_form.is_valid():
                # 登录
                username = login_form.cleaned_data["username"]
                password = login_form.cleaned_data["password"]
                user = authenticate(username=username, password=password)
                if user is not None:
                    user.backend = 'django.contrib.auth.backends.ModelBackend'  # 指定默认的登录验证方式
                    login(request, user)
                else:
                    return render(request, 'failure.html', {'reason': '登录验证失败'})
                return redirect(request.POST.get('source_url'))
            else:
                return render(request, 'failure.html', {'reason': login_form.errors})
        else:
            login_form = LoginForm()
    except Exception as e:
        logging.error(e)
    return render(request, 'login.html', locals())

相关下载

文章评论和注册登录_代码


欢迎留言,博文会持续更新~~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容