Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
…tion-System into n-level
  • Loading branch information
rohitrp committed Mar 20, 2019
2 parents b01f770 + d91170b commit d108964
Show file tree
Hide file tree
Showing 31 changed files with 10,009 additions and 91 deletions.
5 changes: 3 additions & 2 deletions BasicArticle/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,14 @@ class Meta:
fields = ['title', 'body', 'image', 'state', 'tags']

def __init__(self, *args, **kwargs):
role = kwargs.pop('role', None)
super().__init__(*args, **kwargs)
self.fields['title'].widget.attrs.update({'class': 'form-control'})
self.fields['image'].widget.attrs.update({'class': 'file', 'data-allowed-file-extensions':'["jpeg", "jpg","png"]', 'data-show-upload':'false', 'data-show-preview':'false', 'data-msg-placeholder':'Select article image for upload...'})
self.fields['image'].required = False
self.fields['state'].widget.attrs.update({'class': 'form-control'})
self.fields['tags'].widget.attrs.update({'class': 'form-control'})
states = getStatesCommunity(self.instance.state.name)
states = getStatesCommunity(self.instance.state.name, role)
self.fields['state'].queryset = States.objects.filter(name__in=states)

if not settings.REALTIME_EDITOR:
Expand All @@ -45,4 +46,4 @@ def __init__(self, *args, **kwargs):
self.fields['image'].required = False
self.fields['tags'].widget.attrs.update({'class': 'form-control'})
if not settings.REALTIME_EDITOR:
self.fields['body'].widget.attrs.update({'class': 'form-control'})
self.fields['body'].widget.attrs.update({'class': 'form-control'})
4 changes: 4 additions & 0 deletions BasicArticle/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ class Articles(models.Model):
views = models.PositiveIntegerField(default=0)
state = models.ForeignKey(States, null=True,related_name='articleworkflow')
tags = TaggableManager()

def get_absolute_url(self):
from django.urls import reverse
return reverse('article_view', kwargs={'pk': self.id})

def __str__(self):
return self.title
Expand Down
9 changes: 5 additions & 4 deletions BasicArticle/search_indexes.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@


class ArticlesIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
created_by = indexes.CharField(model_attr='created_by')
published_on = indexes.DateTimeField(model_attr='published_on')
text = indexes.CharField(document=True, model_attr='title')
# created_by = indexes.CharField(model_attr='created_by')
created_at = indexes.DateTimeField(model_attr='created_at')
state = indexes.CharField(model_attr='state')

def get_model(self):
return Articles

def index_queryset(self, using=None):
"""Used when the entire index for model is updated."""
return self.get_model().objects.filter(published_on__lte= timezone.make_aware(datetime.datetime.now()))
return self.get_model().objects.all()
12 changes: 11 additions & 1 deletion BasicArticle/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,14 @@ class ArticleEditView(UpdateView):
context_object_name = 'article'
success_url = 'article_view'

def get_form_kwargs(self):
"""
Returns the keyword arguments for instantiating the form.
"""
kwargs = super(ArticleEditView, self).get_form_kwargs()
kwargs.update({'role': self.get_communityrole(self.request, self.get_community())})
return kwargs

def get(self, request, *args, **kwargs):
if request.user.is_authenticated:
self.object = self.get_object()
Expand All @@ -189,7 +197,6 @@ def get(self, request, *args, **kwargs):
return redirect('article_view',pk=self.object.pk)
community = self.get_community()
if self.is_communitymember(request, community):
role = self.get_communityrole(request, community)
if canEditResourceCommunity(self.object.state.name, role.name, self.object, request):
response=super(ArticleEditView, self).get(request, *args, **kwargs)
if settings.REALTIME_EDITOR:
Expand Down Expand Up @@ -336,3 +343,6 @@ def article_watch(request, article):

class SimpleModelHistoryCompareView(HistoryCompareDetailView):
model = Articles



7 changes: 4 additions & 3 deletions CollaborationSystem/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,15 +109,15 @@
}

MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'reversion.middleware.RevisionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'machina.apps.forum_permission.middleware.ForumPermissionMiddleware',
'social_django.middleware.SocialAuthExceptionMiddleware',
'eventlog.middleware.Middleware',
Expand Down Expand Up @@ -250,12 +250,13 @@

HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
'ENGINE': 'haystack.backends.elasticsearch2_backend.Elasticsearch2SearchEngine',
'URL': 'http://'+config('ELASTICSEARCH_ADDRESS')+':9200/',
'INDEX_NAME': 'haystack',
},
}

HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'

COMMENTS_APP='django_comments_xtd'

Expand Down
20 changes: 18 additions & 2 deletions CollaborationSystem/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,14 @@
from Reputation import views as repuationview
from Media import views as mediaview
from TaskQueue import views as taskview
from Community.forms import FacetedSearchForm
from Community.views import FacetedSearchView
from haystack.query import SearchQuerySet
from Categories import views as categoryview
from metadata import views as metadataview
from search import views as SearchView
from workflow import views as workflowview
from django.views.generic import TemplateView
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
Expand Down Expand Up @@ -142,7 +148,10 @@

url(r'^group_content/(?P<pk>\d+)/$', group_views.group_content, name='group_content'),
url(r'^FAQs/$', web.FAQs, name ='FAQs' ),
url(r'^search/', include('haystack.urls')),
#url(r'^search/', include('haystack.urls')),
# url(r'^$', FacetedSearchView.as_view(form_class=FacetedSearchForm, facet_fields=['name'],template_name='search.html', context_object_name='page_object')),
#url(r'^$', FacetedSearchView.as_view(), name='haystack_search'),
#url(r'^search/', FacetedSearchView(form_class=FacetedSearchForm, searchqueryset = SearchQuerySet().facet('desc'), name='haystack_search')),

url(r'^feedback/$', web.provide_feedback, name ='provide_feedback' ),
url(r'^contact_us/$', web.contact_us, name ='contact_us' ),
Expand Down Expand Up @@ -198,15 +207,22 @@

url(r'^community/(?P<cpk>\d+)/media/(?P<mdpk>\d+)/metadata_create/$', metadataview.MetadataCreateView.as_view(), name='metadata_create'),
url(r'^media/(?P<mdpk>\d+)/metadata_update/(?P<pk>\d+)$', metadataview.MetadataUpdateView.as_view(), name='metadata_update'),

url(r'^workflow/transition$', workflowview.getAllStates, name='transition'),
url(r'^workflow/transition/create$', workflowview.createTransitions, name='create_transition'),
]

from wiki.urls import get_pattern as get_wiki_pattern
from django_nyt.urls import get_pattern as get_nyt_pattern

urlpatterns += [
url(r'^wiki-notifications/', get_nyt_pattern()),
url(r'^wiki/', get_wiki_pattern())
url(r'^wiki/', get_wiki_pattern()),
url(r'^search/', FacetedSearchView.as_view(), name='haystack_search'),
# url(r'^search_category/', SearchView.search_queries, name='search_queries'),

]

if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

26 changes: 25 additions & 1 deletion Community/forms.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@

from django import forms
from .models import Community, RequestCommunityCreation
from Categories.models import Category
from mptt.forms import TreeNodeChoiceField
from haystack.forms import FacetedSearchForm

class CommunityCreateForm(forms.ModelForm):

Expand Down Expand Up @@ -92,4 +94,26 @@ def __init__(self, *args, **kwargs):
if community.category:
self.fields['category'] = TreeNodeChoiceField(community.category.get_descendants(include_self=False))
else:
self.fields['category'].queryset = Category.objects.none()
self.fields['category'].queryset = Category.objects.none()



class FacetedProductSearchForm(FacetedSearchForm):

def __init__(self, *args, **kwargs):
data = dict(kwargs.get("data", []))
self.categorys = data.get('category', [])
super(FacetedProductSearchForm, self).__init__(*args, **kwargs)

def search(self):
sqs = super(FacetedProductSearchForm, self).search()
if self.categorys:
query = None
for category in self.categorys:
if query:
query += u' OR '
else:
query = u''
query += u'"%s"' % sqs.query.clean(category)
sqs = sqs.narrow(u'category_exact:%s' % query)
return sqs
1 change: 1 addition & 0 deletions Community/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ def get_file_path(instance, filename):
filename = "%s.%s" % (uuid.uuid4(), ext)
return os.path.join('community', filename)


class Community(MPTTModel):

name = models.CharField(max_length=100)
Expand Down
21 changes: 21 additions & 0 deletions Community/search_indexes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import datetime
from haystack import indexes
from .models import Community
from django.utils import timezone
from haystack.fields import CharField


class CommunityIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.EdgeNgramField(document=True, model_attr='name')
category = indexes.CharField(model_attr='category', faceted=True)
created_at = indexes.DateTimeField(model_attr='created_at')

# for spelling suggestions
suggestions = indexes.FacetCharField()

def get_model(self):
return Community

def index_queryset(self, using=None):
# """Used when the entire index for model is updated."""
return self.get_model().objects.all()
Empty file added Community/urls.py
Empty file.
60 changes: 59 additions & 1 deletion Community/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@
from django.urls import reverse
from Categories.models import Category
from PIL import Image
from django.views.generic import TemplateView
from django.views.generic.detail import DetailView
from django.http import JsonResponse
from haystack.generic_views import FacetedSearchView as BaseFacetedSearchView
from haystack.query import SearchQuerySet
from .forms import FacetedProductSearchForm
from UserRolesPermission.models import ProfileImage
from django.db.models import Count
from django.db.models import F
Expand Down Expand Up @@ -430,7 +436,10 @@ def create_forum(self, name, desc):
try:
cursor = connection.cursor()
cursor.execute(''' select tree_id from forum_forum order by tree_id DESC limit 1''')
tree_id = cursor.fetchone()[0] + 1
try:
tree_id = cursor.fetchone()[0] + 1
except:
tree_id = 0
slug = "-".join(name.lower().split())
#return HttpResponse(str(tree_id))
insert_stmt = (
Expand Down Expand Up @@ -724,3 +733,52 @@ def create_wiki_for_community(community):


cursor.execute('''SET FOREIGN_KEY_CHECKS=1''')

def community_media_create(request):
if request.user.is_authenticated:
if request.method == 'POST':
status = request.POST['status']
cid = request.POST['cid']
community = Community.objects.get(pk=cid)
if status=='1':
media = create_media(request)
metadata = create_metadata(request)
CommunityMedia.objects.create(media=media, user=request.user, community=community)
MediaMetadata.objects.create(media=media, metadata=metadata)
return redirect('media_view', media.pk)
else:
return render(request, 'new_media.html', {'community':community, 'status':1})
else:
return redirect('home')
else:
return redirect('login')


class FacetedSearchView(BaseFacetedSearchView, TemplateView):

form_class = FacetedProductSearchForm
facet_fields = ['category']
template_name = 'search_result.html'
#paginate_by = 3
#context_object_name = 'object_list'

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
print("self.request.GET >>>>>>>>>>>>>>>>>>>>> ", self.request.GET)
try:
if 'community' in self.request.GET:
context['community'] = self.request.GET['community']
if 'article' in self.request.GET:
context['article'] = self.request.GET['article']
if 'image' in self.request.GET:
context['image'] = self.request.GET['image']
if 'audio' in self.request.GET:
context['audio'] = self.request.GET['audio']
if 'video' in self.request.GET:
context['video'] = self.request.GET['video']
if 'query' in self.request.GET:
context['query'] = self.request.GET['query']
except:
pass
return context

6 changes: 5 additions & 1 deletion Media/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,8 @@ class Media(models.Model):
published_on=models.DateTimeField(null=True)
published_by=models.ForeignKey(User,null=True,related_name='media_publisher')
views = models.PositiveIntegerField(default=0)
state = models.ForeignKey(States, null=True,related_name='media_workflow')
state = models.ForeignKey(States, null=True,related_name='media_workflow')

def get_absolute_url(self):
from django.urls import reverse
return reverse('media_view', kwargs={'pk': self.id})
23 changes: 23 additions & 0 deletions Media/search_indexes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import datetime
from haystack import indexes
from .models import Media
from django.utils import timezone
from haystack.fields import CharField


class MediaIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.EdgeNgramField(document=True, model_attr='title')
#category = indexes.CharField(model_attr='category', faceted=True)
mediafile = indexes.CharField(model_attr='mediafile')
state = indexes.CharField(model_attr='state')


# for spelling suggestions
#suggestions = indexes.FacetCharField()

def get_model(self):
return Media

def index_queryset(self, using=None):
# """Used when the entire index for model is updated."""
return self.get_model().objects.all()
Binary file modified Recommendation_API/__pycache__/views.cpython-35.pyc
Binary file not shown.
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
version: '3'
version: '2'

services:
db:
Expand Down
2 changes: 1 addition & 1 deletion eventlog/tests/test_api_essearch.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ def setUp(self):
{'match': {'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36'}},
{'match': {'user-id': '1'}}],
"filter": [
{
{
"term": {
"user-id": 1
}
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ django-notifications-hq==1.4.0
django-activity-stream==0.6.5
django-jsonfield==1.0.1
django-jsonfield-compat==0.4.4
elasticsearch
elasticsearch==2.3.0
social-auth-core==1.7.0
-e git+https://github.com/devjones/PyEtherpadLite.git#egg=PyEtherpadLite
wiki==0.3.1
Expand Down
Loading

0 comments on commit d108964

Please sign in to comment.