Django:自动分配CBV格式的外键

时间:2018-01-15 21:37:43

标签: django

这建立于:Django automatically set foreign key in form (with class based views)。答案似乎有效,但Django抛出了一个ValueError

我有(2)模型:由外键关联的产品和过程。我希望从“产品”页面获得一个链接以添加过程,并将产品FK(通过其pk)自动传递给表单。有几千种产品,因此从下拉列表中手动选择FK是不可行的。

class ProductBase(models.Model):
    id = models.UUIDField(primary_key=True,default=uuid.uuid4,null=False)
    name = models.CharField(max_length=128,null=False)

class ProcedureText(models.Model):
    id_procedure = models.UUIDField(primary_key=True,default=uuid.uuid4,null=False)
    text_procedure = models.TextField()
    parent_product = models.ForeignKey(ProductBase,on_delete=models.CASCADE')

我在“产品详细信息”页面中有一个链接,用于调用CreateView:

<a class='btn btn-success' href="{% url 'products:addprocedure' pk=product_details.pk %}">Add Procedure</a>

通过urls.py映射:

    path('addprocedure <pk>',views.AddProcedureView.as_view(),name='addprocedure'),

class AddProcedureView(CreateView):
    form_class = AddProcedureForm
    template_name = 'addprocedure.html'
    model = ProcedureText
    #fields = ('__all__')

    def form_valid(self, form):
        form.instance.parent_recipe = self.kwargs.get('pk')
        return super(AddProcedureView, self).form_valid(form)

调用forms.py

class AddProcedureForm(forms.ModelForm):

    class Meta:
        model = ProcedureText
        fields = ('__all__')

并模板化为标准形式:

<form class="form-horizontal" action="" enctype="multipart/form-data" method="POST">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

每当提交表单时,Django都会返回以下形式的ValueError:

无法指定“'28a3a242-06f6-464a-9b01-aa3fefa866ed'”:“ProcedureText.parent_product”必须是“ProductBase”实例。

即使被拒绝的UUID是传递给它的UUID,也是实际的现有ProductBase实例。传递给它的任何实例UUID都会出现问题。

想到这里出了什么问题?

1 个答案:

答案 0 :(得分:0)

设置def form_valid(self, form): form.instance.parent_recipe_id = self.kwargs.get('pk') 而不是fields

exclude

然后,您应该修改parent_recipe // Get Historics module.exports.getHistorics = (callback, limit) => { console.log('Get Historics-Historic'); Historic.find(callback).limit(limit); console.log('Get Historics-Historic-After find'); console.log(limit); } ,以便表单中不包含// Get Historics module.exports.getHistorics = (callback, limit) => { var query = Historic.find({}); query.limit(limit); query.exec(callback); }