保存 django ManyToMany 无效

发布于 2024-10-03 01:11:39 字数 2193 浏览 3 评论 0原文

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

每次我尝试保存它时,我都会被扔回页面,只是说此字段是必需的

我的 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]

我的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))

I have a form from my model that needs to be validated and saved making use of ManyToMany Fields.

Everytime I try and save it, I get thrown back to the page, just saying this field is required

My 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

My forms.py looks as follows

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

昔梦 2024-10-10 01:11:39

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

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

Did you try passing blank=True for model field's constructor, or required=False for the ModelMultipleChoiceField's constructor?

I know that blank=True solves the problem for the form in the admin panel, but I don't know how it gets mapped to the ModelForm's fields. I'm assuming that it gets mapped to required property.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文