Не можу зрозуміти у чому проблема

6 августа, 20:51 Разное 4296 0

Допоможіть будь ласка. Не можу зрозуміти у чому проблема. Чи не логічно.

 

Коли з settings я видаляю рядок CKEDITOR_BASEPATH = '/static/ckeditor/' у мене відображається CKEDITOR з деякими функціями (хоч і не з усіма, що мені потрібні) але варто мені додати рядок KEDITOR_BASEPATH = '/static/ckeditor/' і CKEDITOR на сторінці зникає.

 

Хтось може сказати: видали просто рядок і нехай відображається. Але. По-перше, мені не подобається, що працює не логічно і не правильно. По-друге, static\ckeditor\build\ckeditor.js я розмістив для того, щоб були функції (Різні шрифти, розміри тощо), яких зараз немає.

далі код у моїх html, views,models…


у мене ckeditor в: 

D:\Сайт\ ..\static\ckeditor\package.json

D:\Сайт\... \static\ckeditor\webpack.config.js 

D:\Сайт\ …\static\ckeditor\src 

D:\Сайт\... \static\ckeditor\sample 

D:\Сайт\... \static\ckeditor\build 

D:\Сайт\... \static\ckeditor\build\ckeditor.js


У мене в settings:

 

INSTALLED_APPS = [

    'main',

    'catalog.apps.CatalogConfig',

    'users',

    'ckeditor',

    'django.contrib.admin',

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.messages',

    'django.contrib.staticfiles',

    'dal',

    'dal_select2',

    'widget_tweaks',

    'allauth',

    'allauth.account',

    'allauth.socialaccount',

   'allauth.socialaccount.providers.apple',

   'allauth.socialaccount.providers.facebook',

   'allauth.socialaccount.providers.google',

    'django.contrib.sites',

    'debug_toolbar',

 

]

STATIC_URL = '/static/'

 

STATICFILES_DIRS = [

    os.path.join(BASE_DIR, 'catalog', 'static'),

    os.path.join(BASE_DIR, 'main', 'static'),

]

 

STATIC_ROOT = os.path.join(BASE_DIR, 'static')

 

# Media files

MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

 

CKEDITOR_UPLOAD_PATH = 'uploads/' #путь для загрузки файлов

 

CKEDITOR_BASEPATH = '/static/catalog/ckeditor/' #путь к статическим файлам CKEditor

В html:

 

    {% extends 'main/base.html' %}

 

    {% load static %}

 

    {% block content %}

<script src="{% static 'ckeditor/build/ckeditor.js' %}"></script>

    <div id="editor"></div>

 

    <form method="POST" enctype="multipart/form-data">

        {% csrf_token %}

        {{ form.media }}

        <div class="form-group">

            {{ form.title.label_tag }}

            {{ form.title }}

        </div>

        <div class="form-group">

            {{ form.content.label_tag }}

            {{ form.content }}

        </div>

        <div class="form-group">

            {{ form.file.label_tag }}

            {{ form.file }}

        </div>

 

       

        <button type="submit">Загрузить</button>

 

    </form>

 

    {% endblock %}

views:

 

 

class ChapterDetail(DetailView):

    model = Chapter

 

    template_name = 'catalog/chapter_detail.html'

    context_object_name = 'chapter'

 

    def get_object(self, queryset=None):

        if queryset is None:

            queryset = self.get_queryset()

 

        book_slug = self.kwargs.get('book_slug')

        chapter_slug = self.kwargs.get('chapter_slug')

 

        if book_slug is not None and chapter_slug is not None:

            return get_object_or_404(queryset, book__slug=book_slug, slug=chapter_slug)

 

        raise AttributeError("Book slug and chapter slug expected in the URL pattern")

 

    def get_context_data(self, **kwargs):

        context = super().get_context_data(**kwargs)

        context['form'] = CommentForm()  # add this line

        return context

 

 

class ChapterCreate(LoginRequiredMixin, UserPassesTestMixin, CreateView):

    model = Chapter

    form_class = ChapterForm

    template_name = 'catalog/chapter_form.html'

 

    def form_valid(self, form):

        book_slug = self.kwargs['book_slug']

        book = get_object_or_404(Book, slug=book_slug)

        form.instance.book = book

 

        # If a file was uploaded

        if form.instance.file:

            try:

                # Read the file and put its content into the 'content' field

                file_content = form.instance.file.read().decode('utf-8')

                form.instance.content = file_content

            except Exception as e:

                messages.error(self.request, f"Error reading file: {str(e)}")

                return super().form_invalid(form)

        elif not form.instance.content:

            messages.error(self.request, "You must provide chapter content or upload a file.")

            return super().form_invalid(form)

 

        return super().form_valid(form)

 

    deftest_func(self):

        # test_func проверяет, выполняется ли условие для данного пользователя

        # Если пользователь в группе 'Перекладач', он может создать главу

 

        return self.request.user.groups.filter(name='Перекладач').exists()

 

    def get_success_url(self):

        book_slug = self.object.book.slug  # здесь мы получаем slug из созданной главы

        chapter_slug = self.object.slug

        return reverse('catalog:chapter_detail', kwargs={'book_slug': book_slug, 'chapter_slug': chapter_slug})

forms:

 

class ChapterForm(forms.ModelForm):

 

    content = forms.CharField(widget=CKEditorWidget())

 

    class Meta:

        model = Chapter

        fields = ['title', 'content', 'file']

 

        help_texts = {

            'file': 'You can upload a text file instead of typing in the content.',

        }

 

models:

class Chapter(models.Model):

    book = models.ForeignKey('catalog.Book', on_delete=models.CASCADE, related_name='book_chapters')

    title = models.CharField(max_length=255)

    content = RichTextField(config_name='extends', blank=True, null=True)

    file = models.FileField(upload_to='chapters/', blank=True, null=True)

    created_at = models.DateTimeField(auto_now_add=True)

    slug = models.SlugField(blank=False, null=False)

 

    def save(self, *args, **kwargs):

        if not self.slug:

          self.slug = slugify(self.title)

        super().save(*args, **kwargs)

 

 

urls:

from django.contrib import admin

from django.urls import include, path

from django.conf import settings

from django.conf.urls.static import static

 

 

urlpatterns = [

    path('admin/', admin.site.urls),

    path('', include('main.urls')),

    path('catalog/', include(('catalog.urls', 'catalog'), namespace='catalog')),

    path('users/', include(('users.urls', 'users'), namespace='users')),

    path('ckeditor/', include('ckeditor_uploader.urls')) #текстовый редактор CKEditor

] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

 

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

 

if settings.DEBUG:

    import debug_toolbar

    urlpatterns += [

        path('__debug__/', include(debug_toolbar.urls)),

    ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

 

0 комментариев
Сортировка:
Добавить комментарий

IT Новости

Смотреть все