如何在Django中按类别过滤

时间:2020-07-08 21:24:10

标签: python django django-models django-forms django-views

我一直在从事一个项目,用户可以在其中发表文章,但在填写表格时,用户必须回答2个问题:“您要搜索的内容”和“此帖子的类别”;答案数量有限,并且根据问题的答案,必须过滤用户的帖子并将其张贴在“此帖子来自哪个类别”问题的所选类别中,最后,用户必须重定向到所选类别问题“您要搜索什么”。目前,我的代码只能上传帖子,但我不知道过滤过程在views.py文件中的样子如何,因为我是django的新手,所以请您对此过滤过程有所帮助;)

models.py

CATEGORY_CHOICES = (             #I think this choices can help for the filter
    ('action', 'action'),
    ('sports', 'sports'),
)

class Mates(models.Model):    
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='usermates', unique=True)
    categories = models.CharField(choices=CATEGORY_CHOICES, default="choose...", max_length=10)   #I also think this field will help.
    req_bio = models.CharField(max_length=400)
    req_image = models.ImageField(upload_to='requestmates_pics', null=True, blank=True, default=False)

views.py

def matesmain(request):
    contents = Mates.objects.all()
    context = {
        'contents': contents,
        'form_mates': MatesForm(),
    }
    print("nice3")
    return render(request, 'mates.html', context)

def mates(request):
    if request.method == 'POST':
        form_mates = MatesForm(request.POST, request.FILES)
        if form_mates.is_valid():
            instance = form_mates.save(commit=False)
            instance.user = request.user
            instance.save()
            return redirect('mates-main')
            print('succesfully uploded')

    else:
        form_mates = MatesForm()
        print('didnt upload')
    return redirect('mates-main')

forms.py

class MatesForm(forms.ModelForm):
    class Meta:
        model = Mates
        fields = ('req_bio', 'req_image',)
        exclude = ['user']

mates.html

{% for content in contents %}
    {% if not content.user == user %}
        <div class="mates-grid">
            <div class="mates-grid-1">
                <div class="mates-item">
                    <form action="{% url 'mates' %}" method="post" enctype="multipart/form-data">
                        {% csrf_token %}
                        {{form_mates.as_p}}
                    </form>
                </div>
            </div>
        </div>
    {% elif content.user == user %}
        I have my dynamic data output here
    {% endif %}
{% endfor %}

任何问题,请在评论中让我知道。

1 个答案:

答案 0 :(得分:0)

如果要在“模型”字段上进行过滤,则可以使用.filter()。进一步了解该here

在视图中,看起来应该是这样;

from .models import Mates

def show_mates(request):
    # depending on how you want to get the category
    category = ''

    mates_for_category = Mates.objects.filter(categories=category)

    context = {
        "mates": mates_for_category
    }

    return render(request, template_name='mates_for_category.html', context=context)

根据您的问题,我不明白您希望用户如何按类别进行过滤,因此在此示例中未指定。