ModelForm因模型而无法验证.ForeignKey(类别)

时间:2015-07-28 21:31:42

标签: django django-models django-forms

类别字段显示错误:“Façaumaescolhaválida.Suaescolhanãoéumadasdisponíveis”其中翻译为:“做出有效选择。您的选择不是可用的选择”

我也尝试在thread.save()之后添加form.save_m2m(),但它没有效果。

模型

class Thread(models.Model):
    title = models.CharField(max_length=150)
    created = models.DateTimeField(auto_now_add=True)
    creator = models.ForeignKey(User, blank=True, null=True)
    body = models.TextField(max_length=10000)
    category = models.ForeignKey(Category)
    orcamento = models.IntegerField()
    slug = models.SlugField(max_length=40, unique=True)

    def get_absolute_url(self):
        return "/pergunta/%s/" % self.slug

    def __str__(self):
        return self.title

    def save(self, **kwargs):
        slug_str = "%s %s" % (self.category, self.title)
        unique_slugify(self, slug_str)
        super(Thread, self).save(**kwargs)

    def reply_count(self):
        return self.post_set.count()

的ModelForm

class ModelThreadForm(ModelForm):
    class Meta:
        model = Thread
        fields = ['title', 'body', 'category', 'orcamento']
        labels = {
            'title': (''),
            'body': (''),
            'category': (''),
            'orcamento': (''),
        }
        widgets = {
            'title': TextInput(attrs={'class':'form-control', 'placeholder': 'Do que você precisa?', 'required': True}),
            'body': Textarea(attrs={'class':'form-control', 'placeholder': 'Detalhe ao máximo seu caso', 'cols': 60, 'rows': 5, 'required': True}),
            'orcamento': TextInput(attrs={'class':'form-control', 'placeholder': 'Orçamento', 'required': True}),
            'category': SelectMultiple(attrs={'class': 'form-control', 'required': True})
        }

查看

@login_required(login_url='/login/')
def perguntar(request):
    if request.method == 'POST':
        form = ModelThreadForm(request.POST)
        if form.is_valid():
            thread = form.save(commit=False)
            thread.creator = request.user
            thread.save()
            return HttpResponseRedirect(thread.get_absolute_url())
    else:
        form = ModelThreadForm()
    return render(request, 'perguntar.html', {
                               'questionform': form,
    })

模板

        <div id="askQuestion">
            <h2>Faca uma pergunta</h2>
            <form method="post" class="form-horizontal" action="/perguntar/">
                {% csrf_token %}

                        <div class="col-md-7">
                        {{ questionform.title }}
                        {{ questionform.title.errors }}    
                        {{ questionform.body }}
                        {{ questionform.body.errors }}
                        </div>

                        <div class="form-group">
                            <div class="col-sm-4">
                                <div class="input-group">
                                    <div class="input-group-addon">$</div>
                                    <div>{{ questionform.orcamento }}</div>
                                    {{ questionform.orcamento.errors }}
                                    <div class="input-group-addon">,00</div>
                                </div>
                                {{ questionform.category }}
                                {{ questionform.category.errors }}
                                <button type="submit" class="btn btn-primary btn-block">Perguntar</button>
                            </div>
                        </div>
            </form>
        </div>

1 个答案:

答案 0 :(得分:0)

Was using a SelectMultiple widget for a ForeignKey while it should be a Select widget as pointed out by knbk.