我需要有一个允许在计划中创建或添加会话的表格
模型
class Session(models.Model):
tutor = models.ForeignKey(User)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
形式
class SessionForm(forms.ModelForm):
class Meta:
model = Session
exclude = ['tutor']
查看以呈现表单
def editor(request):
if request.method == 'GET':
if request.GET['id'] != '0':
# The user has selected a session
session = Session.objects.get(id=request.GET['id'])
form = SessionForm(instance=session)
else:
# The user wants to add a new session
form = SessionForm()
return render_to_response('planner/editor.html',
{'form': form,}, context_instance=RequestContext(request),)
模板编辑器.html
<form action="/planner/post" method="post">{% csrf_token %}
{{ form.as_p }}
</form>
查看以发布值
def post(request):
if request.method == 'POST':
form = SessionForm(request.POST)
if form.is_valid():
form.instance.tutor = request.user
form.save()
obj = {'posted': True}
return HttpResponse(json.dumps(obj), mimetype='application/json')
else:
return render_to_response('planner/editor.html',
form, context_instance=RequestContext(request),)
问题
会话总是被创建(从不更新)
问题
- 在我看来
post
,我怎么知道会话必须更新而不是创建? - 有没有办法简化这段代码?