Exemple #1
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 #2
0
def create_tag(request):
	tag_dict = request.POST.dict()
	tags = Tag.objects.filter(name=tag_dict['term'])
	if tags.exists():
		# #There is only one result in tags because pk is unique
		# tag = tags[0]
		# #Get CroppedFrame to tag (give by data-cropped-id in <div class="ui-widget" id="tags" data-cropped-id="8">
		# cropped_frame = CroppedFrame.objects.get(pk=tag_dict['cropped_id'])
		#
		# cropped_frame.tags.add(tag)
		# cropped_frame.full_clean()
		# cropped_frame.save()
		toastr_json = dict()
		toastr_json['type'] = 'info'
		toastr_json['css'] = 'toast-bottom-left'
		toastr_json['msg'] = _("Tag already exists, just select it by the list")
	else:
		newtag = Tag(name=tag_dict['term'])
		newtag.save()
		toastr_json = dict()
		toastr_json['type'] = 'warning'
		toastr_json['css'] = 'toast-bottom-left'
		toastr_json['msg'] = _("%s created but not attached, re-search it by the list for attaching it"
		                       % newtag.name)
	data = json.dumps(toastr_json)
	mimetype = 'application/json'
	return HttpResponse(data, mimetype)
Exemple #3
0
def tagControl(request):
    template = 'main_article/tagControl.html'
    tags = Tag.objects.all()
    content = request.POST.get('content')
    if request.method == 'GET':
        context = {
            'tags': tags,
            'articlecount': tags.__len__(),
            'page_title': '标签控制'
        }
        return render(request, template, context)
    #post
    if content == '':
        context = {'tags': tags}
        messages.error(request, '不能为空')
        return render(request, template, context)
    try:
        content2 = str(Tag.objects.get(name=content))
        if content2 == content:
            messages.error(request, '已存在')
    except Tag.DoesNotExist:
        tagform = Tag()
        tagform.name = content
        tagform.save()
        create_action(request.user, '添加了标签', tagform)
        messages.success(request, '新增成功')
    return redirect('main_article:tagControl')
Exemple #4
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 #5
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 #6
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 #7
0
 def test_recreation_of_tag_list_string_representations(self):
     plain = Tag(name='plain')
     spaces = Tag(name='spa ces')
     comma = Tag(name='com,ma')
     self.assertEqual(edit_string_for_tags([plain]), 'plain')
     self.assertEqual(edit_string_for_tags([plain, spaces]), '"spa ces", plain')
     self.assertEqual(edit_string_for_tags([plain, spaces, comma]), '"com,ma", "spa ces", plain')
     self.assertEqual(edit_string_for_tags([plain, comma]), '"com,ma", plain')
     self.assertEqual(edit_string_for_tags([comma, spaces]), '"com,ma", "spa ces"')
Exemple #8
0
    def setUp(self):

        self.client = Client()

        Tag.objects.bulk_create([
            Tag(name='Tag 1', slug='tag-1'),
            Tag(name='Tag 2', slug='tag-2'),
            Tag(name='Tag 3', slug='tag-3'),
        ])
Exemple #9
0
class TagTestCase(TestCase):
    def setUp(self):
        self.tag = Tag(name='test')
        self.tag.save()
        self.tp = TagProperties(tag=self.tag, color=COLOR_RED)
        self.tp.save()

    def runTest(self):
        self.failUnlessEqual(self.tag.name, 'test')
        self.failUnlessEqual(self.tp.get_color_code(), 'red')
Exemple #10
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 #11
0
 def hydrate(self, bundle, request=None):
     """
     We allow sending dumb tag objects with only a "name" attribute, then we retrieve or create proper tag objects
     """
     if bundle.data["name"]:
         tagName = bundle.data["name"]
         try:
             tag = Tag.objects.get(name=tagName)
         except Tag.DoesNotExist:
             tag = Tag(name=tagName)
             tag.save()
         bundle = self.build_bundle(obj=tag)
     return bundle
Exemple #12
0
 def test_tag_many_to_many(self):
     old_tags = [Tag(name='abm'), Tag(name='agent based model (python)')]
     for t in old_tags:
         t.save()
     self.add_tags(old_tags)
     new_names = ['agent based model', 'python']
     for old_tag in old_tags:
         for new_name in new_names:
             TagCleanup.objects.create(new_name=new_name, old_name=old_tag.name)
     TagCleanup.objects.process()
     self.check_tag_name_presence(Event, new_names)
     self.check_tag_name_presence(Job, new_names)
     self.check_tag_name_presence(Codebase, new_names)
Exemple #13
0
def tag(**kwargs):
    """Model Maker for Tags."""
    defaults = {'name': str(datetime.now())}
    defaults.update(kwargs)
    if 'slug' not in kwargs:
        defaults['slug'] = slugify(defaults['title'])
    return Tag(**defaults)
Exemple #14
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 #15
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 #16
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 #17
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 #18
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())
 def set_tags(self):
     has_dupes = {}
     for old_tag in OldTag.objects.all():
         new_tag = NewTag(id=old_tag.id, name=old_tag.name)
         slug = new_tag.slugify(old_tag.name)
         try:
             new_tag = NewTag.objects.get(slug=slug)
             has_dupes.setdefault(new_tag.id, []).append(old_tag.id)
             print "ERROR: %s (%i,%i) already exists" % (slug, new_tag.id, old_tag.id)
         except NewTag.DoesNotExist:
             new_tag.slug = slug
             new_tag.save()
     self.dupemap = {}
     for first, later in has_dupes.items():
         for dupe in later:
             self.dupemap[dupe] = first
     print "%i dupes" % len(self.dupemap)
Exemple #20
0
def _add_tags(obj, tags_str, creator, content_type_name):
    for tag_name in tags_str.split(','):
        tag_name = tag_name.strip()
        # don't recreate the tag if it already exists
        try:
            t = Tag.objects.get(slug=slugify(tag_name))
        except ObjectDoesNotExist as dne:
            t = Tag()
            t.name = tag_name[:99]
            t.slug = slugify(tag_name)
            t.save()
        ti = TaggedItem()
        ti.tag = t
        ti.object_id = obj.id
        ti.tag_creator = creator
        ti.content_type = ContentType.objects.filter(name=content_type_name)[0]
        ti.save()
Exemple #21
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 #22
0
 def set_tags(self):
     has_dupes = {}
     for old_tag in OldTag.objects.all():
         new_tag = NewTag(id=old_tag.id, name=old_tag.name)
         slug = new_tag.slugify(old_tag.name)
         try:
             new_tag = NewTag.objects.get(slug=slug)
             has_dupes.setdefault(new_tag.id, []).append(old_tag.id)
             print 'ERROR: %s (%i,%i) already exists' % (slug, new_tag.id, old_tag.id)
         except NewTag.DoesNotExist:
             new_tag.slug = slug
             new_tag.save()
     self.dupemap = {}
     for first, later in has_dupes.items():
         for dupe in later:
             self.dupemap[dupe] = first
     print '%i dupes' % len(self.dupemap)
Exemple #23
0
def set_page_tags(page, tags):
    existing_tagged = dict([(tp.tag.name, tp) for tp in TaggedPage.objects.filter(content_object=page).select_related()])
    # TODO: cache this dict
    existing_tags = dict([(t.name, t) for t in Tag.objects.filter(name__in=tags)])
    for tag in tags:
        try:
            t = existing_tags[tag]
        except KeyError:
            t = Tag(name=tag)
            t.save()
        # OPTIMIZE: if tag was not found, don't bother checking in other dict
        try:
            tp = existing_tagged[tag]
            del existing_tagged[tag]
        except KeyError:
            tp = TaggedPage(tag=t, content_object=page)
            tp.save()
    # delete stale
    for _, tp in existing_tagged.items():
        tp.delete()
Exemple #24
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 #25
0
 def view_tags(self, request, **kwargs):
     user = self.obj(request, **kwargs)       
     if request.method == 'POST':
         if request.POST.get('tags'):
             tags = [token.strip() for token in request.POST.get('tags').split(' ')]
             user.tags.set(*tags)
             return SuccessResponse()
         elif request.POST.get('tag'):
             user.tags.add(request.POST.get('tag'))
             return SuccessResponse()   
         elif request.POST.get('deleted_tag'):
             user.tags.remove(request.POST.get('deleted_tag'))
             return SuccessResponse()      
         elif request.POST.get('create_tag'):
             t = Tag(name=request.POST.get('create_tag'))
             t.save()
             return SuccessResponse({"id":t.id})   
         else:
             return http.HttpBadRequest()
     else:
         return self.get_my_list(UserTagResource(), user.tags.all(), request)
Exemple #26
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 #27
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 #28
0
        def cleaned(self):
            """Returns the clean version of the tag"""

            return self.slug or Tag.clean_tag(self.name)
Exemple #29
0
 def cleaned(self):
     return self.slug or Tag.clean_tag(self_name)
Exemple #30
0
        def save(self, *args, **kwargs):
            """Cleans up any characters I don't want in a URL"""

            log.debug('Ensuring that tag "%s" has a slug' % (self,))
            self.slug = Tag.clean_tag(self.name)
            super(Tag, self).save(*args, **kwargs)
Exemple #31
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 #32
0
	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",
Exemple #33
0
def submit(url,tags2=[]): #submit url with auto-generated tags and possibly pre-specified ones (tags2)
    try:
        post = Entry.objects.get(url=url)
    except Entry.DoesNotExist:
        withurl=Entry.objects.filter(url__iexact=url) #collect all posts with the submitted url (should be only 1)
        tags = [tag for tag in tags2] #make a shallow copy
        tags.extend([tup[0] for tup in getkeywords(url)]) #getkeywords actually returns tuples of (keyword, n); we only want the keywords here
        if not tags: #don't submit if there are no tags to add
            return
        entry = None
        user = User.objects.get(id=43) #submitbot user
        if withurl:
            for tag in tags: #consider each of the specified tags individually
                #load or create the tag
                tagcheck = Tag.objects.filter(name__iexact=tag)
                if tagcheck:
                    newtag = tagcheck[0]
                else:
                    newtag = Tag(name=tag)
                    newtag.save()
                #make tag active so that ranktags knows to look at it
                activetags = eval(DataList.objects.get(id=1).data)
                if newtag.id not in activetags:
                    activetags.append(newtag.id)
                    d = DataList.objects.get(id=1)
                    d.data = activetags
                    d.save()
                    del d
                entry = withurl.filter(tags__name__in=[tag]) #find out if it already has the given tag
                if entry: #add a 'good' vote if it does
                    tagval=entry[0].posts.tagval_set.get(tag__name_iexact=tag)
                    tagval.val += 1
                    tagval.save()
                    entry[0].voted_by.voter_set.create(tag=tag, user=user, val=1, slug=entry[0].slug)

                    entry[0].save()
                else: #otherwise add tag and a 'good' vote
                    post = request.session.get('post', '')
                    withurl[0].tags.add(newtag)
                    withurl[0].posts.tagval_set.create(tag=newtag, val=1)
                    withurl[0].voted_by.voter_set.create(tag=tag, user=user, val=1, slug=withurl[0].slug)

                    withurl[0].save()

        else: #add entry and tags
            results = linter(url)
            ext = tldextract.extract(url)

            #create entry
            entry = Entry()
            entry.url = url
            entry.title = results.get('title', 'Untitled')
            if results.get('description'):
                entry.summary = results.get('description')
            if results.get('image'):
                entry.photo = results.get('image')
            entry.domain = '%s.%s' % (ext.domain, ext.tld)
            entry.submitted_by = user

            #initialize dictionaries for entry
            postsdict = Dict(name=entry.url)
            postsdict.save()
            entry.posts=postsdict

            dblpostsdict = Dict(name=entry.url)
            dblpostsdict.save()
            entry.double_posts = dblpostsdict

            favdict = Dict(name=entry.url)
            favdict.save()
            entry.favorites = favdict

            voterdict = Dict(name=entry.url)
            voterdict.save()
            entry.voted_by = voterdict

            #slugify
            entry.slug = '%s-%s' % (slugify(entry.title), str(entry.id))
            entry.save()
##                action = request.session.get('action','')
            for tagname in tags:
                #if the tag already exists grab it, otherwise create a new one
                tagcheck = Tag.objects.filter(name__iexact=tagname)
                print(tagname)
                if tagcheck:
                    newtag = tagcheck[0]
                else:
                    newtag = Tag(name=tagname)
                    newtag.save()

                #make tag active so that ranktags knows to look at it
                activetags = eval(DataList.objects.get(id=1).data)
                if newtag.id not in activetags:
                    activetags.append(newtag.id)
                    d = DataList.objects.get(id=1)
                    d.data = activetags
                    d.save()
                    del d

                #add 'good' vote
                entry.posts.tagval_set.create(tag=newtag, val=1)
                entry.voted_by.voter_set.create(tag=tagname, user=user, val=1, slug=entry.slug)
                entry.tags.add(newtag)
                entry.save()

            #try to pull in image from twitter, if it exists.
            domains = Logo.objects.filter(site__iexact=entry.domain)
            r = list(domains[:1])
            if not r:
                logo = Logo()
                logo.site = entry.domain
                try:
                    googleResult = urllib2.urlopen('http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=twitter.com+' + logo.site).read()
                    results = json.loads(googleResult)
                    data = results['responseData']['results']
                    urls = [e['url'] for e in data]

                    for url in urls:
                        if re.search(r"https?://(www\.)?twitter.com/\w+", url):
                            contents = urllib2.urlopen(url).read()
                            start = string.find(contents,"profile-picture")
                            start = string.find(contents,"src=",start)
                            m = re.search(r"src=\"([A-Za-z\.:/_0-9\-]+)\"",contents[start:])
                            if m:
                                image_url = m.group(1)
                                split = urlparse.urlsplit(image_url)
                                localPath = settings.MEDIA_ROOT + "site_logos/" + split.path.split("/")[-1]
                                urlretrieve(image_url, localPath)
                                logo.logo = "site_logos/" + split.path.split("/")[-1]
                                logo.save()
                            break #only first matching
                except:
                    logo = None
Exemple #34
0
def submit_plugin(request):
    user = request.user
    form = None
    extra = 'Entered.'
    if request.method == 'POST':
        form = SubmitFormPlugin(user, request.POST.get('url', ''), request.POST.get('tags',''), request.POST)
        extra += ' Getting form...'

        if form.is_valid():
            extra += ' Form is valid.'
            url = form.cleaned_data['url']
            tags = form.cleaned_data['tags']
            withurl=Entry.objects.filter(url__iexact=url) #collect all posts with the submitted url (should be only 1)
            entry = None
            if withurl:
                for tag in tags.split(', '): #consider each of the specified tags individually
                    #load or create the tag
                    tagcheck = Tag.objects.filter(name__iexact=tag)
                    if tagcheck:
                        newtag = tagcheck[0]
                    else:
                        newtag = Tag(name=tag)
                        newtag.save()
                    #make tag active so that ranktags knows to look at it
                    activetags = eval(DataList.objects.get(id=1).data)
                    if newtag.id not in activetags:
                        activetags.append(newtag.id)
                        d = DataList.objects.get(id=1)
                        d.data = activetags
                        d.save()
                        del d
                    entry = withurl.filter(tags__name__in=[tag]) #find out if it already has the given tag
                    if entry: #update the posts/double_posts
                        form.errors['url'] = ['This link has already been submitted in this Interest Group, and you have voted for it.']
                        extra += ' Entry exists.'
                        voters = [ i.user for i in entry[0].voted_by.voter_set.filter(tag__iexact=tag) ] #check to see if the user has already voted under this tag. change to __exact if we want case sensitive
                        if user not in voters:
                            if request.user.is_authenticated():
                                messages.success(request, 'This link was already submitted in this Interest Group, but we kept your votes for it.', fail_silently=True)
                            action = request.session.get('action', '')
                            if '_post' in request.POST:
                                tagval=sorted(entry[0].posts.tagval_set.filter(tag__iexact=tag), key=lambda e: -e.val)[0]
                                tagval.val += 1
                                tagval.save()
                                entry[0].voted_by.voter_set.create(tag=tag, user=user, val=1, slug=entry[0].slug)
                            else:
                                tagval=sorted(entry[0].double_posts.tagval_set.filter(tag__iexact=tag), key=lambda e: -e.val)[0]
                                tagval.val += 1
                                tagval.save()
                                entry[0].voted_by.voter_set.create(tag=tag, user=user, val=2, slug=entry[0].slug)

                            entry[0].save()

                            extra += ' Entry has been updated.'
                    else: #add tag
                        action = request.session.get('action', '')
                        withurl[0].tags.add(newtag)
                        if '_post' in request.POST:
                            withurl[0].posts.tagval_set.create(tag=newtag, val=1)
                            withurl[0].voted_by.voter_set.create(tag=tag, user=user, val=1, slug=withurl[0].slug)
                        else:
                            withurl[0].double_posts.tagval_set.create(tag=newtag, val=1)
                            withurl[0].voted_by.voter_set.create(tag=tag, user=user, val=2, slug=withurl[0].slug)

                        withurl[0].save()

                        extra += ' Added tag'+tag

            else: #add entry and tags
                results = linter(url)
                ext = tldextract.extract(url)

                #create entry
                entry = Entry()
                entry.url = url
                entry.title = results.get('title', 'Untitled')
                if results.get('description'):
                    entry.summary = results.get('description')
                if results.get('image'):
                    entry.photo = results.get('image')
                entry.domain = '%s.%s' % (ext.domain, ext.tld)
                entry.submitted_by = user

                #initialize dictionaries for entry
                postsdict = Dict(name=entry.url)
                postsdict.save()
                entry.posts=postsdict

                dblpostsdict = Dict(name=entry.url)
                dblpostsdict.save()
                entry.double_posts = dblpostsdict

                favdict = Dict(name=entry.url)
                favdict.save()
                entry.favorites = favdict

                voterdict = Dict(name=entry.url)
                voterdict.save()
                entry.voted_by = voterdict

                #slugify
                entry.slug = '%s-%s' % (slugify(entry.title), str(entry.id))
                entry.save()
##                action = request.session.get('action','')
                for tagname in tags.split(', '):
                    #if the tag already exists grab it, otherwise create a new one
                    tagcheck = Tag.objects.filter(name__iexact=tagname)
                    if tagcheck:
                        newtag = tagcheck[0]
                    else:
                        newtag = Tag(name=tagname)
                        newtag.save()

                    #make tag active so that ranktags knows to look at it
                    activetags = eval(DataList.objects.get(id=1).data)
                    if newtag.id not in activetags:
                        activetags.append(newtag.id)
                        d = DataList.objects.get(id=1)
                        d.data = activetags
                        d.save()
                        del d

                    if '_post' in request.POST: #'good'
                        entry.posts.tagval_set.create(tag=newtag, val=1)
                        entry.voted_by.voter_set.create(tag=tagname, user=user, val=1, slug=entry.slug)
                    else: #'great'
                        entry.double_posts.tagval_set.create(tag=newtag, val=1)
                        entry.voted_by.voter_set.create(tag=tagname, user=user, val=2, slug=entry.slug)
                    entry.tags.add(newtag)
                    entry.save()

                #try to pull in image from twitter, if it exists.
                domains = Logo.objects.filter(site__iexact=entry.domain)
                r = list(domains[:1])
                if not r:
                    logo = Logo()
                    logo.site = entry.domain
                    try:
                        googleResult = urllib2.urlopen('http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=twitter.com+' + logo.site).read()
                        results = json.loads(googleResult)
                        data = results['responseData']['results']
                        urls = [e['url'] for e in data]

                        for url in urls:
                            if re.search(r"https?://(www\.)?twitter.com/\w+", url):
                                contents = urllib2.urlopen(url).read()
                                start = string.find(contents,"profile-picture")
                                start = string.find(contents,"src=",start)
                                m = re.search(r"src=\"([A-Za-z\.:/_0-9\-]+)\"",contents[start:])
                                if m:
                                    image_url = m.group(1)
                                    split = urlparse.urlsplit(image_url)
                                    localPath = settings.MEDIA_ROOT + "site_logos/" + split.path.split("/")[-1]
                                    urlretrieve(image_url, localPath)
                                    logo.logo = "site_logos/" + split.path.split("/")[-1]
                                    logo.save()
                                break #only first matching
                    except:
                        logo = None

        if 'url' in request.session:
            del request.session['url']
        if 'action' in request.session:
            del request.session['action']
        if 'tags' in request.session:
            del request.session['tags']
        return render_to_response('autoclose.html')
    else:
        extra += ' First open.'
        bkmk = request.GET.get('bkmk', '')
        tags = request.GET.get('tags', '')
        post = Entry.objects.filter(url=bkmk)
        if post:
            entry=post[0]
            title = entry.title
            votes = entry.score
            tagscores = sorted([ [tag.name, round(entry._get_ranking(tag),1)] for tag in entry.tags.all()], key=lambda a: -a[1])
        else:
            title = linter(bkmk).get('title','Untitled')
            votes = 0
            tagscores = []
            
        form = SubmitFormPlugin(user, bkmk, tags)
        mytags = zip([ favtag.tags for favtag in user.favoritetag_set.all() ],[ favtag.name for favtag in user.favoritetag_set.all() ])
    template_data = {'form': form, 'extra': extra, 'tags':tags, 'mytags':mytags, 'title':title, 'votes':votes, 'tagscores':tagscores,}
    return render_to_response('content/submit_plugin.html', template_data, context_instance=RequestContext(request))
def save_tag_from_row(tag_row):
    tag = Tag()
    tag.id = tag_row[0]
    tag.name = tag_row[1]
    tag.save()
Exemple #36
0
def make_tag(name="example"):
    tag = Tag(name=name)
    tag.save()
    return tag
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()
Exemple #38
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 #39
0
def taglist(request, tags='', method='decay3', domain='', page=1,
          signup_form=SignupForm, auth_form=AuthenticationForm):

    message="" #use to track what the view function has done, this data is sent to the template and logged to javascript console
    
    signupform = signup_form()
    signinform = auth_form()
    user = request.user
    submitform = SubmitFormPlugin(user, 'url', 'tags')
    tags = tags

    page = int(request.POST.get('page', '1'))
    
    if tags == '':
        taglist = [ tag.name for tag in Tag.objects.all() ]
    else:
        taglist = [ tag for tag in tags.split('+') if not site_re.match(tag) ]
        domainlist = [ tag for tag in tags.split('+') if site_re.match(tag) ]
        tags = '+'.join(taglist)
        taglist = taglist or [ tag.name for tag in Tag.objects.all() ] # if removing all r'^site:' elements has left the list empty, then we want to look at all tags
        domain = domainlist[0][5:] if domainlist else ''
    
    if user.is_authenticated():
        message += "Logged in as user "+user.username+'\n'

        if request.method == 'POST':
            action = request.POST.get('action', '')
            if action == 'addfavtag':
                favtags = request.POST.get('tags','')
                if user.favoritetag_set.filter(tags=favtags):
                    message += 'User already had Favorite tag with tags='+favtags+'\n'
                    pass
                else:
                    message += 'added favorite tag\n'
                    if favtags == '':
                        user.favoritetag_set.create(tags=favtags,name='All Tags')
                    else:
                        user.favoritetag_set.create(tags=favtags,name=' + '.join(favtags.split('+')))
                        
            elif action == 'delete_mytag':
                mytag = request.POST.get('mytag_x','')
                if user.favoritetag_set.filter(tags=mytag):
                    user.favoritetag_set.get(tags=mytag).delete()
                else:
                    pass
                
            elif action == 'signup':
                signupform = signup_form(request.POST, request.FILES)
                if signupform.is_valid():
                    user = signupform.save()

                    # Send the signup complete signal
                    userena_signals.signup_complete.send(sender=None, user=user)
            elif action == 'signout':
                logout(request)
            elif action == 'addtags':
                addtags_url = request.POST.get('addtags_url', '')
                addtags_entry = get_object_or_404(Entry, url=addtags_url)
                addtags_tags = request.POST.get('addtags', '').split(', ')
                for tag in addtags_tags:
                    #load or create the tag
                    tagcheck = Tag.objects.filter(name__iexact=tag)
                    if tagcheck:
                        newtag = tagcheck[0]
                    else:
                        newtag = Tag(name=tag)
                        newtag.save()
    
                    if newtag not in addtags_entry.tags.all(): #check to see if it already has the tag first
                        #make tag active so that ranktags knows to look at it
                        activetags = eval(DataList.objects.get(id=1).data)
                        if newtag.id not in activetags:
                            activetags.append(newtag.id)
                            d = DataList.objects.get(id=1)
                            d.data = activetags
                            d.save()
                            del d
                        addtags_entry.tags.add(newtag)

                        addtags_entry.posts.tagval_set.create(tag=newtag, val=1)
                        addtags_entry.voted_by.voter_set.create(tag=tag, user=user, val=1, slug=addtags_entry.slug)

                        addtags_entry.save()
            elif action == 'pageset':
                pass
            elif action == 'submit':
                submitform = SubmitFormPlugin(user, request.POST.get('url', ''), request.POST.get('tags',''), request.POST)
                if submitform.is_valid():
                    url = submitform.cleaned_data['url']
                    submittags = submitform.cleaned_data['tags']
                    withurl=Entry.objects.filter(url__iexact=url) #collect all posts with the submitted url (should be only 1)
                    entry = None
                    if withurl:
                        for tag in submittags.split(', '): #consider each of the specified tags individually
                            #load or create the tag
                            tagcheck = Tag.objects.filter(name__iexact=tag)
                            if tagcheck:
                                newtag = tagcheck[0]
                            else:
                                newtag = Tag(name=tag)
                                newtag.save()
                            #make tag active so that ranktags knows to look at it
                            activetags = eval(DataList.objects.get(id=1).data)
                            if newtag.id not in activetags:
                                activetags.append(newtag.id)
                                d = DataList.objects.get(id=1)
                                d.data = activetags
                                d.save()
                                del d
                            entry = withurl.filter(tags__name__in=[tag]) #find out if it already has the given tag
                            if entry: #update the posts/double_posts
                                submitform.errors['url'] = ['This link has already been submitted in this Interest Group, and you have voted for it.']
                                voters = [ i.user for i in entry[0].voted_by.voter_set.filter(tag__iexact=tag) ] #check to see if the user has already voted under this tag. change to __exact if we want case sensitive
                                if user not in voters:
                                    post = request.session.get('post', '')
                                    if post == 'post':
                                        tagval=entry[0].posts.tagval_set.get(tag__name_iexact=tag)
                                        tagval.val += 1
                                        tagval.save()
                                        entry[0].voted_by.voter_set.create(tag=tag, user=user, val=1, slug=entry[0].slug)
                                    else:
                                        tagval=entry[0].double_posts.tagval_set.get(tag__name_iexact=tag)
                                        tagval.val += 1
                                        tagval.save()
                                        entry[0].voted_by.voter_set.create(tag=tag, user=user, val=2, slug=entry[0].slug)

                                    entry[0].save()
                            else: #add tag
                                post = request.session.get('post', '')
                                withurl[0].tags.add(newtag)
                                if post == 'post':
                                    withurl[0].posts.tagval_set.create(tag=newtag, val=1)
                                    withurl[0].voted_by.voter_set.create(tag=tag, user=user, val=1, slug=withurl[0].slug)
                                else:
                                    withurl[0].double_posts.tagval_set.create(tag=newtag, val=1)
                                    withurl[0].voted_by.voter_set.create(tag=tag, user=user, val=2, slug=withurl[0].slug)

                                withurl[0].save()

                    else: #add entry and tags
                        results = linter(url)
                        ext = tldextract.extract(url)

                        #create entry
                        entry = Entry()
                        entry.url = url
                        entry.title = results.get('title', 'Untitled')
                        if results.get('description'):
                            entry.summary = results.get('description')
                        if results.get('image'):
                            entry.photo = results.get('image')
                        entry.domain = '%s.%s' % (ext.domain, ext.tld)
                        entry.submitted_by = user

                        #initialize dictionaries for entry
                        postsdict = Dict(name=entry.url)
                        postsdict.save()
                        entry.posts=postsdict

                        dblpostsdict = Dict(name=entry.url)
                        dblpostsdict.save()
                        entry.double_posts = dblpostsdict

                        favdict = Dict(name=entry.url)
                        favdict.save()
                        entry.favorites = favdict

                        voterdict = Dict(name=entry.url)
                        voterdict.save()
                        entry.voted_by = voterdict

                        #slugify
                        entry.slug = '%s-%s' % (slugify(entry.title), str(entry.id))
                        entry.save()
        ##                action = request.session.get('action','')
                        for tagname in submittags.split(', '):
                            #if the tag already exists grab it, otherwise create a new one
                            tagcheck = Tag.objects.filter(name__iexact=tagname)
                            if tagcheck:
                                newtag = tagcheck[0]
                            else:
                                newtag = Tag(name=tagname)
                                newtag.save()

                            #make tag active so that ranktags knows to look at it
                            activetags = eval(DataList.objects.get(id=1).data)
                            if newtag.id not in activetags:
                                activetags.append(newtag.id)
                                d = DataList.objects.get(id=1)
                                d.data = activetags
                                d.save()
                                del d

                            post = request.session.get('post', '')
                            if post == 'post': #'good'
                                postsdict.tagval_set.create(tag=newtag, val=1)
                                voterdict.voter_set.create(tag=tagname, user=user, val=1, slug=entry.slug)
                            else: #'great'
                                dblpostsdict.tagval_set.create(tag=newtag, val=1)
                                voterdict.voter_set.create(tag=tagname, user=user, val=2, slug=entry.slug)
                            entry.tags.add(newtag)
                            entry.save()

                        #try to pull in image from twitter, if it exists.
                        domains = Logo.objects.filter(site__iexact=entry.domain)
                        r = list(domains[:1])
                        if not r:
                            logo = Logo()
                            logo.site = entry.domain
                            try:
                                googleResult = urllib2.urlopen('http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=twitter.com+' + logo.site).read()
                                results = json.loads(googleResult)
                                data = results['responseData']['results']
                                urls = [e['url'] for e in data]

                                for url in urls:
                                    if re.search(r"https?://(www\.)?twitter.com/\w+", url):
                                        contents = urllib2.urlopen(url).read()
                                        start = string.find(contents,"profile-picture")
                                        start = string.find(contents,"src=",start)
                                        m = re.search(r"src=\"([A-Za-z\.:/_0-9\-]+)\"",contents[start:])
                                        if m:
                                            image_url = m.group(1)
                                            split = urlparse.urlsplit(image_url)
                                            localPath = settings.MEDIA_ROOT + "site_logos/" + split.path.split("/")[-1]
                                            urlretrieve(image_url, localPath)
                                            logo.logo = "site_logos/" + split.path.split("/")[-1]
                                            logo.save()
                                        break #only first matching
                            except:
                                logo = None
                else:
                    return render_to_response('404.html')
                
            else:
                post_slug = request.POST.get('post_slug', '')
                post_change = get_object_or_404(Entry, slug=post_slug)
                tagnew = Tag.objects.get(name=taglist[0]) if tags else sorted(post_change.tags.all(), key=lambda t: -post_change._get_ranking(t))[0]
                voters = [ i.user for i in post_change.voted_by.voter_set.filter(tag__iexact=tagnew.name) ]
                message += 'post_change title: '+post_change.title+'\n'+'voters: '+str(voters)+'\n'
                
                if user not in voters:
                    message += 'Voting on tag '+taglist[0]+'\n'
                    activetags = eval(DataList.objects.get(id=1).data)
                    if tagnew.id not in activetags: #make tag active so that ranktags knows to look at it
                        activetags.append(tagnew.id)
                        d = DataList.objects.get(id=1)
                        d.data = activetags
                        d.save()
                        del d
                    if action == 'vote':
                        message += 'single vote\n'
                        post_change.voted_by.voter_set.create(tag=tagnew, user=user, val=1, slug=post_slug)
                        post_change.score += 1
                        try:
                            p=post_change.posts.tagval_set.get(tag__iexact=tagnew.name)
                            p.val += 1
                            p.save()
                        except:
                            post_change.posts.tagval_set.create(tag=tagnew,val=1)

                    if action == 'double_vote':
                        message += 'double vote\n'
                        post_change.voted_by.voter_set.create(tag=taglist[0], user=user, val=2, slug=post_slug)
                        post_change.score += 2
                        try:
                            dbp=post_change.double_posts.tagval_set.get(tag__iexact=tagnew.name)
                            dbp.val += 1
                            dbp.save()
                        except:
                            post_change.double_posts.tagval_set.create(tag=tagnew,val=1)
                else:
                    message += 'the user has already voted on this post with the tag '+taglist[0]+'\n'

        mytags = zip([ favtag.tags for favtag in user.favoritetag_set.all() ],[ favtag.name for favtag in user.favoritetag_set.all() ])

    else:
        message += 'Unauthenticated user\n'
        if request.method == 'POST':
            action = request.POST.get('action', '')
            if action == 'signup':
                signupform = signup_form(request.POST, request.FILES)
                if signupform.is_valid():
                    user = signupform.save()

                    # Send the signup complete signal
                    userena_signals.signup_complete.send(sender=None, user=user)

                    #sign in
                    user = authenticate(identification=request.POST.get('username', ''), password=request.POST.get('password1', ''))
                    login(request, user)
                    
            elif action == 'signin':
                signinform = auth_form(request.POST, request.FILES)
                if signinform.is_valid():
                    identification, password, remember_me = (signinform.cleaned_data['identification'],
                                                             signinform.cleaned_data['password'],
                                                             signinform.cleaned_data['remember_me'])
                    user = authenticate(identification=identification,
                                        password=password)
                    if user is not None:
                        if user.is_active:
                            login(request, user)
                            if remember_me:
                                request.session.set_expiry(userena_settings.USERENA_REMEMBER_ME_DAYS[1] * 86400)
                            else: request.session.set_expiry(0)
                        else:
                            return redirect(reverse('userena_disabled',
                                                kwargs={'username': user.username}))
        mytags = []
                    
    entries = Entry.objects.all()
    if tags:
        for tag in taglist:
            entries = entries.filter(tags__name__in=[tag])
    if domain:
        entries = entries.filter(domain__iexact=domain)
    
    if method == 'votes':
        if not tags and not domain:
            posts = [ Entry.objects.get(id=id) for id in nthslice(eval(DataList.objects.get(id=2).data),page,8) ]
            votecounts = [ entry.score for entry in posts ]
        elif len(taglist)==1:
            try:
                posts = [ Entry.objects.get(id=id) for id in nthslice(eval(DataList.objects.get(name='top_'+taglist[0]).data),page,8) ]
            except:
                posts = []
            if domain:
                posts = [ entry for entry in posts if entry.domain == domain ]
            votecounts = [sum([ a._get_ranking(tag) for tag in taglist]) for a in posts]
        elif domain:
            try:
                posts = [ Entry.objects.get(id=id) for id in nthslice(eval(DataList.objects.get(name='top_'+method+'_site:'+domain).data),page,8) ]
            except:
                posts = []
            if tags:
                votecounts = [sum([ a._get_ranking(tag) for tag in taglist]) for a in posts]
            else:
                votecounts = [ entry.score for entry in posts ]
        else:
            posts = sorted(entries, key=lambda a: -sum([ a._get_ranking(tag) for tag in taglist]))
            votecounts = [sum([ a._get_ranking(tag) for tag in taglist]) for a in posts]
    elif method == 'growth':
        posts = entries.order_by('-last_growth', '-date_added')
        votecounts = [ a.last_growth for a in posts ]
    elif method == 'decay1':
        if not tags and not domain:
            posts = [ Entry.objects.get(id=id) for id in nthslice(eval(DataList.objects.get(id=3).data),page,8) ]
            votecounts = [ round(entry.score * entry.d1) for entry in posts ]
        elif len(taglist)==1:
            try:
                posts = [ Entry.objects.get(id=id) for id in nthslice(eval(DataList.objects.get(name='top_d1_'+taglist[0]).data),page,8) ]
            except:
                posts = []
            if domain:
                posts = [ entry for entry in posts if entry.domain == domain ]
            votecounts = [ round(sum([ a._get_ranking(tag, 'decay1') for tag in taglist])) for a in posts ]
        elif domain:
            try:
                posts = [ Entry.objects.get(id=id) for id in nthslice(eval(DataList.objects.get(name='top_'+method+'_site:'+domain).data),page,8) ]
            except:
                posts = []
            if tags:
                votecounts = [round(sum([ a._get_ranking(tag) for tag in taglist])) for a in posts]
            else:
                votecounts = [ round(entry.score * entry.d1) for entry in posts ]
        else:
            posts = nthslice(sorted(entries, key=lambda a: -sum([ a._get_ranking(tag, 'decay1') for tag in taglist])),page,8)
            votecounts = [ round(sum([ a._get_ranking(tag, 'decay1') for tag in taglist])) for a in posts ]
    elif method == 'decay2':
        if not tags and not domain:
            posts = [ Entry.objects.get(id=id) for id in nthslice(eval(DataList.objects.get(id=4).data),page,8) ]
            votecounts = [ round(entry.score * entry.d2) for entry in posts ]
        elif len(taglist)==1:
            try:
                posts = [ Entry.objects.get(id=id) for id in nthslice(eval(DataList.objects.get(name='top_d2_'+taglist[0]).data),page,8) ]
            except:
                posts = []
            if domain:
                posts = [ entry for entry in posts if entry.domain == domain ]
            votecounts = [ round(sum([ a._get_ranking(tag, 'decay2') for tag in taglist])) for a in posts ]
        elif domain:
            try:
                posts = [ Entry.objects.get(id=id) for id in nthslice(eval(DataList.objects.get(name='top_'+method+'_site:'+domain).data),page,8) ]
            except:
                posts = []
            if tags:
                votecounts = [round(sum([ a._get_ranking(tag) for tag in taglist])) for a in posts]
            else:
                votecounts = [ round(entry.score * entry.d2) for entry in posts ]
        else:
            posts = nthslice(sorted(entries, key=lambda a: -sum([ a._get_ranking(tag, 'decay2') for tag in taglist])),page,8)
            votecounts = [ round(sum([ a._get_ranking(tag, 'decay2') for tag in taglist])) for a in posts ]
    elif method == 'decay3':
        if not tags and not domain:
            posts = [ Entry.objects.get(id=id) for id in nthslice(eval(DataList.objects.get(id=5).data),page,8) ]
            votecounts = [ round(entry.score * entry.d3) for entry in posts ]
        elif len(taglist)==1:
            try:
                posts = [ Entry.objects.get(id=id) for id in nthslice(eval(DataList.objects.get(name='top_d3_'+taglist[0]).data),page,8) ]
            except:
                posts = []
            if domain:
                posts = [ entry for entry in posts if entry.domain == domain ]
            votecounts = [ round(sum([ a._get_ranking(tag, 'decay3') for tag in taglist])) for a in posts ]
        elif domain:
            try:
                posts = [ Entry.objects.get(id=id) for id in nthslice(eval(DataList.objects.get(name='top_'+method+'_site:'+domain).data),page,8) ]
            except:
                posts = []
            if tags:
                votecounts = [round(sum([ a._get_ranking(tag) for tag in taglist])) for a in posts]
            else:
                votecounts = [ round(entry.score * entry.d3) for entry in posts ]
        else:
            posts = nthslice(sorted(entries, key=lambda a: -sum([ a._get_ranking(tag, 'decay3') for tag in taglist])),page,8)
            votecounts = [ round(sum([ a._get_ranking(tag, 'decay3') for tag in taglist])) for a in posts ]
    elif method == 'decay4':
        if not tags and not domain:
            posts = [ Entry.objects.get(id=id) for id in nthslice(eval(DataList.objects.get(id=6).data),page,8) ]
            votecounts = [ round(entry.score * entry.d4) for entry in posts ]
        elif len(taglist)==1:
            try:
                posts = [ Entry.objects.get(id=id) for id in nthslice(eval(DataList.objects.get(name='top_d4_'+taglist[0]).data),page,8) ]
            except:
                posts = []
            if domain:
                posts = [ entry for entry in posts if entry.domain == domain ]
            votecounts = [ round(sum([ a._get_ranking(tag, 'decay4') for tag in taglist])) for a in posts ]
        elif domain:
            try:
                posts = [ Entry.objects.get(id=id) for id in nthslice(eval(DataList.objects.get(name='top_'+method+'_site:'+domain).data),page,8) ]
            except:
                posts = []
            if tags:
                votecounts = [round(sum([ a._get_ranking(tag) for tag in taglist])) for a in posts]
            else:
                votecounts = [ round(entry.score * entry.d4) for entry in posts ]
        else:
            posts = nthslice(sorted(entries, key=lambda a: -sum([ a._get_ranking(tag, 'decay4') for tag in taglist])),page,8)
            votecounts = [ round(sum([ a._get_ranking(tag, 'decay4') for tag in taglist])) for a in posts ]
    elif method == 'decay5':
        if not tags and not domain:
            posts = [ Entry.objects.get(id=id) for id in nthslice(eval(DataList.objects.get(id=7).data),page,8) ]
            votecounts = [ round(entry.score * entry.d5) for entry in posts ]
        elif len(taglist)==1:
            try:
                posts = [ Entry.objects.get(id=id) for id in nthslice(eval(DataList.objects.get(name='top_d5_'+taglist[0]).data),page,8) ]
            except:
                posts = []
            if domain:
                posts = [ entry for entry in posts if entry.domain == domain ]
            votecounts = [ round(sum([ a._get_ranking(tag, 'decay5') for tag in taglist])) for a in posts ]
        elif domain:
            try:
                posts = [ Entry.objects.get(id=id) for id in nthslice(eval(DataList.objects.get(name='top_'+method+'_site:'+domain).data),page,8) ]
            except:
                posts = []
            if tags:
                votecounts = [round(sum([ a._get_ranking(tag) for tag in taglist])) for a in posts]
            else:
                votecounts = [ round(entry.score * entry.d5) for entry in posts ]
        else:
            posts = nthslice(sorted(entries, key=lambda a: -sum([ a._get_ranking(tag, 'decay5') for tag in taglist])),page,8)
            votecounts = [ round(sum([ a._get_ranking(tag, 'decay5') for tag in taglist])) for a in posts ]
    elif method == 'decay6':
        if not tags and not domain:
            posts = [ Entry.objects.get(id=id) for id in nthslice(eval(DataList.objects.get(id=8).data),page,8) ]
            votecounts = [ round(entry.score * entry.d6) for entry in posts ]
        elif len(taglist)==1:
            try:
                posts = [ Entry.objects.get(id=id) for id in nthslice(eval(DataList.objects.get(name='top_d6_'+taglist[0]).data),page,8) ]
            except:
                posts = []
            if domain:
                posts = [ entry for entry in posts if entry.domain == domain ]
            votecounts = [ round(sum([ a._get_ranking(tag, 'decay6') for tag in taglist])) for a in posts ]
        elif domain:
            try:
                posts = [ Entry.objects.get(id=id) for id in nthslice(eval(DataList.objects.get(name='top_'+method+'_site:'+domain).data),page,8) ]
            except:
                posts = []
            if tags:
                votecounts = [round(sum([ a._get_ranking(tag) for tag in taglist])) for a in posts]
            else:
                votecounts = [ round(entry.score * entry.d6) for entry in posts ]
        else:
            posts = nthslice(sorted(entries, key=lambda a: -sum([ a._get_ranking(tag, 'decay6') for tag in taglist])),page,8)
            votecounts = [ round(sum([ a._get_ranking(tag, 'decay6') for tag in taglist])) for a in posts ]
    elif method == 'decay7':
        if not tags and not domain:
            posts = [ Entry.objects.get(id=id) for id in nthslice(eval(DataList.objects.get(id=9).data),page,8) ]
            votecounts = [ round(entry.score * entry.d7) for entry in posts ]
        elif len(taglist)==1:
            try:
                posts = [ Entry.objects.get(id=id) for id in nthslice(eval(DataList.objects.get(name='top_d7_'+taglist[0]).data),page,8) ]
            except:
                posts = []
            if domain:
                posts = [ entry for entry in posts if entry.domain == domain ]
            votecounts = [ round(sum([ a._get_ranking(tag, 'decay7') for tag in taglist])) for a in posts ]
        elif domain:
            try:
                posts = [ Entry.objects.get(id=id) for id in nthslice(eval(DataList.objects.get(name='top_'+method+'_site:'+domain).data),page,8) ]
            except:
                posts = []
            if tags:
                votecounts = [round(sum([ a._get_ranking(tag) for tag in taglist])) for a in posts]
            else:
                votecounts = [ round(entry.score * entry.d7) for entry in posts ]
        else:
            posts = nthslice(sorted(entries, key=lambda a: -sum([ a._get_ranking(tag, 'decay7') for tag in taglist])),page,8)
            votecounts = [ round(sum([ a._get_ranking(tag, 'decay7') for tag in taglist])) for a in posts ]
    elif method == 'decay8':
        if not tags and not domain:
            posts = [ Entry.objects.get(id=id) for id in nthslice(eval(DataList.objects.get(id=10).data),page,8) ]
            votecounts = [ round(entry.score * entry.d8) for entry in posts ]
        elif len(taglist)==1:
            try:
                posts = [ Entry.objects.get(id=id) for id in nthslice(eval(DataList.objects.get(name='top_d8_'+taglist[0]).data),page,8) ]
            except:
                posts = []
            if domain:
                posts = [ entry for entry in posts if entry.domain == domain ]
            votecounts = [ round(sum([ a._get_ranking(tag, 'decay8') for tag in taglist])) for a in posts ]
        elif domain:
            try:
                posts = [ Entry.objects.get(id=id) for id in nthslice(eval(DataList.objects.get(name='top_'+method+'_site:'+domain).data),page,8) ]
            except:
                posts = []
            if tags:
                votecounts = [round(sum([ a._get_ranking(tag) for tag in taglist])) for a in posts]
            else:
                votecounts = [ round(entry.score * entry.d8) for entry in posts ]
        else:
            posts = nthslice(sorted(entries, key=lambda a: -sum([ a._get_ranking(tag, 'decay8') for tag in taglist])),page,8)
            votecounts = [ round(sum([ a._get_ranking(tag, 'decay8') for tag in taglist])) for a in posts ]
    elif method == 'favorites':
        posts = entries.filter(favorites__gt=0).order_by('-favorites', '-date_added')
    elif method == 'green':
        posts = sorted(entries.filter(date_added__range=(datetime.now() - timedelta(days=1), datetime.now())), key=lambda a: -a._get_ranking(taglist[0]))
    elif method == 'orange':
        posts = sorted(entries.filter(date_added__range=(datetime.now() - timedelta(days=3), datetime.now() - timedelta(days=1))), key=lambda a: -a._get_ranking(taglist[0]))
    elif method == 'red':
        posts = sorted(entries.filter(date_added__range=(datetime.now() - timedelta(days=6), datetime.now() - timedelta(days=3))), key=lambda a: -a._get_ranking(taglist[0]))
    elif method == 'black':
        posts = sorted(entries.filter(date_added__range=(datetime.now() - timedelta(days=365), datetime.now() - timedelta(days=6))), key=lambda a: -a._get_ranking(taglist[0]))
    else:
        return render_to_response('404.html')

    tagscores = [ sorted([ [tag.name, round(post._get_ranking(tag, method),1)] for tag in post.tags.all()], key=lambda a: -a[1]) for post in posts]
    if tags or domain:
        relevanttags = listsum([ post.tags.all() for post in posts ])
        toprelevant = sorted([[tag.name,int(sum([a._get_ranking(tag, method) for a in posts]))] for tag in set(relevanttags)], key=lambda a: -a[1])[:10]
    else:
        toprelevant = []
    
    if method=='votes':
        toptags = sorted([ [a.tag, a.val] for a in Dict.objects.get(id=193).tagval_set.all()], key=lambda a: -a[1])
        topsites = sorted([ [a.tag, a.val] for a in Dict.objects.get(id=1463).tagval_set.all()], key=lambda a: -a[1])
    elif method=='decay1':
        toptags = sorted([ [a.tag, a.val] for a in Dict.objects.get(id=194).tagval_set.all()], key=lambda a: -a[1])
        topsites = sorted([ [a.tag, a.val] for a in Dict.objects.get(id=1464).tagval_set.all()], key=lambda a: -a[1])
    elif method=='decay2':
        toptags = sorted([ [a.tag, a.val] for a in Dict.objects.get(id=195).tagval_set.all()], key=lambda a: -a[1])
        topsites = sorted([ [a.tag, a.val] for a in Dict.objects.get(id=1465).tagval_set.all()], key=lambda a: -a[1])
    elif method=='decay3':
        toptags = sorted([ [a.tag, a.val] for a in Dict.objects.get(id=196).tagval_set.all()], key=lambda a: -a[1])
        topsites = sorted([ [a.tag, a.val] for a in Dict.objects.get(id=1466).tagval_set.all()], key=lambda a: -a[1])
    elif method=='decay4':
        toptags = sorted([ [a.tag, a.val] for a in Dict.objects.get(id=197).tagval_set.all()], key=lambda a: -a[1])
        topsites = sorted([ [a.tag, a.val] for a in Dict.objects.get(id=1467).tagval_set.all()], key=lambda a: -a[1])
    elif method=='decay5':
        toptags = sorted([ [a.tag, a.val] for a in Dict.objects.get(id=198).tagval_set.all()], key=lambda a: -a[1])
        topsites = sorted([ [a.tag, a.val] for a in Dict.objects.get(id=1468).tagval_set.all()], key=lambda a: -a[1])
    elif method=='decay6':
        toptags = sorted([ [a.tag, a.val] for a in Dict.objects.get(id=199).tagval_set.all()], key=lambda a: -a[1])
        topsites = sorted([ [a.tag, a.val] for a in Dict.objects.get(id=1469).tagval_set.all()], key=lambda a: -a[1])
    elif method=='decay7':
        toptags = sorted([ [a.tag, a.val] for a in Dict.objects.get(id=200).tagval_set.all()], key=lambda a: -a[1])
        topsites = sorted([ [a.tag, a.val] for a in Dict.objects.get(id=1470).tagval_set.all()], key=lambda a: -a[1])
    elif method=='decay8':
        toptags = sorted([ [a.tag, a.val] for a in Dict.objects.get(id=201).tagval_set.all()], key=lambda a: -a[1])
        topsites = sorted([ [a.tag, a.val] for a in Dict.objects.get(id=1471).tagval_set.all()], key=lambda a: -a[1])
    if not tags and not domain: #show 'all' instead of a list of every single tag
        taglist=['all']
    if domain:
        if tags:
            taglist += ['site:'+domain]
        else:
            taglist = ['site:'+domain]
    
    voter = []
    double_voter = []
    if user.is_authenticated():
        if tags:
            slugs = [ entry.slug for entry in posts ]
            voters = user.voter_set.filter(slug__in=slugs)
            voters = voters.filter(tag__iexact=taglist[0])
            voter = [ v.slug for v in voters.filter(val=1) ]
            double_voter = [ v.slug for v in voters.filter(val=2) ]
        else:
            votedata = [ (post, ts[0][0]) for post,ts in zip(posts,tagscores) if len(ts)>0 ]
            for entry, tag in votedata:
                voted = filter(lambda v: v.tag == tag and v.slug == entry.slug, user.voter_set.all())
                if voted:
                    if voted[0].val==1:
                        voter.append(entry.slug)
                    else:
                        double_voter.append(entry.slug)
    message += "voter: "+str(voter)+'\ndouble_voter: '+str(double_voter)+'\n'
    
    template_data = {
        'tags': tags,
        'postdata': zip(posts,votecounts,tagscores),
        'method': method,
        'voter': voter,
        'double_voter': double_voter,
        'taglist': taglist,
        'page': page,
        'topsites': topsites,
        'toptags_1': nthslice(toptags,1,10),
        'toptags_2': nthslice(toptags,2,10),
        'toprelevant': toprelevant,
        'mytags': mytags,
        'domain': domain,
        'breadcrumbdata': zip(taglist,['+'.join(taglist[:i]+taglist[i+1:]) for i in range(0,len(taglist))]),
        'signupform': signupform,
        'signinform': signinform,
        'submitform': submitform,
        'message': message,
        }
    return render_to_response('brian.html', template_data, context_instance=RequestContext(request))
Exemple #40
0
def make_tag(name="example"):
    tag = Tag(name=name)
    tag.save()
    return tag
Exemple #41
0
 def setUp(self):
     self.tag = Tag(name='test')
     self.tag.save()
     self.tp = TagProperties(tag=self.tag, color=COLOR_RED)
     self.tp.save()