該項目是基於python的web類庫django開發的一套web網站,作爲一個公益項目。html
i.mypython.me/python
django-admin startproject mask
複製代碼
python3 manage.py startapp app
複製代碼
主要是對需求表Product進行設計,在此項目中,咱們須要標題、聯繫人、電話等字段。可參考models.py文件。github
設計字段以下:web
class Product(models.Model):
list_display = ("title", "type", "location")
title = models.CharField(max_length=100,blank=True, null=True)
type = models.IntegerField(default=0)
pv = models.IntegerField(default=0)
contact = models.CharField(max_length=10,blank=True, null=True)
location = models.CharField(max_length=20,blank=True, null=True)
phone = models.CharField(max_length=13, blank=True, null=True)
weixin = models.CharField(max_length=50, blank=True, null=True)
status = models.BooleanField(default=False)
timestamp = models.DateTimeField(auto_now_add=True, null=True)
expire = models.IntegerField(default=1)
複製代碼
本項目一共分爲3個頁面,分別是列表頁、詳情頁、提交頁。django
咱們一一講解bash
首先是首頁,它的模版位於templates/app/index.html 它主要是用來展現首頁內容, 並提交搜索詞,到搜索接口,全部的接口都位於app/urls.py裏面,以下app
app_name = 'app'
urlpatterns = [
path('index', views.IndexView.as_view(), name='index'),
path('detail/<int:pk>', views.DetailView.as_view(), name='detail'),
path('commit', views.CommitView.as_view(), name='commit')
]
複製代碼
咱們設置首頁的路由爲IndexView, 開始編寫IndexView的代碼。它的代碼很是簡單:post
class IndexView(generic.ListView):
model = Product
template_name = 'app/index.html'
context_object_name = 'product_list'
paginate_by = 15
c = None
def get_context_data(self, *, object_list=None, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
paginator = context.get('paginator')
page = context.get('page_obj')
page_list = get_page_list(paginator, page)
context['c'] = self.c
context['page_list'] = page_list
return context
def get_queryset(self):
self.c = self.request.GET.get("c", None)
if self.c:
return Product.objects.filter(type=self.c).order_by('-timestamp')
else:
return Product.objects.filter(status=0).order_by('-timestamp')
複製代碼
咱們再來開發詳情頁,從urls.py中看到,詳情頁是由DetailView來實現的,咱們來窺探它的全貌:網站
class DetailView(generic.DetailView):
model = Product
template_name = 'app/detail.html'
def get_object(self, queryset=None):
obj = super().get_object()
return obj
def get_context_data(self, **kwargs):
context = super(DetailView, self).get_context_data(**kwargs)
return context
複製代碼
它很簡單,繼承了DetailView通用模板類來顯示詳情。
最後再來看一下提交頁,它是由CommitView來實現的。一樣是觀看代碼:
class CommitView(generic.CreateView):
model = Product
form_class = CommitForm
template_name = 'app/commit.html'
@ratelimit(key='ip', rate='2/m')
def post(self, request, *args, **kwargs):
was_limited = getattr(request, 'limited', False)
if was_limited:
messages.warning(self.request, "操做太頻繁了,請1分鐘後再試")
return render(request, 'app/commit.html', {'form': CommitForm()})
return super().post(request, *args, **kwargs)
def get_success_url(self):
messages.success(self.request, "發佈成功! ")
return reverse('app:commit')
複製代碼
它是繼承自CreateView,由於是建立操做嘛,在post中,咱們經過ratelimit來限制提交次數,防止惡意提交。
python3 manage.py runserver
複製代碼