2011-05-15 81 views
0

嘿,大家我是新來的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) 

任何人都可以幫助使這種形式,因此它也允許編輯?

謝謝!

回答

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