我想實現一個相當簡單的事情,但有一個錯誤卡住,不知道它來自哪裏。簡單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)
線,但我不知道該怎麼做。
你好,謝謝你的回答。在使用你的代碼(第二個變體)之後,表單沒有驗證,我收到錯誤,'用戶'和'項目'字段是必需的(他們實際上是)。我想提一下爲什麼我這麼做:我想從'request.user'獲取當前用戶,並從'slug'獲取項目,因此用戶只需輸入'duration'。那是我想要達到的目標。 – Eimantas
該代碼與'new_iteration = Iteration(** form.cleaned_data)'工作正常,但我想從request.user和slug :)獲取當前用戶和項目 – Eimantas