gpt4 book ai didi

python - 我收到 __init__() 与 CreateView 获得意外的关键字参数 'instance'

转载 作者:行者123 更新时间:2023-12-01 09:06:43 25 4
gpt4 key购买 nike

我使用的是 Django 2.1 版本。我正在尝试创建CreateView。这是我的观点.py;

# views.py
class CreateJob(CreateView):
form_class = CreateJob
template_name = 'category_list.html'

这是我的 forms.py;

# forms.py
from django import forms
from myapp.models import Category

class CreateJob(forms.Form):
CATEGORY_CHOICES = (
)
category_list = forms.ChoiceField(
widget=forms.Select(attrs={
"id": "cate"
}),
choices=CATEGORY_CHOICES,
required=True,
)

def __init__(self, *args, **kwargs):
super(CreateJob, self).__init__(*args, **kwargs)
category_choices = [(cat.id, cat.name) for cat in Category.objects.all()]
self.fields['category_list'].choices = category_choices

在此 forms.py 中,我尝试创建选择字段并列出类别对象。在我的模板中,当我选择类别时,它将发出ajax请求并列出与类别模型相关的描述列表。你可以看看我下面的模板。一旦我选择通过 forms.py 中的 choicefield 创建的类别之一,它将在具有“desc”id 的选项中列出描述列表。

{% extends '../base.html' %}

{% block body %}
<form action="." method="post">
{% csrf_token %}
{{ form }}
</form>

<select id="desc">
{% for description in description_list %}
<option value="{{ description.pk }}">{{ description.name }}></option>
{% endfor %}
</select>
{% endblock %}

{% block script %}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function (e) {
$("#cate").change(function(e) {
cat = $(this).val();
var job = $("#desc");
$.ajax({
url: 'item/' + cat + '/',
type: "GET",
processData: false,
contentType: false,
success: function (data) {
console.log(data.description_list),
job.html(data)
},
error: function (xhr, errmsg, err) {
console.log(xhr, errmsg, err);
} // end error: function
});
});
});
</script>
{% endblock %}

我的 urls.py 看起来像这样;

path('test/', CreateJob.as_view()),

当我继续访问 127.0.0.1:8000/test 时,它给出了以下错误:

File "C:\Users\kenan\Desktop\Django\jobs\myapp\forms.py", line 16, in __init__
super(CreateJob, self).__init__(*args, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'instance'
[23/Aug/2018 14:37:03] "GET /test/ HTTP/1.1" 500 89443

I want to note that, I searched for it and some people fix their problem by changing forms.Form to forms.ModelForm. but that's not what I want. Thanks in advance!

最佳答案

您正在使用CreateView,但与之关联的表单不是ModelFormModelForm 采用可选的 instance arg(用于编辑现有模型实例) - 这对于非模型表单不是有效参数 - 和 CreateView 在实例化表单类时将此参数传递给它。因此出现了错误。

TL;DR:如果您想使用CreateView,则必须使用ModelForm(或公开完全相同 API 的内容)作为模型表单)。

关于python - 我收到 __init__() 与 CreateView 获得意外的关键字参数 'instance',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51984225/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com