示例#1
0
def edit_question(request, question_id):
    """Edit a question."""
    question = get_object_or_404(Question, pk=question_id)
    user = request.user

    if not question.allows_edit(user):
        raise PermissionDenied

    ct = ContentType.objects.get_for_model(question)
    images = ImageAttachment.objects.filter(content_type=ct,
                                            object_id=question.pk)

    if request.method == "GET":
        initial = question.metadata.copy()
        initial.update(title=question.title, content=question.content)
        form = EditQuestionForm(
            product=question.product_config,
            initial=initial,
        )
    else:
        form = EditQuestionForm(
            data=request.POST,
            product=question.product_config,
        )

        # NOJS: upload images, if any
        upload_imageattachment(request, question)

        if form.is_valid():
            question.title = form.cleaned_data["title"]
            question.content = form.cleaned_data["content"]
            question.updated_by = user

            question.save(update=True)

            if form.cleaned_data.get("is_spam"):
                _add_to_moderation_queue(request, question)

            # TODO: Factor all this stuff up from here and new_question into
            # the form, which should probably become a ModelForm.
            question.clear_mutable_metadata()
            question.add_metadata(**form.cleaned_metadata)

            return HttpResponseRedirect(
                reverse("questions.details",
                        kwargs={"question_id": question.id}))

    return render(
        request,
        "questions/edit_question.html",
        {
            "question": question,
            "form": form,
            "images": images,
            "current_product": question.product_config,
            "current_category": question.category_config,
        },
    )
示例#2
0
def reply(request, question_id):
    """Post a new answer to a question."""
    question = get_object_or_404(Question, pk=question_id, is_spam=False)
    answer_preview = None

    if not question.allows_new_answer(request.user):
        raise PermissionDenied

    form = AnswerForm(request.POST, **{"user": request.user, "question": question})

    # NOJS: delete images
    if "delete_images" in request.POST:
        for image_id in request.POST.getlist("delete_image"):
            ImageAttachment.objects.get(pk=image_id).delete()

        return question_details(request, question_id=question_id, form=form)

    # NOJS: upload image
    if "upload_image" in request.POST:
        upload_imageattachment(request, request.user)
        return question_details(request, question_id=question_id, form=form)

    if form.is_valid() and not request.limited:
        answer = Answer(
            question=question,
            creator=request.user,
            content=form.cleaned_data["content"],
        )
        if "preview" in request.POST:
            answer_preview = answer
        else:
            if form.cleaned_data.get("is_spam"):
                _add_to_moderation_queue(request, answer)
            else:
                answer.save()

            ans_ct = ContentType.objects.get_for_model(answer)
            # Move over to the answer all of the images I added to the
            # reply form
            user_ct = ContentType.objects.get_for_model(request.user)
            up_images = ImageAttachment.objects.filter(creator=request.user, content_type=user_ct)
            up_images.update(content_type=ans_ct, object_id=answer.id)

            # Handle needsinfo tag
            if "needsinfo" in request.POST:
                question.set_needs_info()
            elif "clear_needsinfo" in request.POST:
                question.unset_needs_info()

            if Setting.get_for_user(request.user, "questions_watch_after_reply"):
                QuestionReplyEvent.notify(request.user, question)

            return HttpResponseRedirect(answer.get_absolute_url())

    return question_details(
        request, question_id=question_id, form=form, answer_preview=answer_preview
    )
示例#3
0
def edit_answer(request, question_id, answer_id):
    """Edit an answer."""
    answer = get_object_or_404(Answer, pk=answer_id, question=question_id)
    answer_preview = None

    if not answer.allows_edit(request.user):
        raise PermissionDenied

    # NOJS: upload images, if any
    upload_imageattachment(request, answer)

    if request.method == "GET":
        form = AnswerForm({"content": answer.content}, user=request.user)
        return render(request, "questions/edit_answer.html", {
            "form": form,
            "answer": answer
        })

    form = AnswerForm(request.POST, **{"user": request.user})

    if form.is_valid():
        answer.content = form.cleaned_data["content"]
        answer.updated_by = request.user
        if "preview" in request.POST:
            answer.updated = datetime.now()
            answer_preview = answer
        else:
            log.warning("User %s is editing answer with id=%s" %
                        (request.user, answer.id))

            if form.cleaned_data.get("is_spam"):
                _add_to_moderation_queue(request, answer)
            else:
                answer.save()

            return HttpResponseRedirect(answer.get_absolute_url())

    return render(
        request,
        "questions/edit_answer.html",
        {
            "form": form,
            "answer": answer,
            "answer_preview": answer_preview
        },
    )
示例#4
0
def aaq(request, product_key=None, category_key=None, step=1):
    """Ask a new question."""

    template = "questions/new_question.html"

    # Check if any product forum has a locale in the user's current locale
    if (request.LANGUAGE_CODE not in QuestionLocale.objects.locales_list()
            and request.LANGUAGE_CODE != settings.WIKI_DEFAULT_LANGUAGE):

        locale, path = split_path(request.path)
        path = "/" + settings.WIKI_DEFAULT_LANGUAGE + "/" + path

        old_lang = settings.LANGUAGES_DICT[request.LANGUAGE_CODE.lower()]
        new_lang = settings.LANGUAGES_DICT[
            settings.WIKI_DEFAULT_LANGUAGE.lower()]
        msg = _(
            "The questions forum isn't available in {old_lang}, we "
            "have redirected you to the {new_lang} questions forum.").format(
                old_lang=old_lang, new_lang=new_lang)
        messages.add_message(request, messages.WARNING, msg)

        return HttpResponseRedirect(path)

    # Check if the user is using a mobile device,
    # render step 2 if they are
    product_key = product_key or request.GET.get("product")
    if product_key is None:

        change_product = False
        if request.GET.get("q") == "change_product":
            change_product = True

        is_mobile_device = get_user_agent(request).is_mobile

        if is_mobile_device and not change_product:
            user_agent = request.META.get("HTTP_USER_AGENT", "")
            product_key = get_mobile_product_from_ua(user_agent)
            if product_key:
                # redirect needed for InAAQMiddleware
                step_2 = reverse("questions.aaq_step2",
                                 kwargs={"product_key": product_key})
                return HttpResponseRedirect(step_2)

    # Return 404 if the product doesn't exist in config
    product_config = config.products.get(product_key)
    if product_key and not product_config:
        raise Http404

    # If the selected product doesn't exist in DB, render a 404
    if step > 1:
        try:
            product = Product.objects.get(slug=product_config["product"])
        except Product.DoesNotExist:
            raise Http404
        else:
            # Check if the selected product has a forum in the user's locale
            if not product.questions_locales.filter(
                    locale=request.LANGUAGE_CODE).count():
                locale, path = split_path(request.path)
                path = "/" + settings.WIKI_DEFAULT_LANGUAGE + "/" + path

                old_lang = settings.LANGUAGES_DICT[
                    request.LANGUAGE_CODE.lower()]
                new_lang = settings.LANGUAGES_DICT[
                    settings.WIKI_DEFAULT_LANGUAGE.lower()]
                msg = _(
                    "The questions forum isn't available for {product} in {old_lang}, we "
                    "have redirected you to the {new_lang} questions forum."
                ).format(product=product.title,
                         old_lang=old_lang,
                         new_lang=new_lang)
                messages.add_message(request, messages.WARNING, msg)

                return HttpResponseRedirect(path)

    context = {
        "products": config.products,
        "current_product": product_config,
        "current_step": step,
        "host": Site.objects.get_current().domain,
    }

    if step == 2:
        context["featured"] = get_featured_articles(
            product, locale=request.LANGUAGE_CODE)
        context["topics"] = topics_for(product, parent=None)
    elif step == 3:
        form = NewQuestionForm(
            product=product_config,
            data=request.POST or None,
            initial={"category": category_key},
        )
        context["form"] = form

        # NOJS: upload image
        if "upload_image" in request.POST:
            upload_imageattachment(request, request.user)

        if form.is_valid() and not is_ratelimited(request, "aaq-day", "5/d"):

            question = form.save(
                user=request.user,
                locale=request.LANGUAGE_CODE,
                product=product,
                product_config=product_config,
            )

            if form.cleaned_data.get("is_spam"):
                _add_to_moderation_queue(request, question)

            # Submitting the question counts as a vote
            question_vote(request, question.id)

            my_questions_url = reverse("users.questions",
                                       args=[request.user.username])
            messages.add_message(
                request,
                messages.SUCCESS,
                _("Done! Your question is now posted on the Mozilla community support forum. "
                  +
                  "You can see your post anytime by visiting the {a_open}My Questions"
                  + "{a_close} page in your profile.").format(
                      a_open="<a href='" + my_questions_url + "'>",
                      a_close="</a>"),
                extra_tags="safe",
            )

            request.session["aaq-final-step"] = True

            url = reverse("questions.details",
                          kwargs={"question_id": question.id})
            return HttpResponseRedirect(url)

        if getattr(request, "limited", False):
            raise PermissionDenied

        user_ct = ContentType.objects.get_for_model(request.user)
        context["images"] = ImageAttachment.objects.filter(
            creator=request.user,
            content_type=user_ct,
        ).order_by("-id")[:IMG_LIMIT]

    return render(request, template, context)