2014-05-25 113 views
0

我想實現一個相當簡單的事情,但有一個錯誤卡住,不知道它來自哪裏。簡單ChoiceField錯誤

我想在我的視圖中創建並保存一個對象。該代碼非常簡單:

models.py:

class Iteration(models.Model): 
user = models.ForeignKey(User) 
one_two = '1-2 weeks' 
two_four = '2-4 weeks' 
four_six = '4-6 weeks' 
six_eight = '6-8 weeks' 
DURATION_CHOICES = (
    (one_two, '1-2 weeks'), 
    (two_four, '2-4 weeks'), 
    (four_six, '4-6 weeks'), 
    (six_eight, '6-8 weeks'), 
) 

duration = models.CharField(max_length=100, choices=DURATION_CHOICES, default=two_four) 
project = models.ForeignKey(Project) 

def is_upperclass(self): 
    return self.duration in (self.one_two, self.six_eight) 

views.py:

def New_iteration(request, slug): 
form = IterationForm() 
user = request.user 
project = Project.objects.get(user=user, slug=slug) 
if request.method == 'POST': 
    form = IterationForm(request.POST) 
    errors = form.errors 
    if form.is_valid: 
     user = request.user 
     duration = request.POST['duration'] 
     project = Project.objects.get(user=user, slug=slug) 
     new_iteration = Iteration(user.id, form.cleaned_data['duration'], project.id) 
     new_iteration.save() 
     return HttpResponseRedirect("/dashboard/") 
    else: 
     return HttpResponse("not valid") 
return render(request, "new_iteration.html", {"form" : form, "project" : project, "user" : user}) 

我收到一個錯誤invalid literal for int() with base 10: '2-4 weeks'。我認爲它來自

new_iteration = Iteration(user.id, form.cleaned_data['duration'], project.id)

線,但我不知道該怎麼做。

回答

2

你不應該創建作爲

new_iteration = Iteration(user.id, form.cleaned_data['duration'], project.id) 

你需要數據作爲關鍵字參數傳遞的

new_iteration = Iteration(user = user, duration = form.cleaned_data['duration'], 
          project = project) 

但是對象,我相信IterationForm是模型的形式,你想之前得到project節省迭代,更好的辦法是

if form.is_valid(): #note this is function call 
    user = request.user 
    project = Project.objects.get(user=user, slug=slug) 
    new_iteration = form.save(commit=False) 
    new_iteration.project = project 
    new_iteration.save() 
+0

你好,謝謝你的回答。在使用你的代碼(第二個變體)之後,表單沒有驗證,我收到錯誤,'用戶'和'項目'字段是必需的(他們實際上是)。我想提一下爲什麼我這麼做:我想從'request.user'獲取當前用戶,並從'slug'獲取項目,因此用戶只需輸入'duration'。那是我想要達到的目標。 – Eimantas

+0

該代碼與'new_iteration = Iteration(** form.cleaned_data)'工作正常,但我想從request.user和slug :)獲取當前用戶和項目 – Eimantas

0

我h ave解決了這個任務。我應該添加我的forms.py以便更好地理解。我編輯了我的forms.py文件並在那裏定義,只有「可選」字段應該是「持續時間」,Django應該在視圖中啓動表單時獲得其他內容(用戶和項目)。

另一個錯誤是我沒有傳遞數據作爲關鍵字參數,感謝Rohan。

因此,我已經將fields = ('duration',)添加到我的ModelForm中,並現在使用關鍵字參數重新創建表單。