Issue
I'm still fairly new to Django and trying to get through the docs and basics. My sticking point is that I cannot get a working modelform on page X to be included inside of another template Y. It's a very simple example derived from django docs. I've looked at the many other SO posts and have tried the obvious fixes to no avail. (they did fix bigger issues but I'm left with this)
I ultimately plan to embed modelforms into modals, but at this stage cannot even render them into other html and some help would be appreciated.
Python 3.12, Django 4.2.7 on SqLite
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 %}
View for page1:
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.
Thank you!
Solution
Well you don't pass a form
to the context, so it can not render it. You thus need to include it in the context of the second page:
def page1(request):
return render(request, 'page1.html', {'form': TitleForm()})
Answered By - willeM_ Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.