Django Фильтр шаблонов Объект в статусе X - PullRequest
0 голосов
/ 05 января 2019

Я хочу отобразить все объекты category_request в статусе Отклонено, но, похоже, я здесь что-то не так делаю. Я совершенно новичок в Django / Python, если у кого-то есть идея, пожалуйста, кричите мне об этом;)

models.py

class CategoryRequests(models.Model):
    author = models.ForeignKey(User, related_name='status', on_delete=models.CASCADE)
    title = models.CharField(max_length=20, verbose_name="Title")
    description = models.TextField(max_length=175, null=True, blank=True)
    cover = fields.ImageField(
        blank=True,
        null=True,
        validators=[default_image_size, default_image_file_extension],
        upload_to=get_file_path_user_uploads,
        dependencies=[FileDependency(processor=ImageProcessor(format='JPEG', quality=99, scale={'max_width': 1000, 'max_height': 1000}))])
    published_date = models.DateField(auto_now_add=True, null=True)
    status = StatusField()
    STATUS = Choices('Waiting', 'Rejected', 'Accepted')

views.py

def view_profile_category_requests_rejected(request, pk=None):
    if pk:
        user = get_user_model.objects.get(pk=pk)
        category_request = CategoryRequests(pk=pk)
    else:
        user = request.user
    args = {'user': user,
            'category_request': category_request}
    return render(request, 'myproject/_from_home/category_request_rejected_from_home.html', args)

template.html

{% if user.category_request.status == Rejected %}
        {% if user.category_request_set.count == 0 %}
            <div class="centercontentfloat">
                <div class="card border-primary mb-3">
                    <div class="card-header">No Post's available yet ? ...</div>
                    <div class="card-body text-primary">
                        <p class="card-text">You did not created any posts at all, go ahead and tell the world what it use to know!</p>
                        <a href="{% url 'post_new' %}">
                            <button class="btn btn-dark" type="submit">Create new Post <i class="fa fa-arrow-right"></i></button>
                        </a>
                    </div>
                </div>
            </div>
        {% else %}
            <h4 class="sub-titel-home">Rejected Request(s):</h4>
            <table class="table center class-three-box">
                <thead>
                <tr>
                    <th style="font-size: small">Title</th>
                    <th style="font-size: small">Comment's</th>
                    <th style="font-size: small">Created</th>
                </tr>
                </thead>
                <tbody>
                {% for category_request in user.category_request_set.all %}
                    <tr>
                        <td><a href="{% url 'category_request_detail' pk=category_request.pk %}">{{ category_request.title }}</a></td>
                        <td>{{ category_request.comment_set.count }}</td>
                        <td>{{ category_request.published_date }}</td>
                        </td>
                    </tr>
                {% endfor %}
                </tbody>
            </table>
        {% endif %}
    {% else %}
    <h1 class="center">Rejected-Status filter does not work</h1>
    {% endif %}

    </div>

Так как же отфильтровать только запросы категорий в статусе отклонено и отобразить его в моей таблице?

Заранее спасибо.

1 Ответ

0 голосов
/ 05 января 2019

Бизнес-логика , такая как фильтрация и т. Д., Как правило, записывается на уровне view , not на шаблон уровень. Фактически это одна из причин, по которой Django ограничил синтаксис шаблона, так что выполнение вызовов функций и т. Д. Довольно сложно.

Все, что мы в основном хотим, это CategoryRequests, где author - это User с данным первичным ключом pk, а status - это Rejected. Мы можем получить это с помощью фильтра вроде:

CategoryRequests.objects.<b>filter(author__pk=pk, status='Rejected')</b>

Таким образом, мы можем определить такой набор запросов в представлении:

def view_profile_category_requests_rejected(request, pk=None):
    if pk:
        category_requests = CategoryRequests.objects.filter(
            author__pk=pk, status='Rejected'
        )
    else:
        category_requests = CategoryRequests.objects.filter(
            author=request.user, status='Rejected'
        )
    return render(
        request,
        'myproject/_from_home/category_request_rejected_from_home.html', 
        {'category_requests': category_requests}
    )

в шаблоне, мы можем перебрать category_requests:

{% if <b>not category_requests</b> %}
    <div class="centercontentfloat">
        <div class="card border-primary mb-3">
            <div class="card-header">No Posts available yet...</div>
            <div class="card-body text-primary">
                <p class="card-text">You did not created any posts at all, go ahead and tell the world what it use to know!</p>
                <a href="{% url 'post_new' %}">
                    <button class="btn btn-dark" type="submit">Create new Post <i class="fa fa-arrow-right"></i></button>
                </a>
            </div>
        </div>
    </div>
{% else %}
    <h4 class="sub-titel-home">Rejected Request(s):</h4>
    <table class="table center class-three-box">
        <thead>
        <tr>
            <th style="font-size: small">Title</th>
            <th style="font-size: small">Comment's</th>
            <th style="font-size: small">Created</th>
        </tr>
        </thead>
        <tbody>
        {% for category_request in <b>category_requests</b> %}
            <tr>
                <td><a href="{% url 'category_request_detail' pk=category_request.pk %}">{{ category_request.title }}</a></td>
                <td>{{ category_request.comment_set.count }}</td>
                <td>{{ category_request.published_date }}</td>
                </td>
            </tr>
        {% endfor %}
        </tbody>
    </table>
{% endif %}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...