将表单数据保存到DB并将其发送到API; Django的

时间:2015-06-14 18:14:38

标签: python django forms post

我是Django的新手,我试图捕获用户信息。提交表单后,数据将保存到数据库中。我还希望将邮政编码字段发送到阳光基金会的API,以便在提交表单后向用户提供有用的信息。

当阳光脚本在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)

1 个答案:

答案 0 :(得分:1)

如何从视图中调用阳光的API。这可以按如下方式完成:

    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)

现在可以根据需要使用此响应。像在模板中一样处理响应,并在上下文中传递处理过的数据。

您无需通过js点击API。在您的模板中,只需提交表单即可。