Example #1
0
def topic(request, slug):
    """
    Topic-dedicated page.

    This displays all messages in order and allows registered users to post
    new messages. This page features anchor links per message and ability to
    edit or delete last posted message for its author. Messages can be
    “liked” too and this is reversible.
    """
    topic = get_object_or_404(Topic, slug=slug)
    messages = Message.objects.filter(topic=topic)
    context = {'topic': topic,
               'form': MessageForm(),
               'messages': messages}
    if request.user.is_authenticated():
        if request.method == 'POST':
            msg_form = MessageForm(request.POST)
            if msg_form.is_valid():
                message = msg_form.save(commit=False)
                message.author = request.user
                message.topic = topic
                message.save()
                msg_form.save_m2m()
                return redirect('topic', slug=slug)
            else:
                context['form'] = msg_form # render errors
    return render(request, 'glass/topic.html', context)
Example #2
0
def new_topic(request):
    """
    Creation of new topics.

    This is mainly about processing of ‘TopicForm’ and ‘MessageForm’, since
    every topic must have initial message.
    """
    if request.method == 'GET':
        context = {'topic_form': TopicForm(prefix='topic'),
                   'msg_form':   MessageForm(prefix='msg')}
    elif request.method == 'POST':
        topic_form = TopicForm(request.POST, prefix='topic')
        msg_form = MessageForm(request.POST, prefix='msg')
        context = {'topic_form': topic_form,
                   'msg_form':   msg_form}
        if topic_form.is_valid():
            new_topic = topic_form.save()
            if msg_form.is_valid():
                new_msg = msg_form.save(commit=False)
                new_msg.author = request.user
                new_msg.topic  = new_topic
                new_msg.save()
                msg_form.save_m2m()
                return redirect('topic', slug=new_topic.slug)
    return render(request, 'glass/new-topic.html', context=context)