Django: Uploading files with AJAX: Form says that the file input field is empty (or CSRF token missing or incorrect) - ajax

I'm trying to add a very simple file upload modal form in my Django app.
But, when I click the submit button, the form shows me an error message: "this field is required".
Everything renders correctly:
My main page loads correctly
When I click in the "Agregar archivo adjunto" button ("add attachment"), the modal form shows correctly, and all the fields are rendered as I want them to.
The issue comes when I click on the "Adjuntar archivo" ("attach file") button in my modal field: The form throws an error, as if I was trying to upload a "null" file!
Now... I forgot to add cache: false, contentType: false, processData: false to the $.ajax() call, but, when I add them, I get the following error: Forbidden (CSRF token missing or incorrect.). So... I don't know how to proceed!
I've already wrote (successfully) a modal form which helps me add notes (related) to my lead object (using this reference), and I'm trying to reproduce exactly the same process for a file upload modal dialog... but it doesn't work :(
Any help will be really appreciated.
By the way: I'm testing this using Chrome (no IE will be used!)
Here is my code:
models.py
def lead_dir_path(instance, filename):
"""
Files will be saved to: MEDIA_ROOT/leads/<int:pk>/<filename>
where <int:pk> is lead's primary key, and <filename> is just that.
Filename will be set to an UUID value.
"""
ext = filename.split('.')[-1]
filename = '%s.%s' % (uuid.uuid4(), ext)
return 'leads/%s/%s' % (instance.lead.pk, filename)
class ArchivosAdjuntosLead(models.Model):
lead = models.ForeignKey(Lead, on_delete=models.CASCADE)
descripcion = models.CharField(max_length=100)
archivo = models.FileField(upload_to=lead_dir_path)
views.py
def agregar_adjunto_json(request, pk):
"""
Adds a file to lead with id=pk
"""
context = {}
data = {}
lead = get_object_or_404(Lead, pk=pk)
context['lead'] = lead
if request.method == 'POST':
form = AdjuntarArchivoLeadForm_v2(request.POST, request.FILES)
if form.is_valid():
form.save();
data['form_is_valid'] = True
else:
data['form_is_valid'] = False
else:
form = AdjuntarArchivoLeadForm_v2()
form.initial = {'lead': lead}
context['form'] = form
data['html_form'] = render_to_string(
template_folder + 'partial_templates/partial_adjuntar_archivo.html',
context,
request = request,
)
return JsonResponse(data)
forms.py
class AdjuntarArchivoLeadForm_v2(forms.ModelForm):
class Meta():
model = ArchivosAdjuntosLead
fields = ['lead', 'descripcion', 'archivo']
widgets = {
'lead': forms.TextInput(attrs={'class':'form-control', 'style':'display:none;'}),
'descripcion': forms.TextInput(attrs={'class':'form-control'}),
'archivo': forms.FileInput(attrs={'class':'form-control'}),
}
partial_adjuntar_archivo.html
I use this partial template to create a modal form:
<form method="POST" enctype="multipart/form-data"
action="{% url 'leads:agregar_adjunto_v2' pk=lead.pk %}"
id="js_adjuntar_archivo_form">
{% csrf_token %}
<div class="modal-header">
<h4 class="modal-title">Adjuntar archivo</h4>
</div>
<div class="modal-body">
{{ form.as_p }}
<div class="modal-footer">
<button type="submit" class="btn btn-primary col-4">Adjuntar archivo</button>
<button type="button" class="btn btn-secondary col-4" data-dismiss="modal">Cancelar</button>
</div>
</div>
</form>
my_lead_page.html
This is the page where I create the modal form:
{% extends "leads/base.html" %}
{% load static %}
{% block contenido %}
<!-- Lots and lots of info -->
<button type="button" class="btn btn-sm btn-primary col-2" id="btn_agregar_adjunto">
Agregar archivo adjunto
</button>
{% endblock %}
{% block other_scripts %}
<script type="text/javascript" src="{% static 'js/leads/archivos_adjuntos.js'%}"></script>
{% endblock %}
archivos_adjuntos.js
$(function() {
$("#btn_agregar_adjunto").click(function() {
$.ajax({
url: 'adjuntar_archivo/',
type: 'get',
dataType: 'json',
beforeSend: function() {
$("#modal-form").modal("show");
},
success: function(data) {
$("#modal-form .modal-content").html(data.html_form);
}
});
});
$("#modal-form").on("submit", "#js_adjuntar_archivo_form", function() {
var form = $(this);
$.ajax({
url: form.attr("action"),
data: form.serialize(),
type: form.attr("method"),
dataType: 'json',
cache: false,
contentType: false,
processData: false,
success: function(data) {
if(data.form_is_valid) {
alert("Archivo adjuntado");
} else {
$("#modal-form .modal-content").html(data.html_form);
}
}
});
return false;
});
});

Instead of form.serialize() try sending it with js formData() it should work.
Here is an example:
$("#modal-form").on("submit", "#js_adjuntar_archivo_form", function() {
$that = this;
var form = new FormData($(this)[0]);
$.ajax({
url:$that.attr("action"),
type:$that.attr("method"),
data:form,
processData: false,
contentType: false,
// rest of the code'''
});
return false;
});

Related

How to implement ajax Django comment?

What I am doing is following.
post_detail.html
<div class="comment_form">
<form id="comment_form" method="POST" class="post-form">
{% csrf_token %}
{% include "myblog/post_comment.html" %}
<button id="add_comment" type="submit" class="save btn btn-default" >Comment</button>
</form>
</div>
Post detail view
def post_detail(request, slug):
post = get_object_or_404(Post, slug=slug)
return render(request, 'myblog/post_detail.html', {'post': post})
Add comment to post
def add_comment_post(request, slug):
form = CommentForm(request.POST or None)
if request.method == "POST":
post = get_object_or_404(Post, slug=slug)
form = CommentForm(request.POST or None)
if form.is_valid():
lst_com = form.save(commit=False)
lst_com.post = post
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
lst_com.ip_address = ip
lst_com.published_date = timezone.now()
lst_com.save()
return render_to_response('myblog/post_comment.html', {'form': form }, RequestContext(request))
ajax request_to_add_comment_post
$('#add_comment').click(function() {
$("input[name=csrfmiddlewaretoken]").val()},
$.ajax({
type: "POST",
url: "comment/",
data: {'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()},
success: addSucsess,
dataType: 'html'
});
});
function addSucsess(data, textStatus, jqXHR)
$('#comment_form').html(data);
Now, my problem here is when add_comment_post return "render_to_response", post_detail.view is called again. How to solve this? What is the correct solution ?

Django-registration ajax post form

registration and to make validations I will be submitting the form via Ajax.
I have checked other posts and tried some options, but the csrf_token gives a jscript error
Uncaught SyntaxError: Unexpected identifier
The form is for login, and if data is entered ok, the form submits ok even with the error. But if the entered data is wrong, just does nothing.
$(document).on("submit", this.id, function(e) {
e.preventDefault();
var frm = e.target.id;
var frmData = $("#"+frm).serialize();
$.ajax({
type: "POST",
url: '{% url 'django.contrib.auth.views.login' %}',
contentType: 'application/x-www-form-urlencoded;charset=utf-8',
csrfmiddlewaretoken : '{% csrf_token %}',
data: frmData,
success: function(data)
{
console.log('success');
},
error: function (data) {
console.log('error');}
});
I also have the csrf_token tag in the form.
I think this will solve your problem:
// ajax components
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
};
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
And what my form looked like:
<ul class="sub-menu collapse" id="settings">
<form id="glucose_boundary_form" action="/glucose/goals" method="POST">
{% csrf_token %}
{{ glucose_boundary_form.as_p }}
</form>
<button type="submit" id="glucose_goals">Submit</button>
</ul>
What a button click looked like
$('button#glucose_submit').click(function() {
$.ajax({
url:'glucose/submit',
type: 'POST',
data: $('form#glucose_form').serialize(),
success: function(data) {
document.getElementById("glucose_form").reset();
}
});
});
EDIT:
Here is my login and registration view. Although I do not use ajax for registration. The form validation happens automatically for the login page. Hope they helps you see what I'm doing and how you might apply my answer.
from django import forms
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import render
from django.contrib.auth.models import User
from django.contrib.auth import login as auth_login
from django.contrib.auth import logout as auth_logout
from loginregistration.models import loginForm, registrationForm
# Login user method
def login(request):
if request.user.is_authenticated():
return HttpResponseRedirect('')
form = loginForm(request.POST or None)
if request.POST and form.is_valid():
user = form.login(request)
if user:
auth_login(request, user)
return HttpResponseRedirect('/') # Redirect to a success page.
return render(request, 'login.html', {'form': form})
# Logout user method
def logout(request):
auth_logout(request)
return HttpResponseRedirect(reverse('loginregistration.views.login')) # Redirect to a success page.
# Register user method
def register(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/')
if request.method == 'POST': # If the form has been submitted...
form = registrationForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
password = form.cleaned_data['password']
username = form.cleaned_data['username']
email = form.cleaned_data['email']
# Tries to create a new user and add them to the database
try:
User.objects.create_user(username, email=email, password=password, first_name=first_name, last_name=last_name)
except:
#Add error
return HttpResponseRedirect('#ERROR')
return HttpResponseRedirect('/login') # Redirect after POST
else:
form = registrationForm() # An unbound form
return render(request, 'register.html', {'form': form})
Here is my login template:
{% extends "base.html" %}
{% block title %}Login{% endblock %}
{% block content %}
<form method="post" action="" id="login" class="container"
style="background-color: #FFFFFF; max-width: 450px; border-radius: 8px;">
{% csrf_token %}
<h1 style="text-align: center">Login to Your Account</h1>
<div class="form-group container" style="max-width: 300px;">
{{form.as_p}}
<button type="submit" class="btn btn-primary">Login</button>
Create an account
</div><br>
</form>
<script type="text/javascript">document.forms.login.id_username.focus();</script>
{% endblock %}
Here is my registration template:
{% extends "base.html" %}
{% block title %}Create Account{% endblock %}
{% block content %}
<form method="post" action="" id="register" class="container "
style="background-color: #FFFFFF; max-width: 450px; border-radius: 8px;">
{% csrf_token %}
<h1 style="text-align: center">Register for an Account</h1>
<b></b>
<p style="text-align: center">WARNING: This is a prototype website for testing purposes only. For security reasons, do not use your real credentials!</p>
<div class="form-group container" style="max-width: 300px;">
{{form.as_p}}
<button type="submit" class="btn btn-primary btn-block">Create The Account</button>
</div>
</form>
<script type="text/javascript">document.forms.register.id_firstName.focus();</script>
{% endblock %}

Django - Ajax modal login/registration

I have a project in which I need to pop a modal window for not authenticated users.
This modal will allow to login directly or create an account.
So it will contain two forms:
django.contrib.auth.forms.AuthenticationForm
registration.forms.RegistrationForm
Here is my view to get both forms:
def ajax_registration(request):
obj = {
'login_form': AuthenticationForm(),
'registration_form': RegistrationForm(),
}
return render(request, 'common/ajax_registration.html', obj)
And my template displaying the forms tabbed
<ul class="nav nav-tabs">
<li>{% trans 'Login' %}</li>
<li>{% trans 'Registration' %}</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="tab1">
{{ login_form|bootstrap }}
</div>
<div class="tab-pane" id="tab2">
{{ registration_form|bootstrap }}
</div>
</div>
Question is: Since I'm using ajax to display this modal, How can I validate the selected form, preferably using the already written django-registrations register & django.contrib.auth login views ?
In addition to Maddog's answer you need some javascript to submit the form back to the URL that rendered the form. Using jquery it could be something like:
$('form').submit(function(e){
e.preventDefault();
var form = $(e.target);
$.ajax({
url: '{% url YOUR_REGISTRATION_URL %}',
type: 'post',
data: account_form.serialize() + '&' + form.serialize(),
error: function(xhr, ajaxOptions, thrownError){ alert(thrownError); },
success: function(){}
})
})
You don't need to do it with a form submit element, you could use any element with $().click(), of course.
Something like this?
def ajax_registration(request):
login_form, registration_form = False, False
if request.method == "POST":
if "email" in request.POST: # some condition to distinguish between login and registration form
login_form = AuthenticationForm(request.POST)
if login_form.is_valid():
# log in
else:
registration_form = RegistrationForm(request.POST)
if registration_form.is_valid():
# register
obj = {
'login_form': login_form if login_form else AuthenticationForm(),
'registration_form': registration_form if registration_form else RegistrationForm(),
}
return render(request, 'common/ajax_registration.html', obj)

Django - after submitting invalid form submit button upon click redirects

I have a django project in which i have a form in a div being loaded by ajax.
when I submit the form with empty fields it returns the form with the required fields shown.
when I hit submit again it redirects to the action of the form instead of reloading the form in the div and showing errors as it does the first time I submit.
does anyone have any idea where the error might be occurring? I imagine somewhere in the ajax or view in my django project.
here is what is returned by the second submit:
{"success": false, "form": "<head>\n\n</head>\n<body>\n<form action=\"/cookbook/createrecipe/\" method=\"POST\" name=\"recipeform\" id=\"createrecipeform\">\n\t<table>\n\t\t<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='c5ea952ee2144b377b375d91b0843c75' /></div>\n\t\t<tr><th><label for=\"id_name\">Name:</label></th><td><ul class=\"errorlist\"><li>This field is required.</li></ul><input id=\"id_name\" type=\"text\" name=\"name\" maxlength=\"200\" /></td></tr>\n<tr><th><label for=\"id_author\">Author:</label></th><td><ul class=\"errorlist\"><li>This field is required.</li></ul><input id=\"id_author\" type=\"text\" name=\"author\" maxlength=\"100\" /></td></tr>\n<tr><th><label for=\"id_picture\">Picture:</label></th><td><input type=\"file\" name=\"picture\" id=\"id_picture\" /></td></tr>\n<tr><th><label for=\"id_ingredients\">Ingredients:</label></th><td><ul class=\"errorlist\"><li>This field cannot be null.</li></ul><textarea id=\"id_ingredients\" rows=\"10\" cols=\"40\" name=\"ingredients\"></textarea></td></tr>\n<tr><th><label for=\"id_steps\">Steps:</label></th><td><ul class=\"errorlist\"><li>This field cannot be null.</li></ul><textarea id=\"id_steps\" rows=\"10\" cols=\"40\" name=\"steps\"></textarea></td></tr>\n<tr><th><label for=\"id_prep_time\">Prep time:</label></th><td><ul class=\"errorlist\"><li>This field is required.</li></ul><input type=\"text\" name=\"prep_time\" id=\"id_prep_time\" /></td></tr>\n<tr><th><label for=\"id_type\">Type:</label></th><td><ul class=\"errorlist\"><li>This field is required.</li></ul><select name=\"type\" id=\"id_type\">\n<option value=\"\" selected=\"selected\">---------</option>\n<option value=\"SW\">Sandwich</option>\n<option value=\"AP\">Appetizers</option>\n<option value=\"SD\">Sauces and Dressings</option>\n<option value=\"SS\">Soups and Salads</option>\n<option value=\"VG\">Vegetables</option>\n<option value=\"RG\">Rice, Grains and Beans</option>\n<option value=\"PA\">Pasta</option>\n<option value=\"BR\">Breakfast</option>\n<option value=\"MT\">Meat</option>\n<option value=\"SF\">Seafood</option>\n<option value=\"BP\">Bread and Pizza</option>\n<option value=\"DT\">Desserts</option>\n</select><input type=\"hidden\" name=\"reset_recipe\" id=\"id_reset_recipe\" /></td></tr>\n\t</table>\n\t<p><input type=\"submit\" value=\"Submit\"></p>\n</form>\n</body>"}
here is my ajax code:
<script type="text/javascript">
$(document).ready(function(){
var form = $('form#createrecipeform');
form.submit(function(e) {
e.preventDefault();
console.log('ajax form submission function called successfully.');
//form = $(this);
console.log(form)
var serialized_form = form.serialize();
$.ajax({ type: "POST", 
url: $(this).attr('action'),
data: serialized_form, 
success: (function(data) { 
console.log('ajax success function called successfully.');
data = $.parseJSON(data);
if (data.success) {
console.log('success');
} else {
console.log('failure');
var newForm = data.form;
form.replaceWith(newForm);
}
})
});
return false;
});
});
</script>
here is the view: (createrecipe is the action of the form and account is the page that is loading the ajax)
def createrecipe(request):
print "entering createrecipeview"
if request.method == 'POST':
print "form is a post"
form = RecipeForm(request.POST)
print form.errors
if form.is_valid():
print "form is valid"
form = RecipeForm(initial = {'original_cookbook' : request.user.cookbooks.all()[0]})
form = form.save()
t = loader.get_template('cookbook/create_form.html')
c = RequestContext(request, {
'form': form,
})
data = {
'replace': True,
'form': t.render(c),
'success': True,
}
json = simplejson.dumps(data)
return HttpResponse(json, mimetype='text/plain')
else:
print "form is invalid"
form = RecipeForm(request.POST)
t = loader.get_template('cookbook/create_form.html')
c = RequestContext(request, {
'form':form,
})
data ={
'form': t.render(c),
'success': False,
}
json = simplejson.dumps(data)
return HttpResponse(json, mimetype='text/plain')
def account(request):
user = request.user
if request.user.is_authenticated():
cookbooks = user.cookbooks
if cookbooks.all().exists():
cookbook = cookbooks.all()[0]
form = RecipeForm(initial = {'original_cookbook' : request.user.cookbooks.all()[0]})
recipe_list = cookbook.recipes.all()
else:
raise Http404
else:
return HttpResponseRedirect('/accounts/login')
t = loader.get_template('cookbook/account.html')
c = RequestContext(request, {
'form': form,
'recipe_list': recipe_list
})
return HttpResponse(t.render(c))
here is the create_form.html template:
<head>
</head>
<body>
<form action="{% url cookbook.views.createrecipe %}" method="POST" name="recipeform" id="createrecipeform">
<table>
{% csrf_token %}
{{ form.as_table }}
</table>
<p><input type="submit" value="Submit"></p>
</form>
</body>
and here is the account template that includes the create_form template:
{% extends "cookbook/base.html" %}
{% load pagination_tags %}
{% load comments %}
<h1>{{ user }}'s Cookbook</h1>
<ul>
{% block nav-cookbooks %}
<li><a class="nav-inactive" href="/cookbooks/">Cookbooks</a></li>
{% endblock %}
{% block nav-account %}
<li><a class="nav-active" href="/account/">My Cookbook</a></li>
{% endblock %}
</ul>
{% block content %}
{% autopaginate recipe_list 6 %}
<div id="recipe_cont">
{% for recipe in recipe_list %}
<div class="recipe">
<div class="button">
<img src="{{ STATIC_URL }}chicknbraw.jpg" alt="" height="70" width="70" style="display:inline;" />
<h4>{{ recipe.name }}</h4>
</div>
<h5>{{ recipe.author }}</h5>
<h5>Prep Time: {{ recipe.prep_time }} minutes</h5>
<h6>Add Recipe
Remove Recipe</h6>
</div>
{% endfor %}
</div>
<div id="popupContact" class="popup">
<a id="popupContactClose" style="cursor:pointer;float:right;">x</a>
<p id="contactArea">
<h1 style="text-align:center">Create New Recipe</h1>
{% include 'cookbook/create_form.html' %}
</p>
</div>
<div id="backgroundPopup">
</div>
<div id="col2-footer">
{% paginate %}
<p id="recipe_order_text"> order by: abc|date
</div>
{% endblock %}
{% block footer %}
<a class="create" style="cursor:pointer" >Create New Recipe</a>
{% endblock %}
sorry for putting so much code but it all seems to rely upon another piece of code so I figured all relevant code would be helpful
thanks for any help you can give me
katie
In your javascript, you're hijacking the form so that it submits via ajax, but then you're calling replaceWith on the form, so your hijacked form gets obliterated and is replaced with a new, non-hijacked form. To solve this you can either
1) Only replace the content of the form - this should work since you're only attaching events to the form itself and not its child elements
2) Write your js as a function which you can call firstly on the initial form, and subsequently on any new forms loaded via ajax.
UPDATE: for example,
<script type="text/javascript">
$(document).ready(function(){
function hijack() {
var form = $('form#createrecipeform');
form.submit(function(e) {
e.preventDefault();
console.log('ajax form submission function called successfully.');
//form = $(this);
console.log(form)
var serialized_form = form.serialize();
$.ajax({ type: "POST",
url: $(this).attr('action'),
data: serialized_form,
success: (function(data) {
console.log('ajax success function called successfully.');
data = $.parseJSON(data);
if (data.success) {
console.log('success');
} else {
console.log('failure');
var newForm = data.form;
form.replaceWith(newForm);
hijack();
}
})
});
return false;
});
};
hijack();
});
</script>

django object_list not updated after object create form submit via ajax

I am working on a django project in which one of the templates has a form in a popup div that submits a form to create a new object.
As of now the ajax function submits the form successfully and adds the recipe to the admin database but for some reason it doesn't appear in the object_list that I pass into my template.
even if i refresh the page the newly added object isn't added to the template and the object created is stuck in limbo on the admin page.
CODE
ajax submit function:
<script type="text/javascript">
$(document).ready(function(){
function hijack() {
var form = $('form#createrecipeform');
form.submit(function(e) {
e.preventDefault();
console.log('ajax form submission function called successfully.');
//form = $(this);
console.log(form)
var serialized_form = form.serialize();
$.ajax({ type: "POST",
url: $(this).attr('action'),
data: serialized_form,
success: (function(data) {
console.log('ajax success function called successfully.');
data = $.parseJSON(data);
if (data.success) {
console.log('success');
alert('recipe added');
} else {
console.log('failure');
var newForm = data.form;
form.replaceWith(newForm);
hijack();
}
})
});
return false;
});
};
hijack();
});
</script>
related views:
** //this is the page the has the popup div to load the form**
def account(request):
user = request.user
if request.user.is_authenticated():
cookbooks = user.cookbooks
if cookbooks.all().exists():
cookbook = cookbooks.all()[0]
form = RecipeForm(initial = {'original_cookbook' : request.user.cookbooks.all()[0]})
recipe_list = cookbook.recipes.all()
else:
raise Http404
else:
return HttpResponseRedirect('/accounts/login')
t = loader.get_template('cookbook/account.html')
c = RequestContext(request, {
'form': form,
'recipe_list': recipe_list
})
return HttpResponse(t.render(c))
**//this is the page that handles the ajax and is the action of the form**
def createrecipe(request):
if request.method == 'POST':
form = RecipeForm(request.POST)
if form.is_valid():
form = form.save(commit=False)
form.original_cookbook = request.user.cookbooks.all()[0]
form.save()
t = loader.get_template('cookbook/create_form.html')
c = RequestContext(request, {
'form': form,
})
data = {
'replace': True,
'form': t.render(c),
'success': True,
}
json = simplejson.dumps(data)
return HttpResponse(json, mimetype='text/plain')
else:
form = RecipeForm(request.POST)
t = loader.get_template('cookbook/create_form.html')
c = RequestContext(request, {
'form':form,
})
data ={
'form': t.render(c),
'success': False,
}
json = simplejson.dumps(data)
return HttpResponse(json, mimetype='text/plain')
templates:
{% block content %}
<div id="recipe_cont">
{% for recipe in recipe_list %}// here is where add each recipe in the recipe list
<div class="recipe">
<div id="recipebutton{{ forloop.counter }}" class="button">
</div>
</div>
{% endfor %}
</div>
<div id="popupContact" class="popup">
<a id="popupContactClose" style="cursor:pointer;float:right;">x</a>
<p id="contactArea">
<div id="create_form_span">
{% include 'cookbook/create_form.html' %} // here is the form
</div>
</p>
</div>
</div>
{% endblock %}
//template for the form that is included
<head>
</head>
<body>
<form action="{% url cookbook.views.createrecipe %}" method="POST" name="recipeform" id="createrecipeform">
<table>
{% csrf_token %}
{{ form.as_table }}
</table>
<p><input type="submit" value="Submit"></p>
</form>
</body>

Resources