larken

勤奋的人生才有价值

导航

Django入门与实践-第19章:主题回复(完结)

#myproject/urls.py
url(r'^boards/(?P<pk>\d+)/topics/(?P<topic_pk>\d+)/reply/$',views.reply_topic, name='reply_topic'),


#boards/forms.py
from .models import Post
class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['message', ]

        
#一个新的受 @login_required 保护的视图,以及简单的表单处理逻辑
#boards/views.py
from .forms import PostForm
@login_required
def reply_topic(request, pk, topic_pk):
    topic = get_object_or_404(Topic, board__pk=pk, pk=topic_pk)
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.topic = topic
            post.created_by = request.user
            post.save()
            return redirect('topic_posts', pk=pk, topic_pk=topic_pk)
    else:
        form = PostForm()
    return render(request, 'reply_topic.html', {'topic': topic, 'form': form})


    
<!--templates/reply_topic.html-->
{% extends 'base.html' %}
{% load static %}
{% block title %}Post a reply{% endblock %}
{% block breadcrumb %}
    <li class="breadcrumb-item"><a href="{% url 'home' %}">Boards</a></li>
    <li class="breadcrumb-item"><a href="{% url 'board_topics' topic.board.pk %}">{{ topic.board.name }}</a></li>
    <li class="breadcrumb-item"><a href="{% url 'topic_posts' topic.board.pk topic.pk %}">{{ topic.subject }}</a></li>
    <li class="breadcrumb-item active">Post a reply</li>
{% endblock %}
{% block content %}
    <form method="post" class="mb-4">
        {% csrf_token %}
        {% include 'includes/form.html' %}
        <button type="submit" class="btn btn-success">Post a reply</button>
    </form>
    {% for post in topic.posts.all %}
    <div class="card mb-2">
        <div class="card-body p-3">
            <div class="row mb-3">
                <div class="col-6">
                    <strong class="text-muted">{{ post.created_by.use rname }}</strong>
                </div>
                <div class="col-6 text-right">
                    <small class="text-muted">{{ post.created_at }}</small>
                </div>
            </div>
        {{ post.message }}
        </div>
    </div>
    {% endfor %}
{% endblock %}
<!--templates/topic_posts.html(-->

{% for post in topic.posts.all %}
    <div class="card mb-2 {% if forloop.first %}border-dark{% endif %}">
        {% if forloop.first %}
    <div class="card-header text-white bg-dark py-2 px-3">{{ topic.subject }}</div>
    {% endif %}
    <div class="card-body p-3">
        <!-- code suppressed -->
    </div>
    </div>
{% endfor %}

 

posted on 2018-09-05 13:51  larken  阅读(208)  评论(0编辑  收藏  举报