Adds automatic slug generation per ajax to posts add

This commit is contained in:
2020-05-29 21:09:14 +00:00
parent f550eb15aa
commit fe114f84ec
3 changed files with 28 additions and 8 deletions

View File

@@ -6,9 +6,11 @@ from .models import Post
class MyPostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title','subtitle', 'image','body','slug','author']
fields = ['title','subtitle','tags', 'image','body','slug','author']
widgets = {'body': CKEditorUploadingWidget(config_name='default')
}
widgets = {'body': CKEditorUploadingWidget(config_name='default')}
class Media:
js = (
'js/auto_slug.js', # inside app static folder
)

View File

@@ -1,8 +1,8 @@
from django.urls import path
from . import views
urlpatterns=[
path('func/slug_calc', views.slug_calc),
path('t/<str:tag>',views.tags,name='posts.tags'),
path('',views.index,name='posts.index'),
path('<str:id>',views.show, name='posts.show'),
]
]

View File

@@ -10,6 +10,9 @@ from rest_framework import permissions
from django_filters.rest_framework import DjangoFilterBackend
from django.core.cache import cache
from django.utils.text import slugify
from django.utils import timezone
def get_next_dict():
posts=Post.news_objects.order_by('-public_date').values('slug')
print(posts)
@@ -41,6 +44,21 @@ def show(request,id=None):
p=Post.objects.get(slug=(id))
return render(request, 'posts/show.html', {"post":p,"next":get_next_dict().get(p.slug,None)})
# Ajax function that is called to calculate a slug from the title
def slug_calc(request):
if request.method == "GET":
get = request.GET.copy()
title = get['title']
datetime_now = timezone.now()
date_str = datetime_now.strftime("%Y-%m-%d")
slug_str = slugify(date_str)+"-"+slugify(title)
return HttpResponse(slug_str)
return HttpResponseServerError("Requires a title field.")
class PostViewSet(viewsets.ModelViewSet):
"""
@@ -53,4 +71,4 @@ class PostViewSet(viewsets.ModelViewSet):
filterset_fields = ['legacy_id', 'slug','legacy_rubrik_id']
lookup_field='slug'
def pre_save(self, obj):
obj.image = self.request.FILES.get('image')
obj.image = self.request.FILES.get('image')