Django view not rendering - sidebar & header загружаются нормально, но основное содержимое не загружается

Я прошла через столько разных вещей и просто не могу разобраться в этом; нужен свежий взгляд хаха

Мой вид не отображается, и, похоже, это происходит во всех моих приложениях и целевой странице - боковая панель и заголовок загружаются нормально, нижний колонтитул загружается частично, но я считаю, что это связано с тем, что основной контент не загружается.

Снимок экрана текущей HTML страницы - не рендеринг вида

views.py

from django.shortcuts import redirect, render
from django.views import View
from django.views.generic.base import TemplateView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.paginator import Paginator
from django.http import request
from django.http.response import HttpResponse
from django.conf import settings

# Form Imports
from .models import NewRecipeForm

#########################################  
# Form Pages                            #
#########################################

# Recipe View
class RecipesView(LoginRequiredMixin, View):
    def get(self, request):
        content = {}
        content['heading'] = "Recipes Database"
        content['pageview'] = "Recipes & Formulations"
        return render(request, 'nf_recipes/recipes-database.html', content)

#########################################  
# Form Pages                            #
#########################################

# Add New Recipe Form
class AddNewRecipeForm(LoginRequiredMixin, View):
    def get(self, request):
        add_new_recipe_form = NewRecipeForm()
        content = {}
        content['heading'] = "Add New Recipe"
        content['pageview'] = "Recipes & Formulations"
        content['add_new_recipe_form'] = add_new_recipe_form
        return render(request, 'nf_recipes/add-new-recipe.html', content)
    
    def post(self, request):
        if "add-new-recipe-submit" in request.POST:
            add_new_recipe_form = NewRecipeForm(request.POST)
            add_new_recipe_form.save()
            return redirect("/nf_recipes/recipe-db")
# End of Add New Recipe Form

add-new-recipe.html

{% extends 'partials/base.html' %}
{% load static %}
{% load humanize %}
{% load crispy_forms_tags %}

{% block extra_css %}
{% endblock %}

{% block contents %}
<div class="row-fluid">
    <div class="col-12">
        <div class="card">
            <div class="class-body">
                <!-- Add New Recipe Form -->
                <form method="POST">
                    {% csrf_token %}
                    <div class="row">
                        <div class="row-fluid pb-1">
                            <!-- Recipe Name -->
                            <div class="mb-3">
                                <!-- Test page content -->
                                <h3>This is a test</h3>
                            </div>
                        </div>
                    </div>
                </form>
                <!-- End of Add New Recipe Form -->
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_javascript %}
{% endblock %}

models.py

import datetime
from django.db import models
from django import forms
from django.forms.widgets import TextInput, Textarea, DateInput
from django.contrib import admin
from django.contrib.auth.models import User

#########################################  
# Static Datasets                       #
#########################################

# Unit Measurement Sets
unit_measure = [
    (0,'g'),
    (1,'kg'),
    (2,'cup'),
    (3,'cups'),
    (4,'tsp'),
    (5,'tbsp'),
    (6,'cl'),
    (7,'ml'),
    (8,'l')
]

#########################################  
# Models                                #
#########################################

# New Recipe Model
class Recipes(models.Model):
    recipe_idpk = models.AutoField(primary_key=True)
    recipe_name = models.CharField(max_length=250, verbose_name="Recipe Name")
    recipe_date = models.DateField(auto_now_add=True, verbose_name="Recipe Addition Date")
    recipe_description = models.TextField(verbose_name="Recipe Description")

    def __str__(self):
        return f"{self.recipe_name}"

    class Meta:
        ordering = ['-recipe_date']
        verbose_name = 'Recipes'
        verbose_name_plural = 'Recipes'

#########################################  
# Forms                                 #
#########################################

# New Recipe Form
class NewRecipeForm(forms.ModelForm):
    class Meta:
        model = Recipes
        fields = ["recipe_name","recipe_description"]

похоже, что вы используете метод get() для добавления context к вашим представлениям в вашем случае content.

измените ваше представление для использования get_context_data() документации Django.

пример views.py

# Recipe View
class RecipesView(LoginRequiredMixin, View):
    template_name = 'nf_recipes/recipes-database.html'

    def get_context_data(self, **kwargs):
        context = super(RecipesView, self).get_context_data(**kwargs)

        context.update({
            'heading': "Recipes Database",
            'pageview': "Recipes & Formulations"
        })

        return context
        

Вы также можете проверить, что в вашем base.html файле есть тег {% block contents%}

Моя проблема была в моем файле base.html - оказалось, что мой разделитель для layout-wrapper не был закрыт </div>.

Всем, у кого есть подобные проблемы, просмотрите свои основные шаблоны HTML и проверьте, все ли разделители были закрыты правильно.

Вернуться на верх