我正在构建一个包含用户配置文件、联系人和事件的站点。我创建了一个表单来添加链接到 UserProfile 的新事件,其中的成员是从 UserProf 的联系人列表中选择的。起初,Event 有一个联系人的 ForeignKey,EventForm 是 ModelChoice,一切正常。我可以处理表单并将联系人添加到事件中,并将事件添加到登录的用户配置文件中。
然后,当我尝试使用 ManyToManyField 和 EventForm ModelMultipleChoice 创建事件时,我得到“成员”是此函数的无效关键字参数错误。完全想不通这个。非常感谢您的帮助:)
意见:
def add_events(request):
user = request.user
contacts_list = user.get_profile().contacts.all().order_by('first_name')
if user.is_authenticated():
if request.method == 'POST':
form = EventForm(request.POST)
if form.is_valid():
na = form.cleaned_data['name']
da = form.cleaned_data['date']
de = form.cleaned_data['description']
me = form.cleaned_data['members']
event = Event.objects.create(user=user.get_profile(), name=na, date=da, description=de, members=me)
return HttpResponseRedirect('/events')
else:
form.fields['members'].queryset = user.get_profile().contacts.all().order_by('first_name')
else:
form = EventForm()
form.fields['members'].queryset = user.get_profile().contacts.all().order_by('first_name')
return render_to_response('add_events.html', {'user': user, 'form': form, 'usp': user.get_profile(), 'contacts_list': contacts_list}, context_instance=RequestContext(request))
楷模:
class EventForm(forms.Form):
name = forms.CharField(max_length=100, required=True)
date = forms.DateField()
description = forms.CharField(max_length=200)
members = forms.ModelMultipleChoiceField(queryset=Profile.objects.all(), widget=forms.CheckboxSelectMultiple)
class Event(models.Model):
user = models.ForeignKey(UserProfile, related_name='event')
members = models.ManyToManyField(Profile)
name = models.CharField(max_length=100)
description = models.CharField(max_length=200)
date = models.CharField(max_length=20)