4👍
When using inclusion_tag
, you shouldn’t call render
yourself. You should return the context dictionary (for example: return {'form': form}
) – Django will then take care of rendering the template you named in the @register.inclusion_tag('demo_form.html')
declaration.
I would advise against trying to handle the if request.method == 'POST':
logic within the tag, as that will be triggered any time any page on your site is rendered in response to a POST request – regardless of whether the POST request had anything to do with your DemoForm. Instead, you should set up a Django view to handle those form submissions, and put the URL to that view in the form’s action
attribute.
0👍
What is returned when the request is not a POST or is_valid() is false? I typically use a pattern like this (note the changes at the end):
from .forms import DemoForm
register = template.Library()
@register.inclusion_tag('demo_form.html')
def book_a_demo(request):
form = DemoForm
if request.method == 'POST':
demo_form = form(data=request.POST)
if demo_form.is_valid():
contact_name = request.POST.get('name', '')
company_name = request.POST.get('company', '')
contact_email = request.POST.get('email', '')
contact_phone = request.POST.get('phone', '')
# Email the profile with the
# contact information
template = get_template('contact_template.txt')
context = Context({
'contact_name': contact_name,
'company_name': company_name,
'contact_email': contact_email,
'contact_phone': contact_phone,
})
content = template.render(context)
email = EmailMessage(
"Request to Book a Demo",
content,
"domain" +'',
['example@email.com'],
headers = {'Reply-To': contact_email }
)
email.send()
return render(request, 'demo_form_landing.html')
else:
demo_form = form()
return render(request, 'demo_form.html', {'form': demo_form})