1
我是Django的新手,我試圖捕獲用戶信息。提交表格後,數據將保存到數據庫中。我還希望將郵政編碼字段發送到陽光基金會的API,以便在提交表單後爲用戶提供有用的信息。將表單數據保存到數據庫併發送給API; Django
陽光腳本在HOME.HTML中時,它會根據郵政編碼返回一個列表,但數據不會由Django保存。當該腳本從HOME.HTML中刪除時,數據將被保存到數據庫中。我怎樣才能充分利用這兩個世界,數據由Django保存,列表在用戶提交表單後呈現。我應該把陽光腳本放在其他地方(views.py?)嗎?
感謝您抽出寶貴時間瀏覽並幫助您!
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 the data
$.getJSON(requestURL, {
'apikey' : apiKey,
'zip' : zipcode,
}, function(data){
if (data.results && data.results.length > 0) {
var mySenators = '<p>Here are your reps.<br> Please urge them to support the 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 for this zip code:' + zipcode + '.<br>Please try again...</p>');
}
});
});
});
</script>
FORMS.PY
from django import forms
from .models import SignUp
class SignUpForm(forms.ModelForm):
class Meta:
model = SignUp
fields = ['name_last', 'name_first', 'email', 'zipcode',]
#overriding/adding to 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 and 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
from .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)