我試圖讓一個Django應用程序來處理事件。下面的視圖處理已經創建的事件的編輯。保存而不是更新的模型
@login_required
def event_admin(request, event_id):
event = get_object_or_404(Event, pk=event_id)
if request.method == 'POST' and request.user == event.organiser:
event_form = EventAdminForm(request.POST, instance=event)
if event_form.is_valid():
event_form.save()
return HttpResponseRedirect(reverse('event_event_detail',
args=(event.id,)))
elif request.user == event.organiser:
event_form = EventAdminForm(instance=event)
return render_to_response('events/event_admin.html',
{'event_form': event_form, 'event': event},
context_instance = RequestContext(request))
return HttpResponseRedirect(reverse('event_event_detail', args=(event.id,)))
當編輯現有事件時,現有事件保持不變,而創建新事件時發生所做的更改。有人可以看到我做錯了什麼嗎?非常感謝。
編輯:
這裏是forms.py的相關部分,如果它有幫助。
class EventAdminForm(ModelForm):
start_time = forms.DateTimeField(widget=SplitSelectDateTimeWidget(
minute_step=5, second_step=60, years=range(2009, 2015)),
initial=datetime.datetime.now())
end_time = forms.DateTimeField(widget=SplitSelectDateTimeWidget(
minute_step=5, second_step=60, years=range(2009, 2015)),
initial=datetime.datetime.now())
def clean(self):
cleaned_data = self.cleaned_data
start_time = cleaned_data.get('start_time')
end_time = cleaned_data.get('end_time')
# The start of an event cannot be after the end.
if start_time > end_time:
raise forms.ValidationError(u'The end of an event can not be before the start.')
return cleaned_data
class Meta:
model = Event
exclude = ('attendees', 'organiser',)
你沒有搞砸重寫save()方法嗎?如果是,則顯示錶單定義 – zalew 2009-08-21 04:20:28
否,save()未觸及。我已經重寫了clean(),如果這會有所作爲? – xoebus 2009-08-21 07:02:06
不是,除非有清除主鍵值的可能性。如果在驗證過程中丟失了pk,它將創建另一個實例。 – zalew 2009-08-21 08:56:36