【问题标题】:Saving form data to DB and sending it to an API; Django将表单数据保存到数据库并将其发送到 API;姜戈
【发布时间】:2015-08-30 05:20:04
【问题描述】:

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

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

【问题讨论】:

    标签: python django forms post


    【解决方案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。只需在您的模板中提交表单即可。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-21
      • 2014-01-20
      • 1970-01-01
      • 2017-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多