我对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:
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.
谢谢大家!