import os
import subprocess
import sys

def install_django():
    try:
        import django
        print("Django уже установлен.")
    except ImportError:
        print("Django не найден. Устанавливаем Django...")
        subprocess.check_call([sys.executable, "-m", "pip", "install", "django", "djangorestframework", "django-cors-headers"])
        print("Django успешно установлен.")

def create_project_structure(project_name, app_name):
    print(f"Создаём директорию для проекта '{project_name}'...")
    subprocess.run(['django-admin', 'startproject', project_name], check=True)
    print(f"Django проект '{project_name}' создан.")

    os.chdir(project_name)

    print(f"Создаём приложение '{app_name}'...")
    subprocess.run(['python', 'manage.py', 'startapp', app_name], check=True)
    print(f"Приложение '{app_name}' создано.")

def update_settings(project_name, app_name):
    settings_path = os.path.join(project_name, 'settings.py')
    with open(settings_path, 'r', encoding='utf-8') as f:
        settings = f.read()

    # Define the new INSTALLED_APPS
    new_installed_apps = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        app_name,
        'rest_framework',
        'corsheaders',
    ]

    # Reconstruct INSTALLED_APPS
    installed_apps_str = "INSTALLED_APPS = [\n" + ",\n".join([f"    '{app}'" for app in new_installed_apps]) + "\n]\n"
    
    # Replace the existing INSTALLED_APPS with the new one
    settings = settings.replace(
        "INSTALLED_APPS = [\n    'django.contrib.admin',\n    'django.contrib.auth',\n    'django.contrib.contenttypes',\n    'django.contrib.sessions',\n    'django.contrib.messages',\n    'django.contrib.staticfiles',\n]",
        installed_apps_str
    )

    # Add 'corsheaders.middleware.CorsMiddleware' to MIDDLEWARE
    middleware = """    'corsheaders.middleware.CorsMiddleware',
    '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',
    """
    settings = settings.replace(
        'MIDDLEWARE = [\n    \'django.middleware.security.SecurityMiddleware\',\n    \'django.contrib.sessions.middleware.SessionMiddleware\',\n    \'django.middleware.common.CommonMiddleware\',\n    \'django.middleware.csrf.CsrfViewMiddleware\',\n    \'django.contrib.auth.middleware.AuthenticationMiddleware\',\n    \'django.contrib.messages.middleware.MessageMiddleware\',\n    \'django.middleware.clickjacking.XFrameOptionsMiddleware\',\n]',
        f"MIDDLEWARE = [\n{middleware}]"
    )

    # Add CORS and other settings at the end
    cors_settings = f"""
CORS_ALLOWED_ORIGINS = [
    "http://localhost:8000",
]
STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, '{app_name}', 'static'),
]

TEMPLATES = [
    {{
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, '{app_name}', 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {{
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        }},
    }},
]
"""
    settings += cors_settings

    with open(settings_path, 'w', encoding='utf-8') as f:
        f.write(settings)
    print("Настройки Django обновлены в settings.py.")

def create_models(app_name):
    models_content = """from django.db import models
from django.contrib.auth.models import User

class Forum(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

class Thread(models.Model):
    forum = models.ForeignKey(Forum, related_name='threads', on_delete=models.CASCADE)
    title = models.CharField(max_length=255)
    author = models.ForeignKey(User, related_name='threads', on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

class Post(models.Model):
    thread = models.ForeignKey(Thread, related_name='posts', on_delete=models.CASCADE)
    author = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f'Post by {self.author.username} on {self.thread.title}'
"""
    models_path = os.path.join(app_name, 'models.py')
    with open(models_path, 'w', encoding='utf-8') as f:
        f.write(models_content)
    print("Модели созданы в models.py.")

def create_admin(app_name):
    admin_content = """from django.contrib import admin
from .models import Forum, Thread, Post

admin.site.register(Forum)
admin.site.register(Thread)
admin.site.register(Post)
"""
    admin_path = os.path.join(app_name, 'admin.py')
    with open(admin_path, 'w', encoding='utf-8') as f:
        f.write(admin_content)
    print("Админка настроена в admin.py.")

def create_forms(app_name):
    forms_content = """from django import forms
from .models import Thread, Post

class ThreadForm(forms.ModelForm):
    class Meta:
        model = Thread
        fields = ['title']

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['content']
        widgets = {
            'content': forms.Textarea(attrs={'rows': 4, 'placeholder': 'Введите ваше сообщение...'}),
        }
"""
    forms_path = os.path.join(app_name, 'forms.py')
    with open(forms_path, 'w', encoding='utf-8') as f:
        f.write(forms_content)
    print("Формы созданы в forms.py.")

def create_views(app_name):
    views_content = f"""from django.shortcuts import render, get_object_or_404, redirect
from .models import Forum, Thread, Post
from .forms import ThreadForm, PostForm
from django.contrib.auth.decorators import login_required

def forum_list(request):
    forums = Forum.objects.all()
    return render(request, '{app_name}/forum_list.html', {{'forums': forums}})

def forum_detail(request, forum_id):
    forum = get_object_or_404(Forum, id=forum_id)
    threads = forum.threads.all()
    return render(request, '{app_name}/forum_detail.html', {{'forum': forum, 'threads': threads}})

def thread_detail(request, thread_id):
    thread = get_object_or_404(Thread, id=thread_id)
    posts = thread.posts.all()
    if request.method == 'POST':
        if not request.user.is_authenticated:
            return redirect('login')
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.thread = thread
            post.author = request.user
            post.save()
            return redirect('thread_detail', thread_id=thread.id)
    else:
        form = PostForm()
    return render(request, '{app_name}/thread_detail.html', {{'thread': thread, 'posts': posts, 'form': form}})

@login_required
def create_thread(request, forum_id):
    forum = get_object_or_404(Forum, id=forum_id)
    if request.method == 'POST':
        form = ThreadForm(request.POST)
        if form.is_valid():
            thread = form.save(commit=False)
            thread.forum = forum
            thread.author = request.user
            thread.save()
            return redirect('thread_detail', thread_id=thread.id)
    else:
        form = ThreadForm()
    return render(request, '{app_name}/create_thread.html', {{'forum': forum, 'form': form}})
"""
    views_path = os.path.join(app_name, 'views.py')
    with open(views_path, 'w', encoding='utf-8') as f:
        f.write(views_content)
    print("Представления созданы в views.py.")

def create_serializers(app_name):
    serializers_content = """from rest_framework import serializers
from .models import Forum, Thread, Post
from django.contrib.auth.models import User

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username']

class PostSerializer(serializers.ModelSerializer):
    author = UserSerializer(read_only=True)

    class Meta:
        model = Post
        fields = ['id', 'thread', 'author', 'content', 'created_at']

class ThreadSerializer(serializers.ModelSerializer):
    author = UserSerializer(read_only=True)
    posts = PostSerializer(many=True, read_only=True)

    class Meta:
        model = Thread
        fields = ['id', 'forum', 'title', 'author', 'created_at', 'posts']

class ForumSerializer(serializers.ModelSerializer):
    threads = ThreadSerializer(many=True, read_only=True)

    class Meta:
        model = Forum
        fields = ['id', 'name', 'description', 'created_at', 'threads']
"""
    serializers_path = os.path.join(app_name, 'serializers.py')
    with open(serializers_path, 'w', encoding='utf-8') as f:
        f.write(serializers_content)
    print("Сериализаторы созданы в serializers.py.")

def create_urls(app_name, project_name):
    app_urls_content = f"""from django.urls import path, include
from . import views
from rest_framework import routers
from .serializers import ForumSerializer, ThreadSerializer, PostSerializer
from rest_framework import viewsets

class ForumViewSet(viewsets.ModelViewSet):
    queryset = Forum.objects.all()
    serializer_class = ForumSerializer

class ThreadViewSet(viewsets.ModelViewSet):
    queryset = Thread.objects.all()
    serializer_class = ThreadSerializer

class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer

router = routers.DefaultRouter()
router.register(r'forums', ForumViewSet)
router.register(r'threads', ThreadViewSet)
router.register(r'posts', PostViewSet)

urlpatterns = [
    path('', views.forum_list, name='forum_list'),
    path('forum/<int:forum_id>/', views.forum_detail, name='forum_detail'),
    path('forum/<int:forum_id>/create_thread/', views.create_thread, name='create_thread'),
    path('thread/<int:thread_id>/', views.thread_detail, name='thread_detail'),
    path('api/', include(router.urls)),
]
"""

    with open(os.path.join(app_name, 'urls.py'), 'w', encoding='utf-8') as f:
        f.write(app_urls_content)
    print("URL-ы приложения созданы в urls.py.")

    project_urls_content = f"""from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as auth_views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('{app_name}.urls')),
    path('accounts/login/', auth_views.LoginView.as_view(template_name='{app_name}/login.html'), name='login'),
    path('accounts/logout/', auth_views.LogoutView.as_view(), name='logout'),
]
"""

    project_urls_path = os.path.join(project_name, 'urls.py')
    with open(project_urls_path, 'w', encoding='utf-8') as f:
        f.write(project_urls_content)
    print("Главные URL-ы проекта обновлены.")

def create_templates(app_name):
    templates_dir = os.path.join(app_name, 'templates', app_name)
    os.makedirs(templates_dir, exist_ok=True)

    # base.html
    base_html = f"""<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <title>{{% block title %}}Мой Форум{{% endblock %}}</title>
    <link rel="stylesheet" href="{{% static '{app_name}/styles.css' %}}">
    <script src="{{% static '{app_name}/scripts.js' %}}" defer></script>
</head>
<body>
    <header>
        <h1><a href="{{% url 'forum_list' %}}">Мой Форум</a></h1>
        <nav>
            {{% if user.is_authenticated %}}
                <span>Привет, {{ user.username }}!</span>
                <a href="{{% url 'logout' %}}">Выйти</a>
            {{% else %}}
                <a href="{{% url 'login' %}}">Войти</a>
            {{% endif %}}
        </nav>
    </header>
    <main>
        {{% block content %}}
        {{% endblock %}}
    </main>
    <footer>
        <p>&copy; 2023 Мой Форум</p>
    </footer>
</body>
</html>
"""

    with open(os.path.join(templates_dir, 'base.html'), 'w', encoding='utf-8') as f:
        f.write(base_html)
    print("Шаблон base.html создан.")

    # forum_list.html
    forum_list_html = f"""{{% extends '{app_name}/base.html' %}}

{{% block title %}}Форумы{{% endblock %}}

{{% block content %}}
<h2>Форумы</h2>
<div class="forums">
    {{% for forum in forums %}}
        <div class="forum-card">
            <h3><a href="{{% url 'forum_detail' forum.id %}}">{{{{ forum.name }}}}</a></h3>
            <p>{{{{ forum.description }}}}</p>
        </div>
    {{% empty %}}
        <p>Форумы отсутствуют.</p>
    {{% endfor %}}
</div>
{{% endblock %}}
"""

    with open(os.path.join(templates_dir, 'forum_list.html'), 'w', encoding='utf-8') as f:
        f.write(forum_list_html)
    print("Шаблон forum_list.html создан.")

    # forum_detail.html
    forum_detail_html = f"""{{% extends '{app_name}/base.html' %}}

{{% block title %}}{{{{ forum.name }}}}{{% endblock %}}

{{% block content %}}
<h2>{{{{ forum.name }}}}</h2>
<p>{{{{ forum.description }}}}</p>
<a href="{{% url 'create_thread' forum.id %}}" class="button">Создать тему</a>
<h3>Темы</h3>
<div class="threads">
    {{% for thread in threads %}}
        <div class="thread-card">
            <h4><a href="{{% url 'thread_detail' thread.id %}}">{{{{ thread.title }}}}</a></h4>
            <p>Автор: {{{{ thread.author.username }}}} | Создано: {{{{ thread.created_at }}}}</p>
        </div>
    {{% empty %}}
        <p>Темы отсутствуют.</p>
    {{% endfor %}}
</div>
{{% endblock %}}
"""

    with open(os.path.join(templates_dir, 'forum_detail.html'), 'w', encoding='utf-8') as f:
        f.write(forum_detail_html)
    print("Шаблон forum_detail.html создан.")

    # thread_detail.html
    thread_detail_html = f"""{{% extends '{app_name}/base.html' %}}

{{% block title %}}{{{{ thread.title }}}}{{% endblock %}}

{{% block content %}}
<h2>{{{{ thread.title }}}}</h2>
<p>Автор: {{{{ thread.author.username }}}} | Создано: {{{{ thread.created_at }}}}</p>
<div class="posts">
    {{% for post in posts %}}
        <div class="post">
            <p><strong>{{{{ post.author.username }}}}</strong> написал:</p>
            <p>{{{{ post.content }}}}</p>
            <p class="post-date">Опубликовано: {{{{ post.created_at }}}}</p>
        </div>
    {{% empty %}}
        <p>Сообщений нет.</p>
    {{% endfor %}}
</div>
{{% if user.is_authenticated %}}
    <h3>Добавить сообщение</h3>
    <form method="post">
        {{% csrf_token %}}
        {{{{ form.as_p }}}}
        <button type="submit">Отправить</button>
    </form>
{{% else %}}
    <p><a href="{{% url 'login' %}}?next={{{{ request.path }}}}">Войдите</a>, чтобы добавить сообщение.</p>
{{% endif %}}
{{% endblock %}}
"""

    with open(os.path.join(templates_dir, 'thread_detail.html'), 'w', encoding='utf-8') as f:
        f.write(thread_detail_html)
    print("Шаблон thread_detail.html создан.")

    # create_thread.html
    create_thread_html = f"""{{% extends '{app_name}/base.html' %}}

{{% block title %}}Создать тему в {{{{ forum.name }}}}{{% endblock %}}

{{% block content %}}
<h2>Создать тему в "{{{{ forum.name }}}}"</h2>
<form method="post">
    {{% csrf_token %}}
    {{{{ form.as_p }}}}
    <button type="submit">Создать</button>
</form>
{{% endblock %}}
"""

    with open(os.path.join(templates_dir, 'create_thread.html'), 'w', encoding='utf-8') as f:
        f.write(create_thread_html)
    print("Шаблон create_thread.html создан.")

    # login.html
    login_html = f"""{{% extends '{app_name}/base.html' %}}

{{% block title %}}Вход{{% endblock %}}

{{% block content %}}
<h2>Вход</h2>
<form method="post">
    {{% csrf_token %}}
    {{{{ form.as_p }}}}
    <button type="submit">Войти</button>
</form>
{{% endblock %}}
"""

    with open(os.path.join(templates_dir, 'login.html'), 'w', encoding='utf-8') as f:
        f.write(login_html)
    print("Шаблон login.html создан.")

def create_static_files(app_name):
    static_dir = os.path.join(app_name, 'static', app_name)
    os.makedirs(static_dir, exist_ok=True)

    # styles.css
    styles_css = """body {
    background-color: #121212;
    color: #e0e0e0;
    font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
    margin: 0;
    padding: 0;
}

header {
    background-color: #1f1f1f;
    padding: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

header a {
    color: #e0e0e0;
    text-decoration: none;
}

nav a {
    margin-left: 15px;
    color: #bb86fc;
    text-decoration: none;
}

main {
    padding: 20px;
}

h1, h2, h3, h4 {
    color: #ffffff;
}

.forums, .threads {
    display: flex;
    flex-direction: column;
}

.forum-card, .thread-card, .post {
    background-color: #1e1e1e;
    padding: 15px;
    margin-bottom: 15px;
    border-radius: 5px;
}

.forum-card a, .thread-card a {
    color: #bb86fc;
    text-decoration: none;
}

.forum-card a:hover, .thread-card a:hover {
    text-decoration: underline;
}

.button {
    display: inline-block;
    padding: 10px 15px;
    background-color: #bb86fc;
    color: #121212;
    border-radius: 5px;
    text-decoration: none;
}

.button:hover {
    background-color: #9a67ea;
}

.post-date {
    font-size: 0.8em;
    color: #888888;
}

footer {
    background-color: #1f1f1f;
    text-align: center;
    padding: 10px;
    position: fixed;
    width: 100%;
    bottom: 0;
}

form textarea {
    width: 100%;
    padding: 10px;
    background-color: #2c2c2c;
    border: 1px solid #444;
    color: #e0e0e0;
    border-radius: 5px;
}

form button {
    padding: 10px 15px;
    background-color: #bb86fc;
    color: #121212;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

form button:hover {
    background-color: #9a67ea;
}
"""
    with open(os.path.join(static_dir, 'styles.css'), 'w', encoding='utf-8') as f:
        f.write(styles_css)
    print("Файл styles.css создан.")

    # scripts.js
    scripts_js = """// Пример простого JavaScript для интерактивности
document.addEventListener('DOMContentLoaded', function() {
    // Здесь можно добавить ваш JS код
    console.log('JavaScript подключен и работает!');
});
"""
    with open(os.path.join(static_dir, 'scripts.js'), 'w', encoding='utf-8') as f:
        f.write(scripts_js)
    print("Файл scripts.js создан.")

def create_requirements():
    requirements = """Django==4.2
djangorestframework==3.14.0
django-cors-headers==3.14.0
"""
    with open('requirements.txt', 'w', encoding='utf-8') as f:
        f.write(requirements)
    print("Файл requirements.txt создан.")

def run_migrations(project_name):
    print("Выполняем миграции...")
    subprocess.run(['python', 'manage.py', 'makemigrations'], check=True)
    subprocess.run(['python', 'manage.py', 'migrate'], check=True)
    print("Миграции выполнены.")

def create_superuser():
    print("Создаём суперпользователя...")
    subprocess.run(['python', 'manage.py', 'createsuperuser'])
    print("Суперпользователь создан.")

def main():
    project_name = "forum_project"
    app_name = "forum"

    install_django()
    create_project_structure(project_name, app_name)
    update_settings(project_name, app_name)
    create_models(app_name)
    create_admin(app_name)
    create_forms(app_name)
    create_views(app_name)
    create_serializers(app_name)
    create_urls(app_name, project_name)
    create_templates(app_name)
    create_static_files(app_name)
    create_requirements()
    run_migrations(project_name)
    create_superuser()
    print("\nПроект успешно создан и настроен!")
    print("Запустите сервер разработки командой:")
    print(f"cd {project_name} && python manage.py runserver")

if __name__ == "__main__":
    main()


ошибка

D:\rageforum>py project.py
Django уже установлен.
Создаём директорию для проекта 'forum_project'...
Django проект 'forum_project' создан.
Создаём приложение 'forum'...
Приложение 'forum' создано.
Настройки Django обновлены в settings.py.
Модели созданы в models.py.
Админка настроена в admin.py.
Формы созданы в forms.py.
Представления созданы в views.py.
Сериализаторы созданы в serializers.py.
URL-ы приложения созданы в urls.py.
Главные URL-ы проекта обновлены.
Шаблон base.html создан.
Шаблон forum_list.html создан.
Шаблон forum_detail.html создан.
Шаблон thread_detail.html создан.
Шаблон create_thread.html создан.
Шаблон login.html создан.
Файл styles.css создан.
Файл scripts.js создан.
Файл requirements.txt создан.
Выполняем миграции...
Traceback (most recent call last):
  File "D:\rageforum\forum_project\manage.py", line 22, in <module>
    main()
    ~~~~^^
  File "D:\rageforum\forum_project\manage.py", line 18, in main
    execute_from_command_line(sys.argv)
    ~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^
  File "C:\Users\ivano\AppData\Local\Programs\Python\Python313\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line
    utility.execute()
    ~~~~~~~~~~~~~~~^^
  File "C:\Users\ivano\AppData\Local\Programs\Python\Python313\Lib\site-packages\django\core\management\__init__.py", line 382, in execute
    settings.INSTALLED_APPS
  File "C:\Users\ivano\AppData\Local\Programs\Python\Python313\Lib\site-packages\django\conf\__init__.py", line 81, in __getattr__
    self._setup(name)
    ~~~~~~~~~~~^^^^^^
  File "C:\Users\ivano\AppData\Local\Programs\Python\Python313\Lib\site-packages\django\conf\__init__.py", line 68, in _setup
    self._wrapped = Settings(settings_module)
                    ~~~~~~~~^^^^^^^^^^^^^^^^^
  File "C:\Users\ivano\AppData\Local\Programs\Python\Python313\Lib\site-packages\django\conf\__init__.py", line 166, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "C:\Users\ivano\AppData\Local\Programs\Python\Python313\Lib\importlib\__init__.py", line 88, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap>", line 1387, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1360, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 935, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 1022, in exec_module
  File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed
  File "D:\rageforum\forum_project\forum_project\settings.py", line 136, in <module>
    os.path.join(BASE_DIR, 'forum', 'static'),
    ^^
NameError: name 'os' is not defined. Did you forget to import 'os'?
Traceback (most recent call last):
  File "D:\rageforum\project.py", line 646, in <module>
    main()
    ~~~~^^
  File "D:\rageforum\project.py", line 639, in main
    run_migrations(project_name)
    ~~~~~~~~~~~~~~^^^^^^^^^^^^^^
  File "D:\rageforum\project.py", line 614, in run_migrations
    subprocess.run(['python', 'manage.py', 'makemigrations'], check=True)
    ~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ivano\AppData\Local\Programs\Python\Python313\Lib\subprocess.py", line 577, in run
    raise CalledProcessError(retcode, process.args,
                             output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command '['python', 'manage.py', 'makemigrations']' returned non-zero exit status 1.

D:\rageforum>