在Django的表单中声明ForeignKey的正确方法

时间:2015-10-19 15:11:13

标签: python django

我将数据发布到数据库表时出错了。我想我在如何申报我的模型时犯了一个错误。当我想提交表格时,出现了这个错误。

无法指定" u' 3'":" AerialFoto.index_id"必须是" No_index"实例

Models.py

class AerialFoto(models.Model):
    AerialFoto_id = models.AutoField(primary_key=True)
    index_id = models.ForeignKey(No_index, null=True, blank=True)
    scale_id = models.ForeignKey(Scale, null=True, blank=True)
    location_id = models.ForeignKey(Location, null=True, blank=True)
    year_id = models.ForiegnKey(Year, null=True, blank=True)
    file_directory = models.CharField(max_length=255)
    size = models.DecimalField(max_digits=19, decimal_places=2, blank=True, null=True)
    gsd = models.CharField(max_length=7)

我的Views.py

def submit_upload(request):

if request.method == 'POST':
    form = UploadForm(request.POST)
    if form.is_valid():
        year_id = form.cleaned_data['year_id']
        scale_id = form.cleaned_data['scale_id']
        index_id = form.cleaned_data['index_id']
        location_id = form.cleaned_data['location_id']
        size = form.cleaned_data['size']
        print index_id
          query = AerialFoto(year_id = year_id , scale_id = scale_id, index_id = index_id, location_id = location_id, size = size)
        query.save()

The Result After Save

3 个答案:

答案 0 :(得分:0)

<强>&#34; AerialFoto.index_id&#34;必须是&#34; No_index&#34;实例<!/强>

你可以写一个拐杖

index_id = No_index.objects.get(pk=form.cleaned_data['index_id'])

但最好使用ModelForm

答案 1 :(得分:0)

要使用模型表单,您需要制作模型表单(困难);这是通过以下方式完成的:

# forms.py
class UploadModelForm(forms.ModelForm):
    class Meta:
        model = AerialFoto
        fields = ['year_id', 'scale_id', 'index_id', 'location_id', 'size']

模型表单需要导入并在您的视图中使用,如下所示:

# views.py
if request.method == 'POST':
    form = UploadModelForm(request.POST)
    if form.is_valid():
       form.save()

我没有测试过这段代码所以请不要回来说“它不起作用”它只是作为锅炉板。

答案 2 :(得分:0)

要使用ModelForm从模型创建表单,您必须:

class AerialPhotoForm(forms.ModelForm):
    class Meta:
        model = AerialPhoto
        fields = ['year_id', 'scale_id', 'index_id', 'location_id', 'size']

然后在你看来:

# ...
form = AerialPhotoForm(request.POST)
if form.is_valid():
    form.save()