簡體   English   中英

允許用戶選擇隨機博客

[英]Allow user to select random blog bost

我已經開始使用Django 2.0和Python 3.6.3開發一個網站,該網站將顯示自定義的“帖子”,如博客文章中所示。

我希望用戶能夠單擊一個基本上顯示“ Random Post”的按鈕。 此按鈕會將他們帶到加載隨機博客文章的模板。

這是我的Post模型:

class Post(models.Model):
    post_id = models.AutoField(primary_key=True)
    ... other fields
    ... other fields

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title     

以下是一些相關視圖:

class PostListView(ListView):
    model = Post
    template_name = 'blog/post_list.html'

class PostDetailView(DetailView):
    model = Post
    template_name = 'blog/post_detail.html'

這是我有問題的觀點:

import random

def random_post(request):
    post_ids = Post.objects.all().values_list('post_id', flat=True) 
    random_obj = Post.objects.get(post_id=random.choice(post_ids))
    context = {'random_post': random_obj,}
    return render(request, 'blog/random_post.html', context)

在這里,我試圖為Post模型創建一個所有post_id值的值列表。 然后,我嘗試從此“值列表”中獲得隨機選擇,這將是一個隨機ID。 然后,我嘗試使用此邏輯創建上下文並渲染模板。

以下是相關的urlpatterns:

urlpatterns = [
    path('post/<int:pk>/', 
        views.PostDetailView.as_view(),name='post_detail'),
    path('post/random/<int:pk>', views.random_post, name='random_post'),

不用說這是行不通的。

如果我省略“ int:pk”,它將呈現一個沒有數據的空白模板-沒有博客文章。 如果包含,則會導致錯誤-未找到參數。 我假設視圖中沒有數據查詢,或者數據沒有從視圖中正確發送到模板。

我是Django的新手。 我感謝您的幫助!

對於您想要的行為,您的URL應為:

urlpatterns = [
    path('post/random/', views.random_post, name='random_post'),
    path('post/<int:pk>/', 
        views.PostDetailView.as_view(),name='post_detail'),
]

並且您的random_post視圖是:

def random_post(request):
    post_count = Post.objects.all().count()
    random_val = random.randint(1, post_count-1)
    post_id = Post.objects.values_list('post_id', flat=True)[random_val]
    return redirect('post_detail', pk=post_id)

這將產生兩個查詢-一個用於獲取所有帖子的計數,一個用於獲取隨機位置中的帖子ID。 這樣做的原因是,您不必從數據庫中獲取所有ID-如果您有成千上萬的帖子,那將是非常低效的。

這是可行的視圖。

def random_post(request):
    post_count = Post.objects.all().count()  
    random_val = random.randint(0, post_count-1)  
    post_id = Post.objects.values_list('post_id', flat=True)[random_val]   
    return redirect('post_detail', pk=post_id) #Redirect to post detail view

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM