<<<<<<< HEAD
<<<<<<< HEAD
from django import forms
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserChangeForm
from django.contrib.auth.forms import UsernameField
from django.utils.translation import gettext_lazy as _

# Register your models here.
from .models import BlogUser


class BlogUserCreationForm(forms.ModelForm):
    password1 = forms.CharField(label=_('password'), widget=forms.PasswordInput)
    password2 = forms.CharField(label=_('Enter password again'), widget=forms.PasswordInput)

    class Meta:
        model = BlogUser
        fields = ('email',)

    def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError(_("passwords do not match"))
        return password2

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.source = 'adminsite'
            user.save()
        return user


class BlogUserChangeForm(UserChangeForm):
    class Meta:
        model = BlogUser
        fields = '__all__'
        field_classes = {'username': UsernameField}

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)


class BlogUserAdmin(UserAdmin):
    form = BlogUserChangeForm
    add_form = BlogUserCreationForm
    list_display = (
        'id',
        'nickname',
        'username',
        'email',
        'last_login',
        'date_joined',
        'source')
    list_display_links = ('id', 'username')
    ordering = ('-id',)
=======
from django.contrib import admin
from django.urls import reverse
from django.utils.html import format_html  # 用于安全地生成HTML内容
from django.utils.translation import gettext_lazy as _  # 用于国际化翻译


# 自定义批量操作：禁用评论状态
def disable_commentstatus(modeladmin, request, queryset):
    queryset.update(is_enable=False)  # 将选中的评论记录is_enable字段设为False


# 自定义批量操作：启用评论状态
def enable_commentstatus(modeladmin, request, queryset):
    queryset.update(is_enable=True)  # 将选中的评论记录is_enable字段设为True


# 为批量操作设置显示名称（支持国际化）
disable_commentstatus.short_description = _('Disable comments')
enable_commentstatus.short_description = _('Enable comments')


class CommentAdmin(admin.ModelAdmin):
    list_per_page = 20  # 每页显示20条记录

    list_display = (
        'id',
        'body',  # 评论内容
        'link_to_userinfo',  # 自定义字段：链接到用户信息
        'link_to_article',  # 自定义字段：链接到文章
        'is_enable',  # 是否启用
        'creation_time'  # 创建时间
    )
    # 列表页中可点击跳转编辑页的字段
    list_display_links = ('id', 'body', 'is_enable')
    # 可筛选的字段（右侧过滤器）
    list_filter = ('is_enable',)
    # 编辑页排除的字段（不允许编辑，如自动生成的时间）
    exclude = ('creation_time', 'last_modify_time')
    # 注册自定义批量操作
    actions = [disable_commentstatus, enable_commentstatus]

    # 自定义列表字段：生成用户信息的编辑链接
    def link_to_userinfo(self, obj):
        # 获取用户模型的app标签和模型名称
        info = (obj.author._meta.app_label, obj.author._meta.model_name)
        # 生成用户编辑页的URL
        link = reverse('admin:%s_%s_change' % info, args=(obj.author.id,))
        # 返回带链接的HTML（优先显示昵称，无昵称则显示邮箱）
        return format_html(
            u'<a href="%s">%s</a>' %
            (link, obj.author.nickname if obj.author.nickname else obj.author.email))

    # 自定义列表字段：生成文章的编辑链接
    def link_to_article(self, obj):
        # 获取文章模型的app标签和模型名称
        info = (obj.article._meta.app_label, obj.article._meta.model_name)
        # 生成文章编辑页的URL
        link = reverse('admin:%s_%s_change' % info, args=(obj.article.id,))
        # 返回带链接的HTML（显示文章标题）
        return format_html(
            u'<a href="%s">%s</a>' % (link, obj.article.title))

    # 自定义字段的显示名称（支持国际化）
    link_to_userinfo.short_description = _('User')
    link_to_article.short_description = _('Article')
>>>>>>> zh_branch
=======
from django import forms
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.utils.html import format_html
from django.utils.translation import gettext_lazy as _

# Register your models here.
from .models import Article


class ArticleForm(forms.ModelForm):
    # body = forms.CharField(widget=AdminPagedownWidget())

    class Meta:
        model = Article
        fields = '__all__'


# 管理员动作函数 - 发布选中文章
def makr_article_publish(modeladmin, request, queryset):
    """将选中的文章状态设置为已发布"""
    queryset.update(status='p')


# 管理员动作函数 - 将选中文章设为草稿
def draft_article(modeladmin, request, queryset):
    """将选中的文章状态设置为草稿"""
    queryset.update(status='d')


# 管理员动作函数 - 关闭文章评论
def close_article_commentstatus(modeladmin, request, queryset):
    """关闭选中文章的评论功能"""
    queryset.update(comment_status='c')


# 管理员动作函数 - 开启文章评论
def open_article_commentstatus(modeladmin, request, queryset):
    """开启选中文章的评论功能"""
    queryset.update(comment_status='o')


# 设置管理员动作的显示名称
makr_article_publish.short_description = _('Publish selected articles')
draft_article.short_description = _('Draft selected articles')
close_article_commentstatus.short_description = _('Close article comments')
open_article_commentstatus.short_description = _('Open article comments')


class ArticlelAdmin(admin.ModelAdmin):
    """文章模型的后台管理配置"""
    list_per_page = 20  # 每页显示20条记录
    search_fields = ('body', 'title')  # 搜索字段
    form = ArticleForm  # 使用自定义表单
    list_display = (
        'id',
        'title',
        'author',
        'link_to_category',
        'creation_time',
        'views',
        'status',
        'type',
        'article_order')  # 列表页显示的字段
    list_display_links = ('id', 'title')  # 可点击链接的字段
    list_filter = ('status', 'type', 'category')  # 右侧过滤器
    filter_horizontal = ('tags',)  # 水平多选控件用于标签
    exclude = ('creation_time', 'last_modify_time')  # 排除的字段
    view_on_site = True  # 启用"在站点查看"功能
    actions = [  # 管理员动作列表
        makr_article_publish,
        draft_article,
        close_article_commentstatus,
        open_article_commentstatus]

    def link_to_category(self, obj):
        """生成分类的管理后台链接"""
        info = (obj.category._meta.app_label, obj.category._meta.model_name)
        link = reverse('admin:%s_%s_change' % info, args=(obj.category.id,))
        return format_html(u'<a href="%s">%s</a>' % (link, obj.category.name))

    link_to_category.short_description = _('category')  # 设置列显示名称

    def get_form(self, request, obj=None, **kwargs):
        """自定义表单，限制作者只能选择超级用户"""
        form = super(ArticlelAdmin, self).get_form(request, obj, **kwargs)
        form.base_fields['author'].queryset = get_user_model(
        ).objects.filter(is_superuser=True)
        return form

    def save_model(self, request, obj, form, change):
        """保存模型时的自定义逻辑"""
        super(ArticlelAdmin, self).save_model(request, obj, form, change)

    def get_view_on_site_url(self, obj=None):
        """获取"在站点查看"的URL"""
        if obj:
            url = obj.get_full_url()  # 文章的完整URL
            return url
        else:
            from djangoblog.utils import get_current_site
            site = get_current_site().domain  # 站点域名
            return site


class TagAdmin(admin.ModelAdmin):
    """标签模型的后台管理配置"""
    exclude = ('slug', 'last_mod_time', 'creation_time')  # 排除自动生成的字段


class CategoryAdmin(admin.ModelAdmin):
    """分类模型的后台管理配置"""
    list_display = ('name', 'parent_category', 'index')  # 列表显示字段
    exclude = ('slug', 'last_mod_time', 'creation_time')  # 排除自动生成的字段


class LinksAdmin(admin.ModelAdmin):
    """友情链接模型的后台管理配置"""
    exclude = ('last_mod_time', 'creation_time')  # 排除时间字段


class SideBarAdmin(admin.ModelAdmin):
    """侧边栏模型的后台管理配置"""
    list_display = ('name', 'content', 'is_enable', 'sequence')  # 列表显示字段
    exclude = ('last_mod_time', 'creation_time')  # 排除时间字段


class BlogSettingsAdmin(admin.ModelAdmin):
    """博客设置模型的后台管理配置"""
    pass  # 使用默认管理配置
>>>>>>> hyt_branch
