Exemple #1
0
def tagged(request, tag_name):
    try:
        tag = Tag.objects.get(name=tag_name)
    except Tag.DoesNotExist:
        tag = Tag(name=tag_name)
    queryset = (
        Production.objects.filter(tags__name=tag_name)
        .prefetch_related('author_nicks__releaser', 'author_affiliation_nicks__releaser', 'platforms', 'types')
    )

    order = request.GET.get('order', 'date')
    asc = request.GET.get('dir', 'desc') == 'asc'

    queryset = apply_order(queryset, order, asc)

    production_page = get_page(
        queryset,
        request.GET.get('page', '1'))

    return render(request, 'productions/tagged.html', {
        'tag': tag,
        'production_page': production_page,
        'order': order,
        'asc': asc,
    })
Exemple #2
0
    def render(self, name, value, attrs=None):
        attrs.update({"class": "hidden"})
        tags = []
        if value is not None and not isinstance(value, basestring):
            # value contains a list a TaggedItem instances
            # Here we retrieve a comma-delimited list of tags
            # suitable for editing by the user
            tags = [o.tag for o in value.select_related('tag')]
            value = edit_string_for_tags(tags)
        elif value is not None:
            tags = [Tag(name=n.replace('"', '')) for n in split_strip(value)]

        json_view = reverse('taggit_autocomplete_jqueryui_tag_list')

        html = u'<div class="selector"><ul class="tags">'
        for tag in tags:
            html += (u'''
                <li data-tag="%(name)s">
                    <span class="name">%(name)s</span>
                    <a class="remove" href="#">X</a>
                </li>''' % {'name': tag.name})
        html += '</ul>'
        html += super(TagAutocomplete, self).render(name, value, attrs)
        html += u'<input type="text" id="%s_autocomplete"/></div>' % attrs['id']

        js = u'''
            <script type="text/javascript">
                (function (root) {
                    root.taggit_init = root.taggit_init || [];
                    root.taggit_init.push(['#%s_autocomplete', '%s']);
                })(window);
            </script>''' % (attrs['id'], json_view)
        return mark_safe("\n".join([html, js]))
Exemple #3
0
    def test_should_return_True_if_form_has_changed(self):
        class TestForm(forms.Form):
            tag = TagField()

        form = TestForm(initial={"tag": [Tag(name="a")]}, data={"tag": ["b"]})

        self.assertTrue(form.has_changed())
Exemple #4
0
    def handle(self, *args, **options):
        """Handle command."""
        tags = []
        for state in STATES:
            tags.append(Tag(name=state, slug=state))

        Tag.objects.bulk_create(tags)
Exemple #5
0
def _delete_and_recreate_tags(slug):
    source_demo = Submission.objects.using('default').get(slug=slug)
    destination_demo = Submission.objects.using('new').get(slug=slug)
    source_type, destination_type = _get_demo_content_types()

    source_tags = source_demo.taggit_tags.all()
    source_tags_names = [tag.name for tag in source_tags]
    destination_tags = destination_demo.taggit_tags.using('new').all()
    destination_tags_names = [tag.name for tag in destination_tags]

    if source_tags_names == destination_tags_names:
        logger.info(
            "%s: Found %s matching tag(s): %s" %
            (source_demo.slug, len(destination_tags), destination_tags_names))
        return destination_tags
    else:
        dest_demo_tagged_items = TaggedItem.objects.using('new').filter(
            tag__in=[tag for tag in destination_tags],
            object_id=destination_demo.id,
            content_type=destination_type)
        dest_demo_tagged_items.using('new').delete()
        logger.info("%s: Migrating %s tag(s): %s" %
                    (source_demo.slug, len(source_tags), source_tags_names))
        for source_tag in source_tags:
            try:
                destination_tag = (Tag.objects.using('new').get(
                    name=source_tag.name))
            except Tag.DoesNotExist:
                destination_tag = Tag(name=source_tag.name)
                destination_tag.save(using='new')
            destination_demo_tag = TaggedItem(content_type=destination_type,
                                              object_id=destination_demo.id,
                                              tag=destination_tag)
            destination_demo_tag.save(using='new')
    return destination_tags
Exemple #6
0
def tag_create(request):
    Permission.objects.check_permissions(request.user, [PERMISSION_TAG_CREATE])
    redirect_url = reverse('tag_list')
    previous = request.POST.get(
        'previous',
        request.GET.get('previous',
                        request.META.get('HTTP_REFERER', redirect_url)))

    if request.method == 'POST':
        form = TagForm(request.POST)
        if form.is_valid():
            tag_name = form.cleaned_data['name']

            if tag_name in Tag.objects.values_list('name', flat=True):
                messages.error(request, _(u'Tag already exists.'))
                return HttpResponseRedirect(previous)

            tag = Tag(name=tag_name)
            tag.save()
            TagProperties(tag=tag, color=form.cleaned_data['color']).save()
            apply_default_acls(tag, request.user)

            messages.success(request, _(u'Tag created succesfully.'))
            return HttpResponseRedirect(redirect_url)
    else:
        form = TagForm()

    return render_to_response('generic_form.html', {
        'title': _(u'create tag'),
        'form': form,
    },
                              context_instance=RequestContext(request))
Exemple #7
0
    def test_should_return_False_if_form_has_not_changed(self):
        class TestForm(forms.Form):
            tag = TagField()

        form = TestForm(initial={"tag": [Tag(name="foo-bar")]},
                        data={"tag": ["foo-bar"]})

        self.assertFalse(form.has_changed())
Exemple #8
0
 def create_new_tags(cls, new_names):
     nonexisting_new_names = new_names.difference(
         Tag.objects.filter(name__in=new_names).values_list('name',
                                                            flat=True))
     # Generating a unique slug without appending unique a id requires adding tags one by one
     for name in nonexisting_new_names:
         tag = Tag(name=name)
         tag.save()
Exemple #9
0
 def setUp(self):
     self.user_factory = UserFactory()
     self.user = self.user_factory.create()
     self.codebase_factory = CodebaseFactory(self.user)
     self.codebase = self.codebase_factory.create()
     self.event_factory = EventFactory(self.user)
     self.event = self.event_factory.create()
     self.job_factory = JobFactory(self.user)
     self.job = self.job_factory.create()
     tag = Tag(name='a random tag')
     tag.save()
Exemple #10
0
 def setUp(self):
     self.job = Job.objects.create(title='Test Job',
                                   url_slug='test-job',
                                   link_to_project='www.testjob.com',
                                   summary='Test Summary',
                                   body='Test Body',
                                   technologies=['python'],
                                   tags=[Tag(name='python')],
                                   date_created=datetime.strptime(
                                       '2018-12-30 09:00:00',
                                       '%Y-%m-%d %H:%M:%S'),
                                   completed=True)
Exemple #11
0
    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        try:
            CheckRunService.run_check_tag(
                Tag(name=serializer["tag"].value),
                serializer["environment"].value,
                request.user,
            )
        except models.Environment.DoesNotExist as exc:
            return Response(str(exc), status=400)

        return Response({serializer["tag"].value: "success"}, status=status.HTTP_200_OK)
Exemple #12
0
def tagged(request, tag_name):
    try:
        tag = Tag.objects.get(name=tag_name)
    except Tag.DoesNotExist:
        tag = Tag(name=tag_name)
    queryset = BBS.objects.filter(tags__name=tag_name).order_by('name')

    page = get_page(queryset, request.GET.get('page', '1'))

    return render(request, 'bbs/tagged.html', {
        'tag': tag,
        'page': page,
    })
Exemple #13
0
    def setUp(self):
        self.adminuser = User.objects.create_superuser('admin',
                                                       '*****@*****.**',
                                                       'pass')
        self.adminuser.save()
        self.client = APIClient()
        self.client.force_authenticate(user=self.adminuser)
        self.IS_A_CAN_UPC_CODE = '000001'
        self.SIX_MONTH_LIFE = '000002'
        self.START_STOCK_LIFE_TAG_NAME = 'stock_life_start'

        from .views import RESET_STACK_TAG_NAME, DELETE_TAG_NAME
        is_can_tag = Tag(name='is_can', slug=self.IS_A_CAN_UPC_CODE).save()
        six_month_tag = Tag(name='six_months_life',
                            slug=self.SIX_MONTH_LIFE).save()
        self.reset_stack_tag = Tag(name=RESET_STACK_TAG_NAME, slug='000003')
        self.reset_stack_tag.save()
        self.delete_stock_tag = Tag(name=DELETE_TAG_NAME, slug='000004')
        self.delete_stock_tag.save()
        self.start_stock_life_tag = Tag(name=self.START_STOCK_LIFE_TAG_NAME,
                                        slug='000005')
        self.start_stock_life_tag.save()
        self.assertEqual(Tag.objects.count(), 5)
Exemple #14
0
def update_tags_for_submission(user_id, submission_id, tags_input_string):
    """Updates the set of tags tied to a submission.

        Returns the updated set of tags tag names for the submission
    """
    if not user_id:
        raise UserCannotBeNoneError(
            "Adding tags to a submission requires a user_id")
    if not submission_id or not isinstance(submission_id, int):
        raise ValueError("submission_id must be a positive integer")
    tag_names = [
        name.strip()
        for name in tags_input_string.split(',')
        if name.strip()
    ]
    if tag_names:
        existing_tag_objs = Tag.objects.filter(name__in=tag_names)
        existing_tag_names = set(tag.name for tag in existing_tag_objs)
        new_tags = [
            Tag(name=tag_name) for tag_name in tag_names
            if tag_name not in existing_tag_names]
        for tag in new_tags:
            tag.save()
        tag_objs = [*existing_tag_objs, *new_tags]
        existing_through_models = SubmissionTagLink.objects.filter(
            content_object_id=submission_id,
            tag__name__in=existing_tag_names)
        existing_through_tag_ids = set(
            through.tag_id for through in existing_through_models)
        new_through_models = (
            SubmissionTagLink(
                content_object_id=submission_id,
                tag_id=tag.id,
                user_id=user_id) for tag in tag_objs
            if tag.id not in existing_through_tag_ids)
        SubmissionTagLink.objects.bulk_create(new_through_models)
    tags_for_submission = FormSubmission.objects.get(
        id=submission_id).tags.all()
    return TagSerializer(tags_for_submission, many=True).data
Exemple #15
0
    def test_new_product_scan_with_control_code_scan(self):
        """
        Scan a control char then a new product
        """
        IS_A_CAN_UPC_CODE = '000001'
        # create the control code first:
        is_can_tag = Tag(name='is_can', slug=IS_A_CAN_UPC_CODE).save()
        self.assertEqual(Tag.objects.count(), 1)

        response = self.client.post('/api/product/%s/scan/' %
                                    IS_A_CAN_UPC_CODE,
                                    follow=True)
        self.assertEqual(ControlStack.objects.count(), 1)
        response = self.client.post('/api/product/3045320094084/scan/',
                                    follow=True)
        self.assertEqual(ControlStack.objects.count(), 0)
        self.assertEqual(Product.objects.count(), 1)
        self.assertEqual(Stock.objects.count(), 1)
        product_tags = Product.objects.first().tags.all()
        # product tags removed
        self.assertEqual(product_tags.count(), 0)
        stock_tags = Stock.objects.first().tags.all()
        self.assertEqual(stock_tags.count(), 1)
Exemple #16
0
c7 = Category(name="Prepared Foods", slug="prepared-foods")

c8 = Category(name="Preserves", slug="preserves")

# Save it
c1.save()
c2.save()
c3.save()
c4.save()
c5.save()
c6.save()
c7.save()
c8.save()

# Create Tags
t1 = Tag(name="Certified Organic", slug="organic")
t2 = Tag(name="Dairy Free", slug="dairy-free")
t3 = Tag(name="Gluten Free", slug="gluten-free")
t4 = Tag(name="Kosher Certified", slug="kosher")
t5 = Tag(name="Non-GMO", slug="non-gmo")
t6 = Tag(name="Nut Free", slug="nut-free")
t7 = Tag(name="Vegan", slug="vegan")
t8 = Tag(name="Vegetarian", slug="vegetarian")
t9 = Tag(name="Free Range", slug="free-range")

# Save it
t1.save()
t2.save()
t3.save()
t4.save()
t5.save()
Exemple #17
0
 def test_custom_comma_joiner(self):
     a = Tag(name="Cued Speech")
     b = Tag(name="transliterator")
     self.assertEqual(edit_string_for_tags([a, b]),
                      "Cued Speech, transliterator")
Exemple #18
0
def make_tag(name="example"):
    tag = Tag(name=name)
    tag.save()
    return tag
Exemple #19
0
 def setUp(self):
     self.tag = Tag(name='test')
     self.tag.save()
     self.tp = TagProperties(tag=self.tag, color=COLOR_RED)
     self.tp.save()
from taggit.utils import parse_tags
from taggit.models import Tag
from mechweb.models import StudentPage, StudentResearchInterestTag

students = StudentPage.objects.all()
for student in students:
    """ put string of comma separated tags """
    tagstring = ''
    words = parse_tags(tagstring)
    tag_list = []
    for word in words:
        tag = Tag(name=word)
        tag.save()
        taggedItem = StudentResearchInterestTag(
            tag=tag,
            content_object=student,
        )
        taggedItem.save()

tagstring = 'C, C++, Algorithms, Data structures'
wkords = parse_tags(tagstring)
# tag_list = []
for word in words:
    abhay.research_interests.set(word)
abhay.save()