03
Май
2020

Вывод на сайте информации из модели без for

Задача проста, но ничего не выходит. Есть модель, содержащая переменную. Мне необходимо вывести на сайте информацию из этой переменной, при чём не используя for. Через админку добавил в эту переменную пару значений. Вывести нужно отдельно первое и второе значения.

foods\models.py

from django.db import models


class Food(models.Model):
    name = models.CharField(max_length=30)

    def __str__(self):
        return self.name

В foods\views.py сейчас ничего не написано. Требуется вывести информацию из переменной name

orders\models.py

from django.contrib.auth.models import User
from django.db import models

from foods.models import Food


class PizzaOrder(models.Model):
    cost = models.IntegerField()
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    food = models.ManyToManyField(Food)

class Preference(models.Model):
    preferences = models.TextField(max_length=100)

    def __str__(self):
        return self.preferences

orders\views.py

from django.shortcuts import render
from project.forms import PreferenceForm


def main_page(request):
    return render(request, 'index.html')


def foods_page(request):
    form = PreferenceForm()

    if request.method == 'POST':
        print(request.POST)
        form = PreferenceForm(request.POST)
        if form.is_valid():
            form.save()

    context = {'form': form}
    return render(request, '2index.html', context)

urls.py

from django.contrib import admin
from django.urls import path

from orders.views import main_page, foods_page

urlpatterns = [
    path('admin/', admin.site.urls),
    path('home/', main_page),
    path('foods/', foods_page),
]

forms.py

from django.forms import ModelForm

from orders.models import Preference


class PreferenceForm(ModelForm):
    class Meta:
        model = Preference
        fields = ('preferences',)

2index.html (шаблон для второй страницы сайта)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Foods page</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
          integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
        crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
        integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
        crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
        integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
        crossorigin="anonymous"></script>

<div class="container-fluid">

    <nav class="navbar navbar-expand-lg navbar-light bg-info">
        <div class="badge badge-pill badge-warning">PT</div>
        <strong>PizzaTown</strong>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup"
                aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
            <div class="navbar-nav">
                <a class="nav-item nav-link active" href="home/">Home <span class="sr-only">(current)</span></a>
                <a class="nav-item nav-link" href="foods/">Foods</a>
                <a class="nav-item nav-link" href="orders/">Orders</a>
            </div>
        </div>
    </nav>

    <div class="container-fluid" style="background-color: azure">
        <div class="row">
            <div class="col">
                <div class="card" style="width: 18rem;">
                    <img src="https://api.papajohns.by//images/catalog/thumbs/full/01879ec69cd11aab78a56670ad6d6b52.png"
                         class="card-img-top" alt="Error">
                    <div class="card-body">
                        <p class="card-text"></p>
                    </div>
                </div>
            </div>
            <div class="col">
                <div class="card" style="width: 18rem;">
                    <img src="https://api.papajohns.by//images/catalog/thumbs/full/fe239676da6c27d17d5e64b81f23a1e0.jpg"
                         class="card-img-top" alt="Error">
                    <div class="card-body">
                        <p class="card-text"></p>
                    </div>
                </div>
            </div>
            <div class="col">
                <div class="card" style="width: 18rem;">
                    <img src="https://api.papajohns.by//images/catalog/thumbs/full/20ebe40c3cd391721de15e2df703f83b.jpg"
                         class="card-img-top" alt="Error">
                    <div class="card-body">
                        <p class="card-text"></p>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col">
                <div class="card" style="width: 18rem;">
                    <img src="https://api.papajohns.by//images/catalog/thumbs/full/e89e7886255685e4de87fea5ec5bbd60.png"
                         class="card-img-top" alt="Error">
                    <div class="card-body">
                        <p class="card-text"></p>
                    </div>
                </div>
            </div>
            <div class="col">
                <div class="card" style="width: 18rem;">
                    <img src="https://api.papajohns.by//images/catalog/thumbs/full/92abaa6fbf6240f53f9ecff2e4813709.png"
                         class="card-img-top" alt="Error">
                    <div class="card-body">
                        <p class="card-text"></p>
                    </div>
                </div>
            </div>
            <div class="col">
                <div class="card" style="width: 18rem;">
                    <img src="https://api.papajohns.by//images/catalog/thumbs/full/e6e96cb5447c26324b317b5cd5144e97.jpg"
                         class="card-img-top" alt="Error">
                    <div class="card-body">
                        <p class="card-text"></p>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col">
                <div class="card" style="width: 18rem;">
                    <img src="https://api.papajohns.by//images/catalog/thumbs/full/03993f82fb00da9721e741202854a43e.jpg"
                         class="card-img-top" alt="Error">
                    <div class="card-body">
                        <p class="card-text"></p>
                    </div>
                </div>
            </div>
            <div class="col">
                <div class="card" style="width: 18rem;">
                    <img src="https://api.papajohns.by//images/catalog/thumbs/full/589efbfc513ff9a069e4790c2bbcbdf9.png"
                         class="card-img-top" alt="Error">
                    <div class="card-body">
                        <p class="card-text"></p>
                    </div>
                </div>
            </div>
            <div class="col">
                <div class="card" style="width: 18rem;">
                    <img src="https://api.papajohns.by//images/catalog/thumbs/full/71b9b358e834a863bc3906474601a967.png"
                         class="card-img-top" alt="Error">
                    <div class="card-body">
                        <p class="card-text"></p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <form action="" method="POST">
        {% csrf_token %}
        {{form}}
        <input type="submit">
    </form>

</div>
</body>
</html>

Источник: https://ru.stackoverflow.com/questions/1119733/%D0%92%D1%8B%D0%B2%D0%BE%D0%B4-%D0%BD%D0%B0-%D1%81%D0%B0%D0%B9%D1%82%D0%B5-%D0%B8%D0%BD%D1%84%D0%BE%D1%80%D0%BC%D0%B0%D1%86%D0%B8%D0%B8-%D0%B8%D0%B7-%D0%BC%D0%BE%D0%B4%D0%B5%D0%BB%D0%B8-%D0%B1%D0%B5%D0%B7-for

Тебе может это понравится...

Добавить комментарий