我试图实现一件相当简单的事情,但被一个错误卡住了,并且不知道它来自哪里。
我想在我的视图中创建并保存一个对象。代码非常简单:
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)
线路,但我不确定该怎么做。
发布于 2014-05-25 21:34:20
您不应将对象创建为
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()发布于 2014-05-25 22:15:37
我已经完成了任务。为了更好地理解,我应该添加我的forms.py。我已经编辑了我的forms.py文件,并在那里定义了唯一的“可选”字段应该是"duration",并且当在视图中启动表单时,Django应该获得其他内容(用户和项目)。
另一个错误是我没有将数据作为关键字参数传递,谢谢Rohan。
因此,我已经将fields = ('duration',)添加到我的ModelForm中,并使用关键字参数重新初始化了表单。
https://stackoverflow.com/questions/23855699
复制相似问题