from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from app1.forms import PersonForm
import time  # 导入时间模块


def index(request):
    return HttpResponse("Hello World")

def article(request,id):
    content = "This article's id is {}".format(id)
    return HttpResponse(content)

def article_detail(request,year,month,slug):
    content = 'the year is {} , the month is {} , the slug is {}'.format(year,month,slug)
    return HttpResponse(content)

def year_archive(request,year):
    return HttpResponse(year)

def current_time(request):  # 定义一个视图方法，必须带有请求对象作为参数
    now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())  # 请求的时间
    html = "<html><body>当前时间：<h1>{}</h1></body></html>".format(now)   # 生成html代码
    return HttpResponse(html)  # 将响应对象返回，数据为生成的html代码



def get_name(request):
    # 判断请求方法是否为POST
    if request.method == 'POST':
        # 将请求数据填充到PersonForm实例中
        form = PersonForm(request.POST)
        # 判断form是否为有效表单
        if form.is_valid():
            # 使用form.cleaned_data获取请求的数据
            first_name = form.cleaned_data['first_name']
            last_name = form.cleaned_data['last_name']
            # 响应拼接后的字符串
            return HttpResponse(first_name + '' + last_name)
        else:
            return HttpResponseRedirect('/error/')
    # 请求为GET方法
    else:
        return render(request, 'name.html', {'form': PersonForm()})
