Potrzebuję dwóch sposobów na kategoryzowanie moich postów w Django. Pierwszy jest szkołę, a drugi jest typu odnowy biologicznej (fizyczna / psychiczna itp.)

Models.py

from django.db import models
from django.db.models.signals import pre_save
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
from ckeditor.fields import RichTextField
from ckeditor_uploader.fields import RichTextUploadingField
from PIL import Image

class Category(models.Model):
    name = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, unique=True)

    class Meta:
        ordering = ('name',)
        verbose_name = 'category'
        verbose_name_plural = 'categories'

    def __str__(self):
        return self.name

class School(models.Model):
    name = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, unique=True)

    class Meta:
        ordering = ('name',)
        verbose_name = 'school'
        verbose_name_plural = 'schools'

    def __str__(self):
        return self.name


class VideoPost(models.Model):
    category = models.ForeignKey('Category', on_delete=models.CASCADE)
    school = models.ForeignKey('School', on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, unique = True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    video = models.CharField(max_length=100, blank=True)
    content = RichTextUploadingField()
    image = models.ImageField(upload_to='images', null=True, blank=True)
    date_posted = models.DateTimeField(default=timezone.now)

    def _get_unique_slug(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(VideoPost, self).save(*args, **kwargs)

    def __unicode__(self):
        return self.title

Views.py

from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from .models import VideoPost
from .forms import PostForm
from django.shortcuts import redirect
# Create your views here.

def post_list(request):
    posts = VideoPost.objects.order_by('-date_posted')
    return render(request, 'stories/browse.html', {'posts': posts})

def post_detail(request, post_slug):
    # post = get_object_or_404(VideoPost, pk=pk)
    post = get_object_or_404(VideoPost, slug=post_slug)
    return render(request, 'stories/post_detail.html', {'post': post})

def post_new(request):
        if request.method == "POST":
            form = PostForm(request.POST, request.FILES)
            if form.is_valid():
                post = form.save(commit=False)
                post.author = request.user
                post.published_date = timezone.now()
                post.save()
                return render(request, 'stories/post_detail.html')
        else:
            form = PostForm()
        return render(request, 'stories/post_new.html', {'form': form})

Urls.py

## the way it is right now is displaying all posts no matter what category they are in
('post/', story_views.post_list, name='post_list'),

## I think this is how to categorize and sort them by category? but not working properly
# path('post/<slug:post_category>', story_views.post_list, name='post_list'),


('post/<slug:post_slug>/', story_views.post_detail, name='post_detail'),
('post/new', story_views.post_new, name='post_new'),

W szablonie

//for A School
// It should link to Post lists that have "A" school category and its type of wellness
//something like

<a href="{% url 'post_list' A_School, Physical %}">
<a href="{% url 'post_list' A_School, Mental %}">

//for B School as well
<a href="{% url 'post_list' B_School, Physical %}">
<a href="{% url 'post_list' B_School, Mental %}">

Nie jestem pewien, czy pytanie jest wystarczająco jasne. To, w którym utknąłem na wyświetlaniu postów według dwóch różnych kategorii i łączenia go z wzorem URL szablonu. Każda pomoc byłaby bardzo doceniana.

0
Hobbit Y 22 marzec 2020, 22:24

1 odpowiedź

Najlepsza odpowiedź

Powinien być czytelny, nie ma potrzeby wyjaśnienia.

def post_list(request):
    category = request.GET.get('category', None)
    whatever = request.GET.get('whatever', None)

    posts = VideoPost.objects.all()

    if category: 
        # you can still use .order_by after .filter()
        posts.filter(category=category)

    if whatever:
        posts.filter(whatever=whatever)

    # do the rest of your logic here like the one above

    return render(request, 'stories/browse.html', {'posts': posts})

Zakłada, że przekazujesz kategorię jako query param www.myexample.com/?category=myawESomeCategory

0
Ahmed I. Elsayed 22 marzec 2020, 21:22