【问题标题】:django forms ForeignKey 'value error must be an instance'django forms ForeignKey '值错误必须是一个实例'
【发布时间】:2015-04-30 13:40:30
【问题描述】:

我正在尝试使用现有数据库移植应用程序。我正在使用 db_column 在使用现有数据库名称和列时正确设置 django 模型外键。

models.py

class foo(models.Model):
  foo_id = models.AutoField(primary_key=True, blank=False, null=False)
  foo_name = models.CharField(max_length=500, blank=True, null=True)
  foo_type_lookup = models.ForeignKey('foo_type_lookup', to_field="foo_type_id", db_column="foo_type", blank=True, null=True)

class foo_type_lookup(models.Model):
  foo_type_id = models.AutoField(primary_key=True, blank=False, null=False)
  foo_type = models.CharField(max_length=500, blank=False, null=False)

表 foo_type_lookup 有两行(ids 0 和 1)用于 foo_type 'bar' 和 'baz'。我正在尝试制作一个表单以在 foo 表中添加一条记录,该记录将具有 foo_type_lookup 的外键。 Foo 可以是 bar 或 baz。

views.py

   def add_foo(request):
        action = '#'
        errors = None
        if request.method == 'POST':
            form = FooForm(request.POST)

            if form.is_valid():

                form.save(commit=True)

                return home(request)
            else:
                # The supplied form contained errors - just print them to the terminal.
                errors = form.errors
        else:
            # If the request was not a POST, display the form to enter details.
            form = FooForm()

        # Bad form (or form details), no form supplied...
        # Render the form with error messages (if any).
        return render(request, 'foo/add_foo.html', {'form' : form, 'errors' : errors, 'action' : action})

forms.py

CONTACT_FOO_CHOICES = [[0,'Bar'],[1,'Baz']]

class FooForm(forms.ModelForm):
    foo_type_lookup = forms.ChoiceField(widget=RadioSelect(), choices=CONTACT_FOO_CHOICES)
    foo_name = forms.CharField(label='First Name', max_length=500, required=False)

    class Meta:
        model = foo 

        fields = ('foo_name','foo_type_lookup')

我必须遍历模板中的表单对象,以便在单选按钮更改时添加一个 jQuery 函数。我觉得这很笨拙,但我不确定是否有更 django 的方式来完成此操作:

add_foo.html

<h2>add_foo.html</h2>
<form action="{{action}}" method="post" role="form">
    {% csrf_token %}
    {% for field in form %}
        {% if field.auto_id = 'id_foo_type_lookup' %}
           {% for choice in form.foo_type_lookup.field.choices %}
            <li>
              <label for="id_{{ field.html_name }}_{{ forloop.counter0 }}">
                  <input type="radio"
                    id="id_{{ field.html_name }}_{{ forloop.counter0 }}"
                    value="{{ choice.0 }}"
                    {% if choice.0 == '0' %}
                      checked="true"
                    {% endif %}
                    name="{{ field.html_name }}"
                    onchange="someFunction('id_{{ field.html_name }}_{{ forloop.counter0 }}')"/>
                   {{ choice.1 }}
              </label>
            </li>
            {% endfor %}
        {% else %}
        <div class="formfield_err">{{ field.help_text }}</div>
          <div id="{{ field.auto_id }}_container" >
              <div class="formfield_divlbl">{{ field.label_tag }}
              </div>
              <div class="formfield_divfld">{{ field }}
                  {% if field.field.required %}
                  <span class="required">*</span>
                  {% endif %}
              </div>
              <div id="{{ field.auto_id }}_errors">{{ field.errors }}
              </div>
          </div><div class="clear" style="margin-bottom:12px;"></div>
        {% endif %}
    {% endfor %}

    <input type="submit" value="Submit" />
</form>

我得到错误:

无法分配“'0'”:“foo.foo_type_lookup”必须是“foo_type_lookup”实例。

如何布局类型查找的单选按钮以添加 onchange javascript 并为我的 ModelForm 提供一个“foo_type_lookup”对象,以便将数据保存到数据库中?

【问题讨论】:

    标签: javascript django forms radio-button foreign-keys


    【解决方案1】:

    ChoiceField 不知道它需要将提供的值强制转换为特定模型实例。

    请改用ModelChoiceField

    https://docs.djangoproject.com/en/1.7/ref/forms/fields/#modelchoicefield

    哎呀,您似乎需要一些非常具体的显示逻辑来将您的值硬编码到您的 python 中,这可能不一定等同于您的相关模型的字符串表示形式。

    如果是这样,请覆盖您的表单 save 以在通过 super 调用真正的保存之前应用任何强制。

    您还可以通过commit=False 手动应用任何python 逻辑(我注意到您已经将该语句设置为True,也许您正在玩这个想法。)

    obj = form.save(commit=false)
    obj.foo_lookup_type = MyObject.objects.get(pk=form.cleaned_data['foo_lookup_type'])
    obj.save()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-21
      • 2016-10-16
      • 1970-01-01
      • 2020-12-01
      • 1970-01-01
      • 2019-08-20
      相关资源
      最近更新 更多