Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 29th, 2012  |  syntax: None  |  size: 9.94 KB  |  hits: 10  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. add text field on button click and pack into jsonfield with django
  2. def createrecipe(request):
  3.         if request.method == 'POST':
  4.             form = RecipeForm(request.POST)
  5.             if form.is_valid():
  6.                 form = RecipeForm(initial = {'original_cookbook' : request.user.cookbooks.all()[0]})
  7.                 form = form.save()
  8.  
  9.                 t = loader.get_template('cookbook/create_form.html')
  10.                 c = RequestContext(request, {
  11.                 'form': form,
  12.                 })
  13.  
  14.                 data = {
  15.                 'replace': True,
  16.                 'form': t.render(c),
  17.                 'success': True,
  18.                 }
  19.  
  20.                 json = simplejson.dumps(data)
  21.                 return HttpResponse(json, mimetype='text/plain')
  22.             else:
  23.                 form = RecipeForm(request.POST)
  24.                 t = loader.get_template('cookbook/create_form.html')
  25.                 c = RequestContext(request, {
  26.                     'form':form,
  27.                 })
  28.  
  29.                 data ={
  30.                     'form': t.render(c),
  31.                     'success': False,
  32.                 }
  33.  
  34.                 json = simplejson.dumps(data)
  35.                 return HttpResponse(json, mimetype='text/plain')
  36.        
  37. class Recipe(models.Model):
  38.     def __unicode__(self):
  39.         return self.name
  40.     original_cookbook = models.ForeignKey(Cookbook)
  41.     name = models.CharField(max_length=200)
  42.     author = models.CharField(max_length= 100)
  43.     picture = models.ImageField(upload_to = 'Downloads', blank=True)
  44.     pub_date = models.DateTimeField('date published', auto_now_add=True, blank=True)
  45.     type = models.CharField(max_length = 2, choices=TYPE_CHOICES)
  46.     ingredients = JSONField()
  47.     steps = JSONField()
  48.     prep_time = models.IntegerField()
  49.        
  50. def account(request):
  51.         user = request.user
  52.         if request.user.is_authenticated():
  53.  
  54.             cookbooks = user.cookbooks
  55.             if cookbooks.all().exists():
  56.                 cookbook = cookbooks.all()[0]
  57.                 form = RecipeForm(initial = {'original_cookbook' : request.user.cookbooks.all()[0]})
  58.                 recipe_list = cookbook.recipes.all()
  59.             else:
  60.                 raise Http404
  61.         else:
  62.             return HttpResponseRedirect('/accounts/login')
  63.         t = loader.get_template('cookbook/account.html')
  64.         c = RequestContext(request, {
  65.             'form': form,
  66.             'recipe_list': recipe_list
  67.         })
  68.         return HttpResponse(t.render(c))
  69.        
  70. <body>
  71. <form action="{% url cookbook.views.createrecipe %}" method="POST" name="recipeform" id="createrecipeform">
  72.     <table>
  73.         {% csrf_token %}
  74.         {{ form.as_table }}
  75.     </table>
  76.     <p><input type="submit" value="Submit"></p>
  77. </form>
  78.  
  79. <form class="task-form" action="." method="POST">
  80.     <button class=".task-add-button" value="Add Task">
  81.     {% csrf_token %}
  82.     {{ TaskFormSet.as_p }}
  83. </form>
  84. </body>
  85.        
  86. {% extends "cookbook/base.html" %}
  87. {% load pagination_tags %}
  88. {% load comments %}
  89.  
  90.  
  91.     <h1>{{ user }}'s Cookbook</h1>
  92.  
  93. <ul>
  94. {% block nav-cookbooks %}
  95. <li><a class="nav-inactive" href="/cookbooks/">Cookbooks</a></li>
  96. {% endblock %}
  97. {% block nav-account %}
  98. <li><a class="nav-active" href="/account/">My Cookbook</a></li>
  99. {% endblock %}
  100. </ul>
  101. {% block content %}
  102. {% autopaginate recipe_list 6 %}
  103.     <div id="recipe_cont">
  104.             {% for recipe in recipe_list %}
  105.         <div class="recipe">
  106.             <div class="button">    
  107.             <a href="{% url cookbook.views.userrecipe recipe.id %}" style="display: none;"></a>  
  108.             <img src="{{ STATIC_URL }}chicknbraw.jpg" alt="" height="70" width="70" style="display:inline;" />
  109.             <h4>{{ recipe.name }}</h4>
  110.              </div>
  111.             <h5>{{ recipe.author }}</h5>
  112.             <h5>Prep Time: {{ recipe.prep_time }} minutes</h5>
  113.  
  114.             <h6><a href="/addrecipe/{{ recipe.id }}">Add Recipe</a>
  115.                 <a href="/removerecipe/{{ recipe.id }}">Remove Recipe</a></h6>
  116.         </div>
  117.     {% endfor %}
  118.     </div>
  119.  
  120.     <div id="popupContact" class="popup">
  121.             <a id="popupContactClose" style="cursor:pointer;float:right;">x</a>
  122.             <p id="contactArea">
  123.             <h1 style="text-align:center">Create New Recipe</h1>
  124.             {% include 'cookbook/create_form.html' %}
  125.             </p>
  126.     </div>
  127.     <div id="backgroundPopup">
  128.     </div>  
  129.     <div id="col2-footer">
  130.     {% paginate %}
  131.     <p id="recipe_order_text"> order by: <a href="/userbook/ordered/name">abc</a>|<a href="/userbook/ordered/date">date</a>
  132.     </div>
  133.  
  134. {% endblock %}
  135.  
  136. {% block footer %}
  137.         <a class="create" style="cursor:pointer" >Create New Recipe</a>
  138. {% endblock %}
  139.        
  140. {% load i18n %}
  141.  
  142.     {% block doctype %}<?xml version="1.0" encoding="UTF-8"?>
  143.     <!DOCTYPE html
  144.          PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  145.          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  146.     <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  147.     {% endblock %}
  148.  
  149.  
  150.     {% block head %}
  151.  <head>
  152.         <title>{% block title %}Recipeek{% endblock %}</title>          
  153.         <script type="text/javascript">
  154.         $(document).ready(function(){
  155.             var form = $('form#createrecipeform');
  156.             form.submit(function(e) {
  157.             e.preventDefault();
  158.             console.log('ajax form submission function called successfully.');
  159.             //form = $(this);
  160.             console.log(form)
  161.             var serialized_form = form.serialize();
  162.                 $.ajax({ type: "POST", 
  163.                     url: $(this).attr('action'),
  164.                     data: serialized_form, 
  165.                     success: (function(data) { 
  166.                         console.log('ajax success function called successfully.');
  167.                         data = $.parseJSON(data);
  168.                         if (data.success) {
  169.                             console.log('success');
  170.                             var newForm = data.form;
  171.                             form.replaceWith(newForm);
  172.                         } else {
  173.                             console.log('failure');
  174.                             var newForm = data.form;
  175.                             form.replaceWith(newForm);  
  176.                         }
  177.                     })
  178.                 });
  179.                 return false;
  180.             });
  181.         });
  182.         </script>
  183.     </head>
  184.     {% endblock %}
  185.  
  186.     {% block body %}
  187.     <body>
  188.         {% block header %}
  189.         <div id="header"></div>
  190.  
  191.         {% endblock %}
  192.  
  193.     <div id="left_pane">
  194.             <div id="left_pane-container">
  195.                 <div id="logo"><img src= "/static/recipeek_logo.png" style="padding-left:10px;" /></div>
  196.                     <div id="left_pane-items">  
  197.                         <div id="nav_out">
  198.                             <ul id="nav_outlist">
  199.                                 <li><a href="/aboutus">about us</a></li>
  200.                                 <li><a href="/contact">contact</a></li>
  201.                                 <li><a href="/glossary">glossary</a></li>
  202.  
  203.                             </ul>
  204.                         </div><!--nav_out-->
  205.                 </div><!--left_pane-items-->
  206.         </div><!--left_pane-container-->
  207.     </div><!--left_pane-->
  208.  
  209.     {% block container %}  
  210.     <div id="container">    
  211.         <div id="container_header">
  212.  
  213.                     <div id="horz_nav">
  214.                         <ol>
  215.                             <li id="cookbook_link">{% block nav-cookbooks %}<a href="/cookbooks/">Cookbooks</a> {% endblock %}</li>
  216.                             <li id="account_link">{% block nav-account %}<a href="/account/">My Cookbook</a>{% endblock %}</li>
  217.                         </ol>
  218.                     </div>
  219.                         <div id="container_header-items">
  220.                                 <a href="{% url index %}">{% trans "Home" %}</a> |
  221.                                 {% if user.is_authenticated %}
  222.                                 {{ user.username }}
  223.                                 (<a href="{% url auth_logout %}">{% trans "Log out" %}</a> |
  224.                                 <a href="{% url auth_password_change %}">{% trans "Change password" %}</a>)
  225.                                 <form action="/search/" method="get">
  226.                                     <input type="text" name="q" id="id_q" value="Search" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"/>
  227.                                 </form>
  228.                                 {% else %}
  229.                                 <a href="{% url auth_login %}">{% trans "Log in" %}</a>
  230.                                 {% endif %}
  231.                             </div><!--header-items-->
  232.  
  233.         </div><!--header-->
  234.  
  235.  
  236.                 <div id="col2">
  237.                     <div id="col2-header"></div>
  238.  
  239.                             {% block content %}{% endblock %}
  240.  
  241.                 </div>
  242.             <div id="footer">
  243.                 {% block footer %}
  244.                 {% endblock %}
  245.             </div>  
  246.     </div>
  247.     {% endblock %}
  248.  
  249.  
  250.     </body>
  251.     {% endblock %}  
  252.     </html>
  253.        
  254. <form class="task-form" action="." method="POST">
  255.     <button class=".task-add-button" value="Add Task">
  256.     {{ TaskFormSet.as_p }}
  257. </form>
  258. <script>
  259. var $form = $('.task-form')
  260.   , $button = $form.find('.task-add-button')
  261.   , template = '{{ TaskFormSet.empty_form.as_p }}'
  262.   , num_formsets = $form.find('input[name=TOTAL_FORMS]').val();
  263.  
  264. $button.on('click', function(){
  265.     var formset_html = template.replace('__prefix__', 'form-'+(++num_formsets);
  266.     $(formset_html).appendTo($form); // Creates new input
  267.     return false;
  268. });
  269. </script>
  270.        
  271. from django.forms.formsets import formset_factory
  272.  
  273. class TaskForm(Form):
  274.     title = CharField()
  275.     ... any number of extra fields
  276.  
  277. TaskFormSet = formset_factory(TaskForm, can_order=True, can_delete=True, extra=1)
  278.  
  279. # In your view
  280. instance = TaskModel.objects.get(...)
  281.  
  282. tasks_formset = TaskFormSet(request.POST, initial=instance.tasks_json)
  283. context['TaskFormSet'] = tasks_formset
  284.  
  285. if request.method == 'POST' and tasks_formset.is_valid():
  286.     instance.tasks_json = [task.cleaned_data for task in tasks_formset]
  287.     instance.save()