gpt4 book ai didi

Django - ModelForm 创建还是更新?

转载 作者:行者123 更新时间:2023-12-02 01:35:56 29 4
gpt4 key购买 nike

我需要一个表格,允许在计划中创建或添加 session

型号

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']

呈现表单的 View

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),)

模板editor.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),)

问题

session 始终被创建(从不更新)

问题

  • 在我看来post我如何知道 session 必须更新而不是创建?
  • 有没有办法简化这段代码?

最佳答案

如果要更新 session ,则需要在绑定(bind)表单时提供实例。

如果表格有效,您可以 save使用commit=False,并更新导师。

form = SessionForm(instance=instance, data=request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.tutor = request.user
instance.save()

关于Django - ModelForm 创建还是更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10205657/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com