简体   繁体   English

Django / Python:/ foo / bar中的ValueError

[英]Django/Python: ValueError at /foo/bar

I'm having some issues with django forms. 我在使用Django表单时遇到了一些问题。 This is the error I'm getting: 这是我得到的错误:

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

views.py 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,
})

I tried to fix the problem with "form.data['category'] = Category.objects.get(pk=form.data['category']),", but that's not going to do it. 我试图用“ form.data ['category'] = Category.objects.get(pk = form.data ['category'])”解决问题,但这并不能解决。

Does anyone have a better idea? 有谁有更好的主意吗? Thanks a lot. 非常感谢。

EDIT: Traceback shows that the error happens at 编辑:追溯显示错误发生在

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

EDIT2: This might explain better, why django forms doesn't work with the "default" programming: 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'

try this 尝试这个

get_cat_name =  form.cleaned_data['category']

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

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

Normally you do not need related Category object, just giving the cleaned_data is enough and the right way to go. 通常,您不需要相关的Category对象,只需提供cleaned_data就足够了,并且是正确的方法。

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

Or if you have to work with related category id, then each ForeignKey model field can be used as <field_name>_id . 或者,如果您必须使用相关的类别ID,那么每个ForeignKey模型字段都可以用作<field_name>_id But you must give a valid foreignkey, not the related object. 但是您必须提供有效的外键,而不是相关对象。

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

You can try 你可以试试

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

The form.cleaned_data would have category instance. form.cleaned_data将具有类别实例。

However, much recommended way is to just save the form as 但是,建议的方法是将表单另存为

my_course = form.save()

If you want to manually change some fields, do 如果要手动更改某些字段,请执行

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM