djangoフォームに問題があります。これは私が得ているエラーです:
ValueError at /coach/new/
Cannot assign "u'7'": "Course.category" must be a "Category" instance.
ビュー.py
def create_course_page(request):
if request.method == 'POST': # If the form has been submitted...
form = CreateCourseForm(request.POST) # A form bound to the POST data
#form.data['category'] = Category.objects.get(pk=form.data['category']),
if form.is_valid(): # All validation rules pass
cleaned_data = form.cleaned_data
my_course = Course(
title = cleaned_data['title'],
prerequisite = cleaned_data['prerequisite'],
category = Category.objects.get(pk=cleaned_data['category']),
short_description = cleaned_data['short_description'],
#listing_city = cleaned_data['xxxx'],
date_created = datetime.now(),
date_last_updated = datetime.now(),
teacher = request.user,
)
my_course.save()
return HttpResponseRedirect('/') # Redirect after POST
else:
return HttpResponseRedirect('/wtf') # Redirect after POST
else:
my_course = Course()
form = CreateCourseForm(instance=my_course) # An unbound form
return render(request, 'learn/new_course.html', {
'form': form,
})
「form.data['category'] = Category.objects.get(pk=form.data['category']),」で問題を解決しようとしましたが、うまくいきません。
誰かがより良いアイデアを持っていますか? どうもありがとう。
編集: トレースバックは、エラーが発生したことを示しています
if form.is_valid(): # All validation rules pass
EDIT2:これは、djangoフォームが「デフォルト」プログラミングで機能しない理由をよりよく説明するかもしれません:
フォーム.py
def categories_as_choices():
categories = [(u'', u'')] # So select box get's an empty value/default label
for category in Category.objects.all():
new_category = []
sub_categories = []
for sub_category in category.get_children():
sub_categories.append([sub_category.id, sub_category.name])
new_category = [category.name, sub_categories]
categories.append(new_category)
return categories
class CreateCourseForm(ModelForm):
category = forms.ChoiceField(choices=categories_as_choices()) #chzn-select
class Meta:
model = Course
fields = ('title', 'category')
def __init__(self, *args, **kwargs):
super (CreateCourseForm, self).__init__(*args, **kwargs)
self.fields['category'].widget.attrs['class'] = 'chzn-select'