<<<<<<< HEAD
from django import forms
<<<<<<< HEAD
from django.contrib.auth import get_user_model, password_validation
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.core.exceptions import ValidationError
from django.forms import widgets
from django.utils.translation import gettext_lazy as _
from . import utils
from .models import BlogUser


class LoginForm(AuthenticationForm):
    def __init__(self, *args, **kwargs):
        super(LoginForm, self).__init__(*args, **kwargs)
        self.fields['username'].widget = widgets.TextInput(
            attrs={'placeholder': "username", "class": "form-control"})
        self.fields['password'].widget = widgets.PasswordInput(
            attrs={'placeholder': "password", "class": "form-control"})


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

        self.fields['username'].widget = widgets.TextInput(
            attrs={'placeholder': "username", "class": "form-control"})
        self.fields['email'].widget = widgets.EmailInput(
            attrs={'placeholder': "email", "class": "form-control"})
        self.fields['password1'].widget = widgets.PasswordInput(
            attrs={'placeholder': "password", "class": "form-control"})
        self.fields['password2'].widget = widgets.PasswordInput(
            attrs={'placeholder': "repeat password", "class": "form-control"})

    def clean_email(self):
        email = self.cleaned_data['email']
        if get_user_model().objects.filter(email=email).exists():
            raise ValidationError(_("email already exists"))
        return email

    class Meta:
        model = get_user_model()
        fields = ("username", "email")


class ForgetPasswordForm(forms.Form):
    new_password1 = forms.CharField(
        label=_("New password"),
        widget=forms.PasswordInput(
            attrs={
                "class": "form-control",
                'placeholder': _("New password")
            }
        ),
    )

    new_password2 = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput(
            attrs={
                "class": "form-control",
                'placeholder': _("Confirm password")
            }
        ),
    )

    email = forms.EmailField(
        label='邮箱',
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'placeholder': _("Email")
            }
        ),
    )

    code = forms.CharField(
        label=_('Code'),
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'placeholder': _("Code")
            }
        ),
    )

    def clean_new_password2(self):
        password1 = self.data.get("new_password1")
        password2 = self.data.get("new_password2")
        if password1 and password2 and password1 != password2:
            raise ValidationError(_("passwords do not match"))
        password_validation.validate_password(password2)

        return password2

    def clean_email(self):
        user_email = self.cleaned_data.get("email")
        if not BlogUser.objects.filter(
                email=user_email
        ).exists():
            # todo 这里的报错提示可以判断一个邮箱是不是注册过，如果不想暴露可以修改
            raise ValidationError(_("email does not exist"))
        return user_email

    def clean_code(self):
        code = self.cleaned_data.get("code")
        error = utils.verify(
            email=self.cleaned_data.get("email"),
            code=code,
        )
        if error:
            raise ValidationError(error)
        return code


class ForgetPasswordCodeForm(forms.Form):
    email = forms.EmailField(
        label=_('Email'),
    )
=======
from django.forms import ModelForm

from .models import Comment


class CommentForm(ModelForm):  # 定义评论表单类，继承自ModelForm
    # 添加父评论ID字段，用于实现评论回复功能
    # 使用HiddenInput控件隐藏显示，且非必填（顶级评论无需父ID）
    parent_comment_id = forms.IntegerField(
        widget=forms.HiddenInput, required=False)

    class Meta:  # Meta类用于配置表单与模型的关联信息
        model = Comment  # 指定表单对应的模型为Comment
        fields = ['body']  # 表单需要包含的模型字段，这里只包含评论内容body
>>>>>>> zh_branch
=======
import logging

from django import forms
from haystack.forms import SearchForm

logger = logging.getLogger(__name__)


class BlogSearchForm(SearchForm):
    """
    博客搜索表单类

    继承自Haystack的SearchForm，用于处理博客文章的搜索功能。
    这个表单定义了搜索框的验证规则和搜索逻辑。
    """

    # 搜索查询字段，设置为必填字段
    querydata = forms.CharField(required=True)

    def search(self):
        """
        执行搜索操作

        重写父类的search方法，添加自定义搜索逻辑：
        1. 调用父类的搜索方法获取基础搜索结果
        2. 验证表单数据是否有效
        3. 记录搜索关键词到日志
        4. 返回搜索结果

        Returns:
            SearchQuerySet: 搜索结果的查询集

        Raises:
            如果表单无效，返回空搜索结果
        """
        # 调用父类的search方法获取基础搜索结果
        datas = super(BlogSearchForm, self).search()

        # 检查表单数据是否有效
        if not self.is_valid():
            # 如果表单无效，返回空搜索结果
            return self.no_query_found()

        # 如果搜索关键词存在，记录到日志中（用于搜索统计和分析）
        if self.cleaned_data['querydata']:
            logger.info(self.cleaned_data['querydata'])

        # 返回搜索结果
        return datas
>>>>>>> hyt_branch
