python - Saving form data to DB and sending it to an API; Django -


i'm new django , i'm trying capture user information. upon submitting form, data saved db. i'd send zipcode field sunlight foundation's api provide users helpful information once form submitted.

when sunlight script in home.html, returns list based on zipcode, data isn't saved django. when script removed home.html, data saved database. how can have best of both worlds, where, data saved django , list rendered after user submits form. should placing sunlight script somewhere else (views.py?)?

thanks taking time on , potentially help!

home.html

    <h1>{{title}}</h1>          join our cause:          <form action="" id="rep-lookup" method='post'>{% csrf_token %}                  {{form.as_p}}              <input type="submit" id="btn-lookup" class="btn" value="join" />         </form>          <div id="rep-lookup-results">         </div>      </div>   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script>window.jquery || document.write('<script src="jquery.min.js"><\/script>')</script> <script> 'use strict';  $(document).ready(function () {     $('#rep-lookup').submit(function(e){         e.preventdefault();          var $results = $('#rep-lookup-results'),             zipcode = $('#id_zipcode').val(),             apikey = 'xxx';          var requesturl = 'http://congress.api.sunlightfoundation.com/legislators/locate?callback=?';          // collect data          $.getjson(requesturl, {             'apikey' : apikey,             'zip' : zipcode,         }, function(data){             if (data.results && data.results.length > 0) {                  var mysenators = '<p>here reps.<br> please urge them support cause.</p>';                  $.each(data.results, function(i, rep) {                         mysenators += '<p>';                         mysenators += '<a href="' + rep.contact_form + '" target="_blank" class="repname">';                         mysenators += '</a> ';                         mysenators += rep.state + '</span><br>';                         mysenators += '</p><hr>';                 });                  $results.html(mysenators);             } else {                 $results.html('<p style="color:#ff0000;">no reps found zip code:' + zipcode + '.<br>please try again...</p>');             }         });      }); });   </script> 

forms.py

from django import forms  .models import signup   class signupform(forms.modelform):     class meta:         model = signup         fields = ['name_last', 'name_first', 'email', 'zipcode',]  #overriding/adding django validation     def clean_email(self):         email = self.cleaned_data.get('email')         return email      def clean_name_first(self):         name_first = self.cleaned_data.get('first_name')         #write validation code.         return name_first      def clean_zipcode(self):         zipcode = self.cleaned_data.get('zipcode')         return zipcode 

models.py

from django.db import models  class signup(models.model):     email = models.emailfield(max_length=120)     name_first = models.charfield(max_length=120, blank=true, null=true) #optional , also: default=''     name_last = models.charfield(max_length=120,)     zipcode = models.charfield(max_length=120,)      def __unicode__(self):          return self.email 

views.py

from django.shortcuts import render  .forms import signupform  def home(request):     title = 'welcome'     form = signupform(request.post or none)       context = {         "title": title,         "form": form,     }      if form.is_valid():         instance = form.save(commit=false)          first_name = form.cleaned_data.get("first_name")         if not first_name:             first_name = "none given"             instance.first_name = first_name         instance.save()         context = {         "title": "thanks",         }         return render(request, "home.html", context) 

how calling sunlight's api inside view. can done follows:

    def home(request):         if request.method=="post":             payload = {'apikey' : apikey,                     'zip' : request.post.get('zipcode'),}             response = requests.get("http://congress.api.sunlightfoundation.com/legislators/locate?callback=?",params=payload) 

now use response wish. process response did in template , pass processed data in context back.

you need not hit api via js. in template submit form.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -