使用表单编辑对象

时间:2011-05-15 18:38:28

标签: django-models

嘿大家我是Django的新手,所以我在解决这个问题时遇到了问题。

我目前有一个允许用户保存他/她的活动的表单。我还想让用户能够点击事件并编辑事件而无需创建新事件。这是我目前添加事件的表单。

def event_page(request):
if request.method == 'POST':
    form = EventForm(request.POST)
    if form.is_valid():
        event = Event.objects.create(
        user=request.user,
        eventname = form.cleaned_data['eventname'],
        eventdate = form.cleaned_data['eventdate'],
        eventtime = form.cleaned_data['eventtime'],
        address = form.cleaned_data['address'])
        event.save()
        return HttpResponseRedirect(
            '/user/%s/' % request.user.username
        )
else:
        form = EventForm()
variables = RequestContext(request, {
        'form': form
    })
return render_to_response('events.html', variables)

任何人都可以帮忙制作此表格,以便进行编辑吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

如果您使用ModelForm(http://docs.djangoproject.com/en/1.3/topics/forms/modelforms/)

,这很容易

示例代码如下所示:

def event_page(request, event_id=None):
    """Return a form allowing the user to create or edit
    an event. On a POST request, process the form."""

    # get an event instance: use a dummy instance if
    # we're making a new event, else retrieve the requested event
    if event_id:
        event = get_object_or_404(Event, id=int(event_id))
    else:
        event = Event()

    # am I processing the form? if so, handle that...
    if request.method == 'POST':
        form = EventForm(request.POST, instance=event)
        if form.is_valid():
            # save the form contents to the database
            event = form.save()

            # done; redirect the user off
            return HttpResponseRedirect('/user/%s/' % request.user.username)
    else:
        form = EventForm(instance=event)

    # done; return the template
    return render_to_response('events.html', RequestContext(request, {
        'form': form,
    }))