Django学习——结合前面所学实现一个博客小案例
在这个Django博客小案例中,我们将实现一个简单的博客系统,包括创建博客、列出博客列表以及显示单个博客的功能。
首先,我们需要定义模型:
from django.db import models
from django.contrib.auth.models import User
class Blog(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
pub_date = models.DateTimeField('date published')
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
接下来,我们需要创建一个视图来处理博客的创建和显示:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.utils import timezone
from .models import Blog
from .forms import BlogForm
def create_blog(request):
if request.method == "POST":
form = BlogForm(request.POST)
if form.is_valid():
blog = form.save(commit=False)
blog.pub_date = timezone.now()
blog.save()
return HttpResponseRedirect(reverse('blog-detail', args=[blog.id]))
else:
form = BlogForm()
return render(request, 'blog/create_blog.html', {'form': form})
def blog_list(request):
blogs = Blog.objects.all().order_by('-pub_date')
return render(request, 'blog/blog_list.html', {'blogs': blogs})
def blog_detail(request, blog_id):
blog = get_object_or_404(Blog, pk=blog_id)
return render(request, 'blog/blog_detail.html', {'blog': blog})
我们还需要定义一个表单来创建新博客:
from django import forms
from .models import Blog
class BlogForm(forms.ModelForm):
class Meta:
model = Blog
fields = ['title', 'content']
最后,我们需要创建相应的HTML模板来显示表单和博客列表:
create\_blog.html:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
blog\_list.html:
<ul>
{% for blog in blogs %}
<li><a href="{% url 'blog-detail' blog.id %}">{{ blog.title }}</a></li>
{% empty %}
<li>No blogs are available.</li>
{% endfor %}
</ul>
blog\_detail.html:
<h1>{{ blog.title }}</h1>
<p>{{ blog.content }}</p>
<p>Published: {{ blog.pub_date|date:"F j, Y" }}</p>
这个例子展示了如何使用Django框架创建一个简单的博客系统。在实际的应用中,你可能需要添加更多的功能,比如用户登录、注册、评论系统等,但是这已经是一个很好的开始。
评论已关闭