13

我需要有一个允许在计划中创建或添加会话的表格

模型

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,我怎么知道会话必须更新而不是创建?
  • 有没有办法简化这段代码?
4

4 回答 4

25

如果要更新会话,则需要在绑定表单时提供实例。

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

form = SessionForm(instance=instance, data=request.POST)
if form.is_valid():
    instance = form.save(commit=False)
    instance.tutor = request.user
    instance.save()
于 2012-04-18T08:52:06.333 回答
1
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponseRedirect, Http404
from django.template import RequestContext
from application.models import Session
from application.forms import SessionForm

def allInOneView(request):
    session_id = request.POST.get('session_id')

    if session_id:
        session = get_object_or_404(Session, pk=session_id)
    else:
        session = None

    """
    A subclass of ModelForm can accept an existing model instance 
    as the keyword argument instance; 
    if this is supplied, save() will update that instance. 
    If it's not supplied, save() will create a new instance of the specified model.
    """
    form = SessionForm(instance=session)

    if request.method == 'POST':
        form = SessionForm(request.POST, instance=session)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(request.path)

    return render_to_response('planner/editor.html', {
        'form': form
    }, context_instance=RequestContext(request))
于 2012-04-18T19:37:20.447 回答
1

我现在通常做的(按照这里提到的建议)只使用一个视图将可选的 session_id(没有用于创建的 session_id)传递给 URL 调度程序。

<form action="{% url session_edit session_id=session_id|default_if_none:"" %}"
    method="post">{% csrf_token %}
{{ form.as_p }}
</form>
url('^planner/edit$', session_edit, name='session_edit'),
url('^planner/edit/(?P<session_id>\d+)$', session_edit, name='session_edit'),

我发现重新组合所有 4 个案例

  • 获取创作表格
  • 获取更新表格
  • 帖子创建表单
  • 发布更新表格

进入一个视图更易于维护。

于 2013-06-08T08:08:23.290 回答
0

在一个视图中完成所有操作。就像是:

def session_manager(request):

    session = None
    try:
        session = Session.objects.get(id=request.POST['id'])
    except Session.DoesNotExist:
        pass

    if request.method == "POST":
       kwargs = {
            data = request.POST
       }
       if session:
            # Update
            kwargs['instance'] session 
       form = SessionForm(**kwargs)
       if form.is_valid():
            ...
    else:
        form = SessionForm(instance=session)
于 2012-04-18T08:53:35.990 回答