I am new to Django.
My app allows a user to create a project by providing a title and a body content, delete it and update it.
Now, I am creating and edit/update view for my app but it is not showing up in my html page.
urls.py
from django.urls import path, include
from . import views
urlpatterns = [
path('allprojects', views.allprojects, name='allprojects'),
path('createproject', views.createproject, name='createproject'),
path('<int:project_id>', views.projectdetail, name='projectdetail'),
path('<int:project_id>/editproject', views.editproject, name='editproject'),
]
projects/views.py
#login_required
def editproject(request, project_id):
if request.method == 'POST':
if request.POST['title'] and request.POST['content']:
project = get_object_or_404(Project, pk=project_id)
project.title = request.POST['title']
project.content = request.POST['content']
project.developer = request.user
project.save()
return redirect('/projects/' + str(project.id))
else:
return render(request, 'projects/editproject.html', {'error':'All fields are required.'})
else:
return render(request, 'projects/allprojects.html')
projects/templates/projects/editproject.html
{% extends 'base.html' %}
{% block title %}Edit Project{% endblock %}
{% block content %}
<div class="container">
<div class="row">
<div class="mt-4 offset-md-3 col-md-6">
<h2>Create a new project</h2>
<form method="post">
{% csrf_token %}
<div class="form-group">
<label for="exampleFormControlTextarea1">Title of the project</label>
<textarea class="form-control" id="exampleFormControlTextarea1" rows="1" name="title"></textarea>
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Brief description of this project</label>
<textarea class="form-control" id="exampleFormControlTextarea1" rows="5" name="content"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
{% endblock %}
PROBLEM
When I go to a urls such as http://localhost:8000/projects/2/editproject there is not the update form I want, the page exists but it contains nothing
You have to pass the project = get_object_or_404(Project, pk=project_id) in the dictionary in order to get the value in template.
Change your view like this:
#login_required
def editproject(request, project_id):
project = get_object_or_404(Project, pk=project_id)
if request.method == 'POST':
if request.POST['title'] and request.POST['content']:
project.title = request.POST['title']
project.content = request.POST['content']
project.developer = request.user
project.save()
return redirect('/projects/',project.project_id)
return render(request, 'projects/editproject.html', {'error':'All fields are required.','project':project})
And in the template you can get value like this :
Also in your template change method=put to method=post
and also you need to provide action if you want to update.
<div class="form-group">
<label for="exampleFormControlTextarea1">Title of the project</label>
<textarea class="form-control" id="exampleFormControlTextarea1" rows="1" name="title">
{{project.title}}
</textarea>
</div>
Related
Maybe it might be an oversight but I do not know the point where I am getting it wrong.
My form is rendered correctly but it keeps failing without errors.
forms.py
from crispy_forms.helper import FormHelper
from django import forms
from django.utils.translation import ugettext as _
class BeneficiaryForm(forms.Form):
"""Add Beneficiary template form"""
# Form fields
account_currency = forms.ModelChoiceField(queryset=Currency.objects.all(), empty_label=_('Select account currency'))
bank_account_type = forms.CharField(max_length=50, required=False)
email = forms.CharField(max_length=150, required=False, help_text=_("We'll notify them when a transfer is made"))
name = forms.CharField(max_length=50, required=False)
swift_code = forms.CharField(max_length=11, required=False,
widget=forms.TextInput(attrs={'placeholder': 'MSBCCNBJ001'}))
iban = forms.CharField(max_length=34)
def __init__(self, *args, **kwargs):
super(BeneficiaryForm, self).__init__()
self.helper = FormHelper()
self.helper.form_show_labels = False
views.py
def beneficiaries(request):
"""View function for viewing Beneficiaries and adding a Beneficiary instance"""
if request.method == 'POST':
form = BeneficiaryForm(request.POST)
if form.is_valid():
print("Form is valid")
print(request.POST['bank_account_type'])
print(request.POST['email'])
print(request.POST['name'])
print(request.POST['iban'])
print(request.POST['swift_code'])
print("Form is invalid")
print(form.errors)
form = BeneficiaryForm()
context = {
'form': form
}
return render(request, 'dashboard/beneficiaries.html', context)
and in my rendered form. I have this block to show errors and nothing shows up
HTML
<form action="{% url 'beneficiary_index' %}" method="post">
{% csrf_token %}
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
{% if field != '__all__' %}
<strong>{{ field.label }}:</strong>
{% endif %}
{{ error|escape}}
</div>
{% endfor %}
{% endfor %}
{% endif %}
<div class="form-group">
<div class="form-label-group">
<label class="form-label" for="default-01">{% trans "Account currency" %}</label>'
</div>
{{ form.account_currency | as_crispy_field }}
</div>
<div class="form-group">
<div class="form-label-group">
<label class="form-label" for="default-01">{% trans "Bank Account type" %}</label>
</div>
{{ form.bank_account_type | as_crispy_field }}
</div>
<div class="form-group">
<div class="form-label-group">
<label class="form-label" for="default-01">Their email(optional)</label>
</div>
{{ form.email | as_crispy_field }}
</div>
<div class="form-group">
<div class="form-label-group">
<label class="form-label" for="default-01">Full name of account holder</label>
</div>
{{ form.name | as_crispy_field }}
</div>
<h6>{% trans "Recipient Bank Information" %}</h6>
<hr>
<div class="form-group">
<div class="form-label-group">
<label class="form-label" for="default-01">Swift code</label>
</div>
{{ form.swift_code | as_crispy_field }}
</div>
<div class="form-group">
<div class="form-label-group">
<label class="form-label" for="default-01">IBAN</label>
</div>
{{ form.iban | as_crispy_field }}
</div>
<div class="form-group">
<button class="btn btn-lg btn-primary btn-block">{% trans 'Add Beneficiary' %}</button>
</div>
</form>
This is the Html to the form. I have just tried all the suggestions and still without the errors.
Form is Invalid is the only thing printed on screen without the form.errors
You need to create the GET request empty form in the else block or return the request in the POST block.
You are re-creating an empty form before returning the response.
def beneficiaries(request):
"""View function for viewing Beneficiaries and adding a Beneficiary instance"""
if request.method == 'POST':
form = BeneficiaryForm(request.POST)
if form.is_valid():
print("Form is valid")
print(request.POST['bank_account_type'])
print(request.POST['email'])
print(request.POST['name'])
print(request.POST['iban'])
print(request.POST['swift_code'])
# do other stuff like saving to DB
# then redirect
else:
print("Form is invalid")
print(form.errors)
elif request.method == 'GET':
form = BeneficiaryForm()
else:
# maybe return 404
pass
context = {
'form': form
}
return render(request, 'dashboard/beneficiaries.html', context)
Or maybe you can try Class Based Views, to avoid the if-else block for GET and POST requests.
Try adding this to the place you want the error to appear (In the HTML file)
Better if you use it inside the tags.
{% if form.errors %}
<p>Form is invalid</p>
{% endif %}
I Hope this answers the question.
I have a form like so:
{% extends "interface/base.html" %}
{% load subscribertags %}
{% block title %}{{ object }}{% endblock %}
{% block center %}
<div class="page-header">
<h1>Редактирование меню <small>{% operator_name object.operator %}: {{ object }} ({{ object.slug }})</small></h1>
</div>
<!-- Modal -->
<div class="modal fade" id="itemModal" tabindex="-1" role="dialog" aria-labelledby="itemModalTitle" aria-hidden="true">
<form method="post">{% csrf_token %}
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="itemModalTitle">Добавить пункт</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="item_name">Действие</label>
<select class="form-control" name="action">
<option value="">----------</option>
{% for value, action in actions %}
<option value="{{ value }}">{{ action }}</option>
{% endfor %}
</select>
</div>
<div class="checkbox">
<label>
<input id='is_hidden' type="checkbox" name='is_hidden' > Спрятать
</label>
</div>
<div class="checkbox">
<label>
<input id='allow_back' type="checkbox" name='allow_back' > Пункт назад
</label>
</div>
<div class="form-group">
<label for="label">Метка</label>
<input type="text" class="form-control" id="label" placeholder="Название метки" name='slug'>
</div>
<div class="form-group">
<label for="params">Доп параметры</label>
<textarea type="text" class="form-control" id="params" placeholder="Дополнительные параметры" name='params'></textarea>
</div>
{% for code, language in languages %}
<div class="form-group">
<h5>{{ language }}</h5>
{% if code = object.default_language %}
<label for="text">Текст</label>
<input type="text" class="form-control" id="text" placeholder="Текст" name='text'>
<label for="result_text">Текст результата</label>
<input type="text" class="form-control" id="result_text" placeholder="Текст результата" name='result_text'>
{% else %}
<label for="text-{{ code }}">Текст</label>
<input type="text" class="form-control" id="text-{{ code }}" placeholder="Текст" name='text-{{ code }}'>
<label for="result_text-{{ code }}">Текст результата</label>
<input type="text" class="form-control" id="result_text-{{ code }}" placeholder="Текст результата" name='result_text-{{ code }}'>
{% endif %}
</div>
{% endfor %}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Отмена</button>
<button type="subbmit" class="btn btn-primary">Сохранить</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</form>
</div><!-- /.modal -->
<div class="tree">
{% if object.item_set.count %}
<ul>
{% with object.item_set.all.0 as item %}
{% include "interactive/interface/menu_item.html" %}
{% endwith %}
</ul>
{% endif %}
</div>
{% endblock %}
SECOND PART:
{% load interactivetags %}
<li class="element-interactive-item{% if not item.is_visible %} i-hidden{% endif %}">
<span data-toggle="tooltip" title="{{ item.params }}" class='name'><i class="glyphicon glyphicon-{% item_icon item %}"></i> ({{ item.id }}) {{ item }} {% if item.slug %}({{ item.slug }}){% endif %}
<a class='tool item-tool' data-values='{% item_to_json item %}' data-toggle="modal" data-target="#itemModal" data-label="Редактировать: {{ item }}" href="#" data-href="{% url "interactive.views.item_update" pk=item.pk %}"><i class="glyphicon glyphicon-edit"></i></a>
<a class='tool item-tool' data-toggle="modal" data-target="#itemModal" data-label="Добавить пункт" href="#" <data-href="{% url "interactive.views.item_create" pk=object.pk parent_pk=item.pk %}"><i class="glyphicon glyphicon-plus"></i></a>
{% if item.is_leaf_node and not item.is_root_node%}
<a class='tool confirm' href="{% url "interactive.views.item_delete" pk=item.pk %}"><i class="glyphicon glyphicon-remove"></i></a>
{% endif %}
<a class='tool confirm' href="{% url "interactive.views.item_up" pk=item.pk %}"><i class="glyphicon glyphicon-arrow-up"></i></a>
<a class='tool confirm' href="{% url "interactive.views.item_down" pk=item.pk %}"><i class="glyphicon glyphicon-arrow-down"></i></a>
</span>
<ul>
{% for item in item.get_children %}
{% include "interactive/interface/menu_item.html" %}
{% endfor %}
</ul>
</li>
When I hit the Save/Сохранить button data isn't updated in the database for this form and I get
"POST /interactive/1/ HTTP/1.1" 405 0
Code that handles the request:
# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.contrib.contenttypes.models import ContentType
from django.http import HttpResponseRedirect
from interactive.models import Menu, Item
from interactive.forms import UpdateItemForm
from interface.views import InterfaceMixin
from interactive.processors import ProcessorManager
from subscribers.models import Subscriber
from languages.models import Translate
class MenuList(InterfaceMixin, ListView):
model = Menu
name = u'Интерактивные меню'
index = MenuList.as_interface_view(template_name='interactive/interface/index.html')
class MenuItem(InterfaceMixin, DetailView):
""" Редактирование интерактивного меню """
model = Menu
def get_context_data(self, **kwargs):
kwargs['actions'] = ProcessorManager.actions()
kwargs['languages'] = Subscriber.LANGUAGES
return super(MenuItem, self).get_context_data(**kwargs)
menu = MenuItem.as_interface_view(item=MenuList, template_name='interactive/interface/item.html')
class ItemMixin:
#classmethod
def update_language(cls, attribute, text, context):
if text:
o, _ = Translate.objects.get_or_create(attribute=attribute, **context)
o.text = text
o.save()
class CreateItemView(ItemMixin, InterfaceMixin, CreateView):
menu = None
parent = None
model = Item
form_class = UpdateItemForm
auth = False
def get_success_url(self):
return reverse("interactive.views.menu", kwargs={'pk': self.menu.pk})
def post(self, request, *args, **kwargs):
pk = kwargs.get('pk')
parent_pk = kwargs.get('parent_pk')
self.menu = Menu.objects.get(pk=pk)
self.parent = Item.objects.get(pk=parent_pk)
return super(CreateItemView, self).post(request, *args, **kwargs)
def form_valid(self, form):
form.instance.menu = self.menu
form.instance.insert_at(self.parent, position='last-child')
form.instance.save()
ct = ContentType.objects.get_for_model(form.instance)
for code, _ in Subscriber.LANGUAGES:
text = self.request.POST.get('text-%s' % code)
result_text = self.request.POST.get('result_text-%s' % code)
context = dict(content_type=ct, object_id=form.instance.pk, language=code, operator=self.menu.operator)
self.update_language('text', text, context)
self.update_language('result_text', result_text, context)
return super(CreateItemView, self).form_valid(form)
def form_invalid(self, form):
return super(CreateItemView, self).form_valid(form)
item_create = CreateItemView.as_view()
class UpdateItemView(ItemMixin, InterfaceMixin, UpdateView):
""" Изменение пункта меню """
model = Item
form_class = UpdateItemForm
auth = False
def get_success_url(self):
return reverse("interactive.views.menu", kwargs={'pk': self.object.menu.pk})
def form_valid(self, form):
ct = ContentType.objects.get_for_model(self.object)
for code, _ in Subscriber.LANGUAGES:
text = self.request.POST.get('text-%s' % code)
result_text = self.request.POST.get('result_text-%s' % code)
context = dict(content_type=ct, object_id=self.object.pk, language=code)
self.update_language('text', text, context)
self.update_language('result_text', result_text, context)
return super(UpdateItemView, self).form_valid(form)
def form_invalid(self, form):
return super(UpdateItemView, self).form_valid(form)
item_update = UpdateItemView.as_view()
class DeleteItemView(InterfaceMixin, DeleteView):
model = Item
auth = False
def get_success_url(self):
return reverse("interactive.views.menu", kwargs={'pk': self.object.menu.pk})
def get(self, request, *args, **kwargs):
return self.delete(request, *args, **kwargs)
item_delete = DeleteItemView.as_view()
class UpDownItemVew(DetailView):
action = None
model = Item
auth = False
def get(self, request, *args, **kwargs):
item = self.get_object()
if self.action == 'left':
other = item.get_previous_sibling()
else:
other = item.get_next_sibling()
item.move_to(other, position=self.action)
return HttpResponseRedirect(reverse("interactive.views.menu", kwargs={'pk': item.menu.pk}))
item_up = UpDownItemVew.as_view(action='left')
item_down = UpDownItemVew.as_view(action='right')
URL patterns:
urlpatterns = patterns(
'interactive.views',
(r'^(?P<pk>\d+)/(?P<parent_pk>\d+)/additem/$', "item_create"),
(r'^item/(?P<pk>\d+)/delete/$', "item_delete"),
(r'^item/(?P<pk>\d+)/up/$', "item_up"),
(r'^item/(?P<pk>\d+)/down/$', "item_down"),
(r'^item/(?P<pk>\d+)/$', "item_update"),
(r'^(?P<pk>\d+)/$', "menu"),
(r'^$', 'index'),
)
This code perfectly work on a production server, but wasn't uploaded by me and uses nginx as http server.
I am running it on local server using python manage.py runserver
I have created a template design for signup page using Flat UI. Now i want to use Django registration to register a user. I have goggled various resources but they are very complex and using Django inbuilt form to create a form.
I need simple steps that i can follow
signup.html(home/django/mysite/templates)
{% extends "base.html" %}
{% block title %}Signup page{% endblock %}
{% block content %}
<div class="container" style="width:500px">
<h3 style="margin-top:100px">Sign Up</h3>
<hr>
<div class="login-form">
<form action="" method="post">
<div class="control-group span3" style="width:400px" >
<input type="text" value="" placeholder="Enter your name" id="name" style="width:400px;padding-bottom:15px;margin-bottom:10px" >
<i class="input-icon fui-user" for="login-name"></i>
</div>
<div class="control-group span3" style="width:400px" >
<input type="text" value="" placeholder="Your E-mail" id="email" style="width:400px;padding-bottom:15px;margin-bottom:10px" >
<i class="input-icon fui-mail" for="login-name"></i>
</div>
<div class="control-group span3" style="width:400px">
<input type="password" value="" placeholder="Password" id="pass" style="width:400px;padding-bottom:15px;margin-bottom:10px">
<i class="input-icon fui-lock" for="login-pass"></i>
</div>
<div class="control-group span3" style="width:400px">
<input type="password" value="" placeholder="Confirm Password" id="login-pass" style="width:400px;padding-bottom:15px;margin-bottom:10px">
<i class="input-icon fui-lock" for="login-pass"></i>
</div>
<div style="text-align:center">
<a class="btn btn-hg btn-primary btn-wide" href="#">Sign Up</a>
<!--<a class="login-link" href="#">Lost your password ?</a> -->
</div>
</form>
</div><!-- /login-form -->
</div> <!-- /container -->
{% endblock content %}
views.py
def signup(request):
return render(request, 'signup.html')
urls.py
urlpatterns = patterns('',
url(r'^signup/$', views.signup),)
What i should write in views.py or models.py to register a user using django registration.
You can use django registration together with custom html/css through django forms. Here are the steps:
Provided you have included relevant imports, your urls.py looks fine so no changes needed.
Create a forms.py file in the same folder as your views.py and add the following code into forms.py:
from django import forms
class Signup_form(forms.Form):
# CSS styles should not be inline. i've moved your style contents under a 'form-control' class
name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'type':'text', 'placeholder':'Enter your name', 'id':'name', 'name':'name', 'class' : 'form-control'}))
email = forms.EmailField(label="Email address", widget=forms.TextInput(attrs={'type':'text', 'placeholder':'Your E-mail', 'id':'email', 'name':'email', 'class' : 'form-control'}))
pass1 = forms.CharField(max_length = 20, widget=forms.TextInput(attrs={'type':'password', 'placeholder':'Password', 'id':'pass1', 'name':'pass1', 'class' : 'form-control'}))
pass2 = forms.CharField(max_length = 20, widget=forms.TextInput(attrs={'type':'password', 'placeholder':'Confirm Password', 'id':'pass2', 'name':'pass2', 'class' : 'form-control'}))
3.In your views.py file, you have to link pass the Signup_form to your views layer. Change your views.py file to the following:
from forms import Signup_form
def signup(request):
form = Signup_form()
name = request.POST.get('name','')
email = request.POST.get('email', '')
pass1 = request.POST.get('pass1', '')
pass2 = request.POST.get('pass2', '')
# Do some validations here
user = User.objects.create_user(name, email, pass2)
if user:
user.save()
return render(request, 'signup.html', {'form': form})
4.Now that you have passed your Signup_form object in views layer, you can use django template tags to display them in your signup.html page. Here's how your signup.html could look like:
{% extends "base.html" %}
<link rel="stylesheet" href="{% static 'css/custom.css' %}">
{% block title %}Signup page{% endblock %}
{% block content %}
<div class="container" style="width:500px">
<h3 style="margin-top:100px">Sign Up</h3>
<hr>
<div class="login-form">
<form action="" method="post"> {% csrf_token %}
<div class="control-group span3" style="width:400px" >
{{ form.name.errors }}
{{ form.name }}
<i class="input-icon fui-user" for="login-name"></i>
</div>
<div class="control-group span3" style="width:400px" >
{{ form.email.errors }}
{{ form.email }}
<i class="input-icon fui-mail" for="login-name"></i>
</div>
<div class="control-group span3" style="width:400px">
{{ form.pass1.errors }}
{{ forms.pass2 }}
<i class="input-icon fui-lock" for="login-pass"></i>
</div>
<div class="control-group span3" style="width:400px">
{{ form.pass2.errors }}
{{ forms.pass2 }}
<i class="input-icon fui-lock" for="login-pass"></i>
</div>
<div style="text-align:center">
<input type="submit" class="btn btn-hg btn-primary btn-wide" value="Sign Up">
<!--<a class="login-link" href="#">Lost your password ?</a> -->
</div>
</form>
</div><!-- /login-form -->
</div> <!-- /container -->
{% endblock content %}
5.Since i have earlier moved your CSS styles(in point 2) into a 'form-control' class, now we will place it back by adding your styles in a external custom.css file. Create a custom.css file in the directory static/css/custom.css and add the following into it:
.form-control {
width:400px;
padding-bottom:15px;
margin-bottom:10px;
}
In your Views.py
from django.contrib.auth.models import User
def signup(request):
username = request.POST.get("name","")
password = request.POST.get("pass","")
login_pass = request.POST.get("login-pass","")
email = request.POST.get("email","")
if username != "" or password != "" or login_pass != "":
#do some validations
user = User.objects.create_user(username, email, password)
if user:
user.is_active = True
user.save()
return render(request, 'signup.html')
Above code will register a new user into system
If you would have use Django forms then all the validations will be done by Django.
Note: Please add name attribute to your HTML fields required for getting vaLues in request.POST. Also point your HTMl form action to "signup" view
I'd like to show last_item in a Twitter-Bootstrap modal after django form submission, however I don't know how to handle the modal. I tried the form button suggested in documentation, but it doesn't process the form data. What do I have to do?
<button data-toggle="modal" data-target="#myModal2">Submit</button>
views.py
def main(request):
if request.method == 'POST':
form = MyModelForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
request.session['name'] = name
mm = MyModel.objects.create(name=name)
mm.save()
return HttpResponseRedirect('/') # Redirect after POST
else:
form = MyModelForm()
args = {}
args['last_item'] = MyModel.objects.all().order_by('pk').reverse()[0]
args['form'] = form
return render(request, 'form.html', args)
form.html
{% extends "base.html" %}
{% block content %}
<form method="POST" id="" action="">
{% csrf_token %}
{{ form.as_p }}
<button>Submit</button>
</form>
<div class="modal" id="myModal2" tabindex="-1" role="dialog"
aria-labelledby="myModal2Label" aria-hidden="true" style="display: none">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModal2Label">Modal header</h3>
</div>
<div class="modal-body">
<p>Last item: {{ last_item }}</p>
</div>
</div>
{% endblock %}
{% block scripts %}
{% endblock %}
It seems like bootstrap calls event.preventDefault() on click, which prevents the form from being submited.
You should bind your own event on this button and close the modal programaticaly.
It could look like:
$('form').submit(function() {
$('#myModal2').modal('hide');
})
I did not test this code but it should be a good start.
I'm trying to run django forms with Twitter-Bootstrap modals. I'd like to know what should I do to return to / after form submission. My views and templates are below.
url.py
urlpatterns = patterns('myapp.views',
url(r'^$', 'main'),
url(r'^add/', 'form_add'),
)
views.py
def main(request):
if request.method == 'POST':
form = MyModelForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
request.session['name'] = name
mm = MyModel.objects.create(name=name)
mm.save()
return HttpResponseRedirect('/add') # Redirect after POST
else:
form = MyModelForm()
args = {}
args['last_item'] = MyModel.objects.all().order_by('pk').reverse()[0]
args['form'] = form
return render(request, 'form.html', args)
def form_add(request):
args = {}
name = request.session['name']
return render(request, 'add.html', args)
form.html
{% extends "base.html" %}
{% block content %}
<button type="button" data-toggle="modal"
data-target="#myModal1">Launch modal</button>
<div class="modal" id="myModal1" tabindex="-1" role="dialog"
aria-labelledby="myModal1Label" aria-hidden="true" style="display: none">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModal1Label">Modal header</h3>
</div>
<div class="modal-body">
<form method="POST" id="" action="">
{% csrf_token %}
{{ form.as_p }}
<button>Submit</button>
</form>
</div>
</div>
<p>Last item: {{ last_item }}</p>
{% endblock %}
{% block scripts %}
{% endblock %}
Comment converted to answer.
HttpResponseRedirect('/') instead of '/add'?