保存django ManyToMany无效

时间:2010-11-15 09:24:50

标签: django django-models django-forms django-orm

我的模型中有一个表格,需要使用ManyToMany字段进行验证和保存。

每当我尝试保存它时,我都会被抛回页面,只是说this field is required

我的models.py

class HuntingReport(models.Model):
    user = models.ForeignKey(User, related_name='User')
    outfitter = models.ForeignKey(User, related_name='Outfitter', null=True, blank=True)
    date_travel_started = models.DateField(blank=True, null=True)
    date_travel_ended = models.DateField(null=True, blank=True)
    title = models.CharField(max_length=50)
    report = models.TextField()
    wish_list = models.ManyToManyField(Specie)
    bag_list = models.ManyToManyField(Trophies)

    def __unicode__(self):
        return self.title

我的forms.py看起来如下

class HuntingReportForm(ModelForm):
    date_travel_started = forms.DateField(widget=extras.SelectDateWidget(years=range(1970,2010)))
    date_travel_ended = forms.DateField(widget=extras.SelectDateWidget(years=range(1970,2010)))
    wish_list = forms.ModelMultipleChoiceField(queryset=Specie.objects.all(), widget=FilteredSelectMultiple("verbose name", is_stacked=False))
    bag_list = forms.ModelMultipleChoiceField(queryset=Trophies.objects.all(), widget=FilteredSelectMultiple("verbose name", is_stacked=False))

    class Meta:
        model = HuntingReport
        exclude = ['user']

    def __init__(self, user, *args, **kwargs):
        super(HuntingReportForm, self).__init__(*args, **kwargs)

        users = User.objects.filter(userprofile__outfitter=True)
        self.fields['outfitter'].choices = [('', '')] + [(user.pk, user.get_full_name()) for user in users]

my views.py

def create(request, template_name='reports/new.html'):
    if request.method == 'POST':
        form = HuntingReportForm(request.POST, request.FILES)
        if form.is_valid():
            newform = form.save(commit=False)
            newform.user = request.user
            newform.save_m2m()
            return HttpResponseRedirect('/hunting-reports/')
    else:
        form = HuntingReportForm(request.user)

    context = { 'form':form, }

    return render_to_response(template_name, context,
        context_instance=RequestContext(request))

1 个答案:

答案 0 :(得分:1)

您是否尝试将blank=True传递给模型字段的构造函数,或required=False传递给ModelMultipleChoiceField的构造函数?

我知道blank=True解决了管理面板中表单的问题,但我不知道它是如何映射到ModelForm的字段的。我假设它被映射到required属性。