我正在努力实现一个相当简单的事情,但却陷入了错误,并且不知道它来自何处。
我想在视图中创建并保存对象。代码非常简单:
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)
行,但我不确定该怎么做。
答案 0 :(得分: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()
答案 1 :(得分:0)
我已经解决了这个任务。我应该添加我的forms.py以便更好地理解。我已经编辑了我的forms.py文件并在那里定义了 only " selectable"字段应该是" duration",当在视图中启动表单时,Django应该获得其他内容(用户和项目)。
另一个错误是我没有将数据作为关键字参数传递,感谢Rohan。
所以我已将fields = ('duration',)
添加到我的ModelForm中,并立即使用关键字参数重新初始化该表单。