我有一個奇怪的問題與Django 1.3。當我嘗試使用ActivityForm添加一個新的Activity時,即使我使用非Id顯式創建一個新的Activity對象,該活動也會經常更新。Django更新,而不是插入新記錄
另外,當我的ActivityForm類的init有一個明確的trip_id參數時,UI會顯示「選擇一個有效的選擇,該選擇不是可用選項之一」。對於現場位置(即使顯示的選擇是有效的)。但是,如果我將其設置爲可選參數並從kwargs彈出,我不會看到這個問題。
有人可以看看下面的代碼,看看我做錯了什麼?
forms.py
class DestinationMultipleChoiceField(ModelMultipleChoiceField):
def label_from_instance(self, obj):
return obj.city_name
class ActivityForm(forms.Form):
description = forms.CharField(max_length=100, required=True)
location = DestinationChoiceField(queryset = Visit.objects.none(), empty_label=None, required=True)
def __init__(self, trip_id = None, *args, **kwargs):
super(ActivityForm, self).__init__(*args, **kwargs)
if trip_id is not None:
self.fields['location'].queryset = Visit.objects.filter(trip=trip_id).all().select_related('destination')
# A new Activity() is created if nothing is provided
def save(self, activity = Activity()):
if not self.is_valid():
raise forms.ValidationError('ActivityForm was not validated first before trying to call save().')
activity.visit = self.cleaned_data['location']
activity.description = self.cleaned_data['description']
activity.added_by = User.objects.get(pk=1)
activity.save()
views.py
def add_activity(request, trip_id = None, template_name = 'edit-form.html'):
if request.POST:
form = ActivityForm(trip_id, request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('views.list_trip'))
else:
form = ActivityForm(trip_id)
return render_to_response(template_name, {
'page_title': 'Add',
'form': form,
}, context_instance=RequestContext(request))
我沒有使用ModelForm,因爲我需要觸摸多個實體。 – Martin 2012-02-27 22:32:39