【发布时间】:2019-01-29 17:45:55
【问题描述】:
我使用的是 Django 2.1 版本。 我正在尝试制作 CreateView。这是我的views.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 中的选择字段创建的类别之一,它将在具有“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
我想指出,我搜索了它,有些人通过将 forms.Form 更改为 forms.ModelForm 来解决他们的问题。但这不是我想要的。提前致谢!
【问题讨论】:
-
我不明白你想在这里做什么。你的观点似乎与创造任何东西没有任何关系。那么你为什么使用 CreateView 呢?使用简单的 FormView。
-
因为我还没写。我只是在测试它是否会列出类别对象。
-
但这没有任何意义。如果要使用视图创建 Job 对象,请使用带有 ModelForm 的 CreateView。如果要返回完全不同的类别列表,请不要使用 CreateView。
-
对,我想创建 Job 对象,但是现在当我将 forms.Form 更改为 forms.ModelForm 时,它给了我这个错误;
ValueError: ModelForm has no model class specified. -
ok,我这样问,Meta类怎么不写字段,自己写自定义字段?
标签: python django python-3.x django-forms django-views