Skip to content

Commit

Permalink
Merge pull request #102 from DJWOMS/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
DJWOMS committed Oct 16, 2019
2 parents f91d58c + cb6b59a commit 5530048
Show file tree
Hide file tree
Showing 19 changed files with 256 additions and 72 deletions.
4 changes: 2 additions & 2 deletions MANIFEST.in
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ prune oms_cms/static/css
prune oms_cms/static/js
prune oms_cms/static/vendor
prune oms_cms/static/img
prune oms_cms/static/fonts
prune oms_cms/static/rest_framework
prune oms_cms/static/range_filter
prune oms_cms/static/dfg_yasg
prune oms_cms/static/drf-yasg
prune oms_cms/static/debug_toolbar
prune oms_cms/static/ckeditor
prune oms_cms/static/mptt

prune oms_cms/templates/admin
prune oms_cms/templates/include
Expand Down
5 changes: 5 additions & 0 deletions docs/devdoc/updates.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
Версии
======

0.5.7
-------

* "news" URL removed

0.5.6
-------

Expand Down
4 changes: 3 additions & 1 deletion oms_cms/backend/comments/admin.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from django.contrib import admin
from django import forms
from django.utils.translation import ugettext_lazy as _

from ckeditor_uploader.widgets import CKEditorUploadingWidget
from django.contrib.contenttypes.admin import GenericStackedInline

Expand All @@ -10,7 +12,7 @@

class CommentAdminForm(forms.ModelForm):
"""Виджет редактора ckeditor"""
comment = forms.CharField(label="Комментарий", widget=CKEditorUploadingWidget())
comment = forms.CharField(label=_("Комментарий"), widget=CKEditorUploadingWidget())

class Meta:
model = OmsComment
Expand Down
3 changes: 2 additions & 1 deletion oms_cms/backend/comments/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@

from .views import *

# app_name = "comments"
app_name = "comments"
urlpatterns = [
path('post/', post_comment, name='post-comment'),
# path("comment-edit/<int:pk>/", EditCommentView.as_view(), name="edit_comment"),
# path("comment-del/<int:pk>/", DeleteComment.as_view(), name="delete_comment")
]
178 changes: 156 additions & 22 deletions oms_cms/backend/comments/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,6 @@
# return HttpResponseRedirect(self.get_success_url())


# class CreateCommentView(AddCommentMixin, View):
# """Добавление комментария"""
#
# def post(self, request, **kwargs):
# self.create_comment(Post.objects.get(slug=kwargs.get("post")))
# return self.next_url()
#
#
# class EditCommentView(View):
# """Редактирование комментария"""
# model = None
Expand Down Expand Up @@ -108,20 +100,20 @@
# form_class = CommentsForm
# template_name = 'news/comment_create.html'
#
# def post(self, request, *args, **kwargs):
# form = CommentsForm(request.POST)
# if form.is_valid():
# form = form.save(commit=False)
# form.user = request.user
# form.post = Post.objects.get(comments=self.kwargs.get('pk'))
# comm_1 = self.model.objects.get(id=self.kwargs.get('pk'))
# form.text = comm_1.user.username + ', ' + form.text
# form.save()
# form.move_to(comm_1)
# return redirect('new-detail',
# lang=self.kwargs.get('lang'),
# category=self.kwargs.get('category'),
# post=self.kwargs.get('post'))
# def post(self, request, *args, **kwargs):
# form = CommentsForm(request.POST)
# if form.is_valid():
# form = form.save(commit=False)
# form.user = request.user
# form.post = Post.objects.get(comments=self.kwargs.get('pk'))
# comm_1 = self.model.objects.get(id=self.kwargs.get('pk'))
# form.text = comm_1.user.username + ', ' + form.text
# form.save()
# form.move_to(comm_1)
# return redirect('new-detail',
# lang=self.kwargs.get('lang'),
# category=self.kwargs.get('category'),
# post=self.kwargs.get('post'))
#
#
# class DeleteComment(View):
Expand All @@ -131,3 +123,145 @@
# comm.delete()
# return redirect('new-detail', lang=lang, category=category, post=post)


from django import http
from django.apps import apps
from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.shortcuts import render
from django.template.loader import render_to_string
from django.utils.html import escape
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.http import require_POST

import django_comments
from django_comments import signals
from django_comments.views.utils import next_redirect, confirmation_view


class CommentPostBadRequest(http.HttpResponseBadRequest):
"""
Response returned when a comment post is invalid. If ``DEBUG`` is on a
nice-ish error message will be displayed (for debugging purposes), but in
production mode a simple opaque 400 page will be displayed.
"""

def __init__(self, why):
super(CommentPostBadRequest, self).__init__()
if settings.DEBUG:
self.content = render_to_string("comments/400-debug.html", {"why": why})


@csrf_protect
@require_POST
def post_comment(request, next=None, using=None):
"""
Post a comment.
HTTP POST is required. If ``POST['submit'] == "preview"`` or if there are
errors a preview template, ``comments/preview.html``, will be rendered.
"""
# Fill out some initial data fields from an authenticated user, if present
data = request.POST.copy()
if request.user.is_authenticated:
if not data.get('name', ''):
data["name"] = request.user.get_full_name() or request.user.get_username()
if not data.get('email', ''):
data["email"] = request.user.email

# Look up the object we're trying to comment about
ctype = data.get("content_type")
object_pk = data.get("object_pk")
if ctype is None or object_pk is None:
return CommentPostBadRequest("Missing content_type or object_pk field.")
try:
model = apps.get_model(*ctype.split(".", 1))
target = model._default_manager.using(using).get(pk=object_pk)
except TypeError:
return CommentPostBadRequest(
"Invalid content_type value: %r" % escape(ctype))
except AttributeError:
return CommentPostBadRequest(
"The given content-type %r does not resolve to a valid model." % escape(ctype))
except ObjectDoesNotExist:
return CommentPostBadRequest(
"No object matching content-type %r and object PK %r exists." % (
escape(ctype), escape(object_pk)))
except (ValueError, ValidationError) as e:
return CommentPostBadRequest(
"Attempting go get content-type %r and object PK %r exists raised %s" % (
escape(ctype), escape(object_pk), e.__class__.__name__))

# Do we want to preview the comment?
preview = "preview" in data

# Construct the comment form
form = django_comments.get_form()(target, data=data)

# Check security information
if form.security_errors():
return CommentPostBadRequest(
"The comment form failed security verification: %s" % escape(str(form.security_errors())))

# If there are errors or if we requested a preview show the comment
if form.errors or preview:
template_list = [
# These first two exist for purely historical reasons.
# Django v1.0 and v1.1 allowed the underscore format for
# preview templates, so we have to preserve that format.
"comments/%s_%s_preview.html" % (model._meta.app_label, model._meta.model_name),
"comments/%s_preview.html" % model._meta.app_label,
# Now the usual directory based template hierarchy.
"comments/%s/%s/preview.html" % (model._meta.app_label, model._meta.model_name),
"comments/%s/preview.html" % model._meta.app_label,
"comments/preview.html",
]
return render(request, template_list, {
"comment": form.data.get("comment", ""),
"form": form,
"next": data.get("next", next),
},
)

# Otherwise create the comment
comment = form.get_comment_object(site_id=get_current_site(request).id)
comment.ip_address = request.META.get("REMOTE_ADDR", None) or None
if request.user.is_authenticated:
comment.user = request.user
# if data.get("comment_perent", None) is not None:
# comm_1 = django_comments.get_model().get(id=data.get("comment_perent"))
# comment.comment = comm_1.user.username + ', ' + comment.comment
# form.move_to(comm_1)
# Signal that the comment is about to be saved
responses = signals.comment_will_be_posted.send(
sender=comment.__class__,
comment=comment,
request=request
)

for (receiver, response) in responses:
if response is False:
return CommentPostBadRequest(
"comment_will_be_posted receiver %r killed the comment" % receiver.__name__)

# Save the comment and signal that it was saved
comment.save()
if data.get("comment_parent", None) is not None and data.get("comment_parent") != '':
comm_1 = django_comments.get_model().objects.get(id=data.get("comment_parent"))
# comment.comment = comm_1.user.username + ', ' + comment.comment
comment.move_to(comm_1)
signals.comment_was_posted.send(
sender=comment.__class__,
comment=comment,
request=request
)

return next_redirect(request, fallback=next or 'comments-comment-done',
c=comment._get_pk_val())


comment_done = confirmation_view(
template="comments/posted.html",
doc="""Display a "comment was posted" success page."""
)
4 changes: 2 additions & 2 deletions oms_cms/backend/contact/management/commands/addcontact.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,12 @@ def handle(self, *args, **options):
)
ContactSocNet.objects.create(
contact_soc=contact_footer,
your_id="djangochannel",
your_id="groups/djangochannel/",
link=SocialNetworks.objects.get(title="Facebook")
)
ContactSocNet.objects.create(
contact_soc=contact_footer,
your_id="DJWOMS",
your_id="DJWOMS/oms_cms",
link=SocialNetworks.objects.get(title="Github")
)
self.stdout.write('Success add contact')
Expand Down
11 changes: 10 additions & 1 deletion oms_cms/backend/languages/models.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from django.contrib.sites.models import Site
from django.conf import settings
from django.db import models
from django.utils.translation import gettext_lazy as _
Expand All @@ -6,14 +7,22 @@
class AbstractLang(models.Model):
"""Абстактная модель для языков"""
lang = models.CharField(_("Язык"), max_length=7, choices=settings.LANGUAGES, default='en')
slug = models.SlugField(
slug = models.CharField(
_("url"),
help_text=_("Укажите url"),
max_length=500,
blank=True,
null=True
)

def get_slug_url(self):
if not self.slug.endswith("/"):
slash = "/"
return f"{Site.objects.get_current().domain}/{self.slug}"

get_slug_url.short_description = 'Site url'
get_slug_url.allow_tags = True

class Meta:
unique_together = ('lang', 'slug')
abstract = True
1 change: 1 addition & 0 deletions oms_cms/backend/menu/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ class MenuItemAdminForm(forms.ModelForm):
class Meta(object):
model = MenuItem
fields = ('__all__')
exclude = ("slug",)
widgets = {
'object_id': GfkLookupWidget(
content_type_field_name='content_type',
Expand Down
4 changes: 2 additions & 2 deletions oms_cms/backend/news/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ class CategoryAdmin(MPTTModelAdmin, ActionPublish):
actions = ['unpublish', 'publish']
inlines = (SeoInlines,)
form = CategoryAdminForm
readonly_fields = ("get_slug_url",)

def save_model(self, request, obj, form, change):
messages.add_message(request, messages.INFO, 'Hello world.')
Expand Down Expand Up @@ -71,6 +72,5 @@ class PostAdmin(ActionPublish):
save_as = True
save_on_top = True
autocomplete_fields = ["tag"]
readonly_fields = ('viewed',)

readonly_fields = ('viewed', "get_slug_url")
inlines = (SeoInlines, CommentsInlines,)
4 changes: 0 additions & 4 deletions oms_cms/backend/news/models.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from django.conf import settings
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
from django.contrib.auth.models import User
Expand All @@ -16,7 +15,6 @@ class Category(MPTTModel, AbstractLang):
"""Класс модели категорий сетей"""
name = models.CharField(_("Название"), max_length=50)
description = models.TextField(_("Описание"), max_length=1000, default="", blank=True)
# lang = models.CharField(_("Язык"), max_length=7, choices=settings.LANGUAGES, default='en')
parent = TreeForeignKey(
'self',
verbose_name=_("Родительская категория"),
Expand All @@ -26,7 +24,6 @@ class Category(MPTTModel, AbstractLang):
related_name='children'
)
template = models.CharField(_("Шаблон"), max_length=500, default="news/post_list.html")
# slug = models.SlugField(_("url"), max_length=100, blank=True, null=True)
published = models.BooleanField(_("Отображать?"), default=True)
paginated = models.PositiveIntegerField(_("Количество новостей на странице"), default=5)

Expand Down Expand Up @@ -105,7 +102,6 @@ class Post(AbstractLang):
on_delete=models.CASCADE,
)
template = models.CharField(_("Шаблон"), max_length=500, default="news/post_detail.html")
# slug = models.SlugField(_("url"), max_length=500, unique=True)

published = models.BooleanField(_("Опубликовать?"), default=True)
viewed = models.IntegerField(_("Просмотрено"), default=0)
Expand Down
2 changes: 1 addition & 1 deletion oms_cms/backend/news/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@

app_name = "news"
urlpatterns = [
path("news/", PostView.as_view(), name="all-news"),
path("tag/<slug:tag>/", PostView.as_view(), name="tag-news"),
path("<slug:category>/<slug:post>/", PostDetail.as_view(), name="new-detail"),
path("<slug:slug>/", PostView.as_view(), name="list-news"),
path("", PostView.as_view(), name="all-news"),
]
1 change: 0 additions & 1 deletion oms_cms/backend/news/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ class PostView(ListView):
paginate_by = 5

def get_posts(self):
print(get_language())
return Post.objects.filter(
lang=get_language(),
category__published=True,
Expand Down
1 change: 1 addition & 0 deletions oms_cms/backend/pages/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ class PagesAdmin(ActionPublish):
actions = ['unpublish', 'publish']
inlines = [SeoInlines, BlockPageAdmin]
save_on_top = True
readonly_fields = ("get_slug_url",)



Expand Down
11 changes: 4 additions & 7 deletions oms_cms/backend/pages/management/commands/addpage.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,9 @@ class Command(BaseCommand):
help = 'Add page'

def handle(self, *args, **options):
text_home = """<h3>Language</h3>
                 <p>OMS is written in Python, the fastest growing programming language.</p>
                 <h3>Sites</h3>
                 <p>OMS sites are immediately operational after installation and easily expandable.</p>
                 <h3>Security</h3>
                 <p>OMS is developed on Django which includes security.</p>"""
text_home = """The system is open source, written using the Django framework in the Python
programming language. This cms allows you to make a website in minutes. You can use the
basic template or download from the official site."""
text_about = """<h1>Install OMS CMS in just 4 steps</h1>
<p>pip install oms-cms</p>
<p>oms-start</p>
Expand All @@ -22,7 +19,7 @@ def handle(self, *args, **options):
Pages.objects.create(
title="Home",
text=text_home,
slug=None,
slug="/",
lang=settings.LANGUAGE_CODE
)
Pages.objects.create(
Expand Down
Loading

0 comments on commit 5530048

Please sign in to comment.