djangobb之view form

Posted on 2018-03-23 21:32  王将军之武库  阅读(253)  评论(0编辑  收藏  举报
def add_topic(request, forum_id):
    """
    create a new topic, with or without poll
    """
    forum = get_object_or_404(Forum, pk=forum_id)#获取表单
    if not forum.category.has_access(request.user):#判断有无访问权
        raise PermissionDenied

    ip = request.META.get('REMOTE_ADDR', None)
    post_form_kwargs = {"forum": forum, "user": request.user, "ip": ip, }

    poll_form = None
    if request.method == 'POST':#表单数据发过来啦
        form = AddPostForm(request.POST, request.FILES, **post_form_kwargs)#构造添加主题表单
        if form.is_valid():#判断主题是否合法
            all_valid = True
        else:
            all_valid = False

        if forum_settings.ENABLE_POLLS:#取得投票数据
            poll_form = PollForm(request.POST)
            if not poll_form.has_data():
                # All poll fields are empty: User didn't want to create a poll
                # Don't run validation and remove all form error messages
                poll_form = PollForm() # create clean form without form errors
            elif not poll_form.is_valid():
                all_valid = False

        if all_valid:
            post = form.save()
            if poll_form and poll_form.has_data():
                poll_form.save(post)
                messages.success(request, _("Topic with poll saved."))
            else:
                messages.success(request, _("Topic saved."))
            return HttpResponseRedirect(post.get_absolute_url())
    else:#点击添加主题,返回用户的添加主题表单
        form = AddPostForm(
            initial={
                'markup': request.user.forum_profile.markup,
                'subscribe': request.user.forum_profile.auto_subscribe,
            },
            **post_form_kwargs
        )
        if forum_settings.ENABLE_POLLS and forum_id: # Create a new topic
            poll_form = PollForm()

    context = {
        'forum': forum,
        'create_poll_form': poll_form,
        'form': form,
        'form_url': request.path,
        'back_url': forum.get_absolute_url(),
    }
    return render(request, 'djangobb_forum/add_topic.html', context)

添加主题和表单提交,都调用相同的view函数。

Copyright © 2024 王将军之武库
Powered by .NET 9.0 on Kubernetes