Django:无法分配对象:" VoterCode.region"必须是"地区"例

时间:2017-03-15 09:36:39

标签: django django-forms foreign-keys

我是Django的新手,我正在尝试使用外键创建一个表单。我只从表单中获取一个外键,然后分配其余的值。我理解我正在尝试保存一个对象,而不是一个实例。 我认为查询正在获取实例集合(实例的查询集),即使它只有一个元素,我也必须始终采用第一个。这是我试图做的,但它不起作用:

return Region.objects.filter(name = region_name)[:1].get()

这是我的表格:

class VoterCodeForm(forms.ModelForm):
    election = forms.ModelChoiceField(queryset=Election.objects.all(), empty_label="Select an election")
    class Meta:
        model = VoterCode
        fields = ('election',)

以下是我的观点:

def populate_voter_codes(request):
    if request.method == "POST":
        form = VoterCodeForm(request.POST)
        if form.is_valid():
            election = form.instance.election
            form.save(commit=False)
            VoterCode.populate_voter_codes(election)
            return redirect('elections')
    else:
        form = VoterCodeForm()
    return render(request, 'admin_interface/populate_voter_codes.html', {'form': form})

以下是我保存值的方法:

def postcode_to_region(postcode):
        ...some processing...
        return Region.objects.filter(name = region_name)[:1].get()

def populate_voter_codes(the_election):
    data = requests.get(url = "http://t2a.co/rest/?output=json&method=person_search&api_key=test").json()
    data = data["person_list"]
    i = 1
    for person in data:
        voter_code = VoterCode.generate_voter_code()
        #print(person["postcode"])
        region = VoterCode.postcode_to_region(person["postcode"]);
        entry = VoterCode(id=i, code=voter_code, election = the_election, region = region)
        entry.save()
        i += 1

感谢您寻找:)

0 个答案:

没有答案