Simple Django form in Twitter-Bootstrap modal

妖精的绣舞 提交于 2019-12-11 18:28:58

问题


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 %}

回答1:


Comment converted to answer.

HttpResponseRedirect('/') instead of '/add'?



来源:https://stackoverflow.com/questions/12647949/simple-django-form-in-twitter-bootstrap-modal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!