数据库代码块
1 from django.db import models 2 from django.utils import timezone 3 from django.contrib.auth.models import User 4 5 # Create your models here. 6 class BlogArticles(models.Model): 7 title = models.CharField(max_length=30) 8 author = models.ForeignKey(User,related_name="blog_posts") 9 body = models.TextField()10 publish = models.DateTimeField(default=timezone.now)11 12 class Meta:13 ordering = ("-publish",)14 15 def __str__(self):16 return self.title
显示文章标题代码块
1 from django.shortcuts import render2 from .models import BlogArticles3 4 def blog_title(request):5 blogs = BlogArticles.objects.all()6 return render(request,'blog/titles.html',{ "blogs":blogs})
公共模板base.html
1 {% load staticfiles %} 2 3 4 5 6{% block title %}{% endblock %} 7 8 9 1011 {% block content %}12 {% endblock %}1314 15 16 17
显示文章标题
unblog的url中
url(r'^blog/', include('blog.urls')),
blog的url中
url(r'^blog_title/', views.blog_title),
视图函数
1 from .models import BlogArticles2 3 def blog_title(request):4 blogs = BlogArticles.objects.all()5 return render(request,'blog/titles.html',{ "blogs":blogs})
titles。html
1 {% extends "base.html" %} 2 3 {% block title %}blog titles{% endblock %} 4 5 {% block content %} 67我的博客
816 {% endblock %}91510 {% for blog in blogs %}11
14- { { blog.title }}
12 {% endfor %}13
显示结果
查看文章内容
映射关系
url(r'^blog_title/$', views.blog_title), url(r'^blog_title/(?P\d)/$', views.blog_article),
前端中的title,html更改项目
{% for blog in blogs %}
函数部分
1 def blog_article(request,nid):2 # article=BlogArticles.objects.get(id=nid)3 article= get_object_or_404(BlogArticles,id=nid)4 pub = article.publish5 return render(request,'blog/content.html', { "article":article,"pub":pub})
content.html前端代码
{% extends "base.html" %}{% block title %}blog articel{% endblock %}{% block content %}{ { article.title }}
{% endblock %}{ { article.author.username }} { { pub }}
{ { article.body }}
最后结果
url代码
url(r'^register/$', views.user_register, name='user_register'),
注册的视图函数
def user_register(request): if request.method == 'GET': user_form = RegistrationForm() return render(request, 'account/register.html', { "form": user_form}) if request.method == 'POST': user_form = RegistrationForm(request.POST) print(">>>",request.POST) if user_form.is_valid(): new_user = user_form.save(commit=False) print('1',new_user) new_user.set_password(user_form.cleaned_data['password']) print('2',new_user) new_user.save() return HttpResponse('注册成功') else: return HttpResponse('注册失败') else: user_form = RegistrationForm() return render(request, 'account/register.html', { "form": user_form})
html验证的代码
注册时的代码html的代码
1 {% extends "base.html" %} 2 {% load staticfiles %} 3 {% block title %}用户注册{% endblock %} 4 5 {% block content %} 6 30 {% endblock %}
未完待续