2014-01-17 116 views
1

我有一個相當簡單的表單,但我收到了ModelChoiceField的TypeError,我無法理解爲什麼。表單返回模型ID號碼,並且我應該能夠查找特定模型並將其用於任何目的。它不工作了這樣though.Here是我的表單代碼:Django的'NoneType'對象沒有屬性'__getitem__'與表格保存

class TestimonialForm(forms.Form): 
    title = forms.CharField(max_length=100) 
    content = forms.CharField(max_length=500, widget=forms.Textarea) 
    ratings = (
     (1, '1'), 
     (2, '2'), 
     (3, '3'), 
     (4, '4'), 
     (5, '5') 
     ) 
    rating = forms.ChoiceField(choices=ratings, widget=forms.RadioSelect) 
    reward = forms.ModelChoiceField(queryset=Reward.objects.all()) 
    username = forms.CharField(max_length=50, widget=forms.HiddenInput) 
    def clean(self): 
     cleaned_data = super(TestimonialForm, self).clean() 
     usr = cleaned_data.get('username') 
     res = cleaned_data.get('reward') 
    if Reward_Review.objects.filter(id=res.id).filter(affiliate__username=usr): 
     raise forms.ValidationError("You have already submitted a testimonial. You can only submit one per gift card.") 
    if not Redeem.objects.filter(reward__id=res.id).filter(affiliate__username=usr): 
     raise forms.ValidationError("You haven't received this gift card yet, so you cannot write a review for it.") 
    def clean_username(self): 
    data = self.cleaned_data['username'] 
    try: 
     Affiliate.objects.get(user__username=data) 
    except ObjectDoesNotExist, e: 
     msg = 'The username provided by the form submission does not match anyone in our database.' 
     logger.exception(e) 
     logger.debug(msg, exc_info=True) 
     raise forms.ValidationError("Invalid username. Please try again later.") 
    return data 
    def save(self, request, *args, **kwargs): 
    data = self.cleaned_data 
    user = request.user 
    re = Reward.objects.get(id=data['reward']) 
    points = Points.objects.create(affiliate=user, points=float(10), from_offer=False, from_task=True) 
    rate = Reward_Rating.objects.create(affiliate=user, reward=re, rating_value=data['rating']) 
    testimonial = Reward_Review.objects.create(affiliate=user, reward=re, reward_rating=rate, review_title=data['title'], review_content=data['content']) 
    return testimonial 

完全跟蹤:

Environment: 
Request Method: POST 
Traceback: 

File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 
    114.      response = wrapped_callback(request, *callback_args, **callback_kwargs) 
File "/app/.heroku/python/lib/python2.7/site-packages/django/views/generic/base.py" in view 
    69.    return self.dispatch(request, *args, **kwargs) 
File "/app/.heroku/python/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper 
    29.    return bound_func(*args, **kwargs) 
File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 
    22.     return view_func(request, *args, **kwargs) 
File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 
    22.     return view_func(request, *args, **kwargs) 
File "/app/.heroku/python/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func 
    25.     return func(self, *args2, **kwargs2) 
File "/app/myapp/views.py" in dispatch 
    756.   return super(TestimonialFormView, self).dispatch(*args, **kwargs) 
File "/app/.heroku/python/lib/python2.7/site-packages/newrelic-2.8.0.7/newrelic/hooks/framework_django.py" in wrapper 
    809.    return wrapped(*args, **kwargs) 
File "/app/.heroku/python/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch 
    87.   return handler(request, *args, **kwargs) 
File "/app/.heroku/python/lib/python2.7/site-packages/django/views/generic/edit.py" in post 
    171.    return self.form_valid(form) 
File "/app/myapp/views.py" in form_valid 
    743. form.save(self.request) 
File "/app/myapp/forms.py" in save 
    215. re = Reward.objects.get(id=data['reward']) 

Exception Type: TypeError at /testimonials/ 
Exception Value: 'NoneType' object has no attribute '__getitem__' 
+0

什麼是異常的* full *回溯?如果在DEBUG模式下使用Django,瀏覽器中的錯誤頁面會有* show traceback作爲文本*選項;點擊並從那裏複製回溯。 –

+0

@MartijnPieters新增 – user3084860

回答

1

Form.clean()必須返回清理數據。

0

Probaby的問題是在這裏

re = Reward.objects.get(id=data['reward']) 

當使用ModelChoiceFieldcleaned_data字典將已經包含相應的對象(而不是它的id) - 所以只是做

re = data['reward'] 
+0

看起來不錯,但不會導致錯誤提及。 –

+0

他他可能是一個完整的堆棧跟蹤會告訴我們確切的問題在哪裏:) – Serafeim

2

在Django的1.6 Form源代碼Somewhere有一行:

self.cleaned_data = self.clean() 

這意味着你應該返回一個字典從clean方法。

事情是這樣的:

def clean(self, ...): 
    // whatever 
    return cleaned_data 

注:

改變在Django開發版本:從clean方法返回一個字典不會在Django的未來版本可能需要在以前的Django的版本, form.clean()需要返回已清理的數據字典。該方法仍然可以返回要使用的數據字典,但不需要更長的 。

相關問題