2012-09-05 147 views
0

我在使用django表單時遇到了一些問題。這是我得到的錯誤:Django/Python:ValueError at/foo/bar

ValueError at /coach/new/ 
Cannot assign "u'7'": "Course.category" must be a "Category" instance. 

views.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.objects.get解決這個問題(PK = form.data ['category'])「,但這不會做到。

有沒有人有更好的主意?非常感謝。

編輯: 回溯顯示錯誤在

if form.is_valid(): # All validation rules pass 

EDIT2情況: 這可能更好地解釋,爲什麼Django的形式不與 「默認」 的編程工作:

forms.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' 

回答

0

試試這個

get_cat_name = form.cleaned_data['category'] 

get_obj = Category.objects.get(category = get_cat_name) 

category = get_obj.id 
0
category = Category.objects.get(pk=cleaned_data['category']) 

通常你不需要相關Category對象,只是給了cleaned_data是足夠和正確的方式去。

my_course = Course(......, category = cleaned_data['category'], ...) 

或者,如果您有相關的類ID工作,那麼每ForeignKey示範田可以作爲<field_name>_id。但是你必須給出一個有效的外鍵,而不是相關的對象。

my_course = Course(......, category_id = 8, ...) 
0

您可以嘗試

my_course = Course(..., category = form.cleaned_data['category']), ...) 

form.cleaned_data將有類別實例。

然而,許多建議的方法是隻在窗體保存爲

my_course = form.save() 

如果你想手動更改某些領域,做

my_course = form.save(commit=False) 
my_course.some_field = some_value 
... 
my_couse.save() 
+0

已經試過了。我認爲這個問題在forms.is_valid()方法中。 –