@ssl_required
@mobile_template('questions/{mobile/}new_question.html')
@anonymous_csrf  # This view renders a login form
def aaq(request, product_key=None, category_key=None, showform=False,
        template=None, step=0):
    """Ask a new question."""
    # Use react version if waffle flag is set
    if waffle.flag_is_active(request, 'new_aaq'):
        return aaq_react(request)

    # This tells our LogoutDeactivatedUsersMiddleware not to
    # boot this user.
    request.session['in-aaq'] = True

    if (QuestionLocale.objects.locales_list() not in request.LANGUAGE_CODE 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 = (_(u"The questions forum isn't available in {old_lang}, we "
                 u"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)

    if product_key is None:
        product_key = request.GET.get('product')
        if request.MOBILE and product_key is None:
            # Firefox OS is weird. The best way we can detect it is to
            # look for a mobile Firefox that is not Android.
            ua = request.META.get('HTTP_USER_AGENT', '').lower()
            if 'firefox' in ua and 'android' not in ua:
                product_key = 'firefox-os'
            elif 'fxios' in ua:
                product_key = 'ios'
            else:
                product_key = 'mobile'

    product_config = config.products.get(product_key)
    if product_key and not product_config:
        raise Http404

    if product_config and 'product' in product_config:
        try:
            product = Product.objects.get(slug=product_config['product'])
        except Product.DoesNotExist:
            pass
        else:
            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 = (_(u"The questions forum isn't available for {product} in {old_lang}, we "
                         u"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)

    if category_key is None:
        category_key = request.GET.get('category')

    if product_config and category_key:
        product_obj = Product.objects.get(slug=product_config.get('product'))
        category_config = product_config['categories'].get(category_key)
        if not category_config:
            # If we get an invalid category, redirect to previous step.
            return HttpResponseRedirect(reverse('questions.aaq_step2', args=[product_key]))
        deadend = category_config.get('deadend', False)
        topic = category_config.get('topic')
        if topic:
            html = None
            articles, fallback = documents_for(
                locale=request.LANGUAGE_CODE,
                products=[product_obj],
                topics=[Topic.objects.get(slug=topic, product=product_obj)])
        else:
            html = category_config.get('html')
            articles = category_config.get('articles')
    else:
        category_config = None
        deadend = product_config.get('deadend', False) if product_config else False
        html = product_config.get('html') if product_config else None
        articles = None
        if product_config:
            # User is on the select category step
            statsd.incr('questions.aaq.select-category')
        else:
            # User is on the select product step
            statsd.incr('questions.aaq.select-product')

    if request.MOBILE:
        login_t = 'questions/mobile/new_question_login.html'
    else:
        login_t = 'questions/new_question_login.html'

    if request.method == 'GET':
        search = request.GET.get('search', '')
        if search:
            results = _search_suggestions(
                request,
                search,
                locale_or_default(request.LANGUAGE_CODE),
                [product_config.get('product')])
            tried_search = True
        else:
            results = []
            tried_search = False
            if category_config:
                # User is on the "Ask This" step
                statsd.incr('questions.aaq.search-form')

        if showform or request.GET.get('showform'):
            # Before we show the form, make sure the user is auth'd:
            if not request.user.is_authenticated():
                # User is on the login or register Step
                statsd.incr('questions.aaq.login-or-register')
                login_form = AuthenticationForm()
                register_form = RegisterForm()
                return render(request, login_t, {
                    'product': product_config,
                    'category': category_config,
                    'title': search,
                    'register_form': register_form,
                    'login_form': login_form})
            form = NewQuestionForm(
                product=product_config,
                category=category_config,
                initial={'title': search})
            # User is on the question details step
            statsd.incr('questions.aaq.details-form')
        else:
            form = None
            if search:
                # User is on the article and questions suggestions step
                statsd.incr('questions.aaq.suggestions')

        return render(request, template, {
            'form': form,
            'results': results,
            'tried_search': tried_search,
            'products': config.products,
            'current_product': product_config,
            'current_category': category_config,
            'current_html': html,
            'current_articles': articles,
            'current_step': step,
            'deadend': deadend,
            'host': Site.objects.get_current().domain})

    # Handle the form post.
    if not request.user.is_authenticated():
        if request.POST.get('login'):
            login_form = handle_login(request, only_active=False)
            statsd.incr('questions.user.login')
            register_form = RegisterForm()

            if login_form.is_valid():
                statsd.incr('questions.user.login.success')
            else:
                statsd.incr('questions.user.login.fail')

        elif request.POST.get('register'):
            login_form = AuthenticationForm()
            register_form = handle_register(
                request=request,
                text_template='users/email/activate.ltxt',
                html_template='users/email/activate.html',
                subject=_('Please confirm your Firefox Help question'),
                email_data=request.GET.get('search'),
                reg='aaq')

            if register_form.is_valid():  # Now try to log in.
                user = auth.authenticate(
                    username=request.POST.get('username'),
                    password=request.POST.get('password'))
                auth.login(request, user)
                statsd.incr('questions.user.register')
        else:
            # L10n: This shouldn't happen unless people tamper with POST data.
            message = _lazy('Request type not recognized.')
            return render(request, 'handlers/400.html', {'message': message}, status=400)

        if request.user.is_authenticated():
            # Redirect to GET the current URL replacing the step parameter.
            # This is also required for the csrf middleware to set the auth'd
            # tokens appropriately.
            url = urlparams(request.get_full_path(), step='aaq-question')
            return HttpResponseRedirect(url)
        else:
            return render(request, login_t, {
                'product': product_config,
                'category': category_config,
                'title': request.POST.get('title'),
                'register_form': register_form,
                'login_form': login_form})

    form = NewQuestionForm(product=product_config, category=category_config, data=request.POST)

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

    user_ct = ContentType.objects.get_for_model(request.user)

    if form.is_valid() and not is_ratelimited(request, 'aaq-day', '5/d'):
        question = Question(
            creator=request.user,
            title=form.cleaned_data['title'],
            content=form.cleaned_data['content'],
            locale=request.LANGUAGE_CODE)

        if product_obj:
            question.product = product_obj

        if category_config:
            t = category_config.get('topic')
            if t:
                question.topic = Topic.objects.get(slug=t, product=product_obj)

        question.save()

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

        # User successfully submitted a new question
        statsd.incr('questions.new')
        question.add_metadata(**form.cleaned_metadata)

        if product_config:
            # TODO: This add_metadata call should be removed once we are
            # fully IA-driven (sync isn't special case anymore).
            question.add_metadata(product=product_config['key'])

        if category_config:
            # TODO: This add_metadata call should be removed once we are
            # fully IA-driven (sync isn't special case anymore).
            question.add_metadata(category=category_config['key'])

        # The first time a question is saved, automatically apply some tags:
        question.auto_tag()

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

        if request.user.is_active:
            messages.add_message(
                request, messages.SUCCESS,
                _('Done! Your question is now posted on the Mozilla community support forum.'))

            # Done with AAQ.
            request.session['in-aaq'] = False

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

        return HttpResponseRedirect(reverse('questions.aaq_confirm'))

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

    images = ImageAttachment.objects.filter(creator=request.user,
                                            content_type=user_ct)

    statsd.incr('questions.aaq.details-form-error')
    return render(request, template, {
        'form': form,
        'images': images,
        'products': config.products,
        'current_product': product_config,
        'current_category': category_config,
        'current_articles': articles})
dataset/ETHPy150Open mozilla/kitsune/kitsune/questions/views.py/aaq/swapped operands of `not in`