我对Django还是相当陌生的,正在努力完成文档和基础知识.我的症结在于我不能将页面X上的工作模型表单包含在另一个模板Y中.这是一个从django docs派生出来的非常简单的例子.我看了许多其他的SO帖子,并try 了明显的修复无效.(他们确实解决了更大的问题,但我留下了这个)

我最终计划将模型表单嵌入到通道中,但在这个阶段甚至不能将它们呈现到其他html中,如果能得到一些帮助将不胜感激.

SqLite上的Python 3.12、Django 4.2.7

Model:

class Title(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)

    def __str__(self):
        return self.title

Form:

class TitleForm(ModelForm):
    class Meta:
        model = Title
        fields = '__all__'

View for the Title modelform (works):

def add_title(request):
    if request.method == 'POST':
        form = TitleForm()
        context = {'form': form}
        print(request.POST) # to see if the form works
        return render(request, 'add_title.html', context)
    else:
        form = TitleForm()
        return render(request, 'add_title.html', {'form': form})

Here is the add_title.html file:

{% block content %}
<h1>Test Form</h1>
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Submit</button>
</form>
{% endblock %}

The modelform is working at the page 127.0.0.1/add_title.html: enter image description here

I would like this form to be embedded in 127.0.0.1/page1. If I can do this, I should be able to eventually include the form in a modal, or anything else. Here is page1.html

{% extends 'base.html' %}
{% block content %}
{% include "include.html" %} # a test of just pure html, renders fine
{% include "add_title.html" %} # this only renders the submit button
{% endblock %}

查看第1页:

def page1(request):
    return render(request, 'page1.html')

When the page renders, it renders another pure html file via include, and it renders the html in the add_title.html but it does not render the two form fields. missing form fields

谢谢大家!

推荐答案

你不会把form传递给上下文,所以它不能呈现它.因此,您需要将其包括在第二页的上下文中:

def page1(request):
    return render(request, 'page1.html', {'form': TitleForm()})

Django相关问答推荐

Django www.example.com从常量列表中删除值

如何在Django REST框架中使用FactoryBoy创建不同的项目

如何在Django模板中获取组中对象的整体计数器(&Q;)?

Django Admin:在一个部分中同时显示多个应用程序?

在Django Rest Framework中按模型属性排序时如何避免重新计算?

QuerySet对象在bulk_update中没有属性pk

django - 让用户登录到测试客户端

try 编辑/创建时,特定模型的 Django 管理员挂起(直到超时错误)

django 在 ubuntu 中安装在哪里

Django 模板列表的第一个元素

Django 模板:通过扩展模板覆盖包含的子模板块

在 django admin 中创建对象时如何自动插入当前用户?

在 Django 中使用 AuthenticationForm

从基于类的通用视图中获取 request.session

如何在 Django 中触发 500 错误?

保存前向 ModelForm 对象添加数据

访问 django 管理模板中的对象

Django Admin - save_model 方法 - 如何检测字段是否已更改?

django rest 框架:从序列化程序 validate() 方法设置字段级错误

Django 测试客户端方法覆盖标头