主要是對需求表Product進行設計,在此專案中,我們需要標題、聯絡人、電話等欄位。可參考models.py檔案。
設計欄位如下:
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個頁面,分別是列表頁、詳情頁、提交頁。
我們一一講解
首頁首先是首頁,它的模版位於templates/app/index.html 它主要是用來展示首頁內容, 並提交搜尋詞,到搜尋介面,所有的介面都位於app/urls.py裡面,如下
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的程式碼。它的程式碼非常簡單:
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來限制提交次數,防止惡意提交。
最新評論