我是Django的新手,正在尝试捕获用户信息。提交表单后,数据将保存到数据库。我还想将邮政编码字段发送到sunlight Foundation的API,以便在提交表单后为用户提供有用的信息。

当阳光脚本位于HOME.HTML中时,它将返回基于邮政编码的列表,但Django不会保存数据。从HOME.HTML删除脚本后,数据将保存到数据库中。我怎么能两全其美,数据由Django保存,并且列表在用户提交表单后呈现。我应该将阳光脚本放置在其他位置吗(views.py?)?

感谢您抽出宝贵的时间对此进行检查,并可能会对您有所帮助!

主页.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>


格式

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


模型

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


观点

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)

最佳答案

从视图内部调用阳光的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。在您的模板中,提交表单。

关于python - 将表单数据保存到DB并将其发送到API; Django的,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30832862/

10-13 07:52
查看更多