使用 Radio Widget 添加 IntegerField 后,Django 表单验证不起作用

Django form validation not working after adding IntegerField with Radio Widget

我已经设置了我的表单并且没有错误,但是在我添加了一个带有 RadioSelect 小部件的 IntegerFIeld 之后,表单不再有效。 (在此之前我的模型中只有 CharFields 而没有小部件)

我已经搜索了其他类似的问题,但未能找到解决此问题的方法。

目前我只是不断收到我在 views.py 中编码的错误消息。

我的设置如下:

views.py

from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.utils import timezone
from .forms import DiaryEntryForm
from .models import DiaryEntry

def new_entry(request):
    if request.method == "POST":
        form = DiaryEntryForm(request.POST)
        if form.is_valid():
            entry = form.save(commit=False)
            entry.author = request.user
            entry.created_date = timezone.now()
            entry.save()
            messages.success(request, "Entry created successfully")
            return redirect(entry_detail, entry.pk)
        else:
            messages.error(request, "There was an error saving your entry")            
            return render(request, 'diaryentryform.html', {'form': form})
    else:
        form = DiaryEntryForm()
        return render(request, 'diaryentryform.html', {'form': form})

forms.py

from django import forms
from .models import DiaryEntry, FORM_CHOICES


class DiaryEntryForm(forms.ModelForm):
    body = forms.ChoiceField(widget=forms.RadioSelect(),choices=FORM_CHOICES)
    mind = forms.ChoiceField(widget=forms.RadioSelect(),choices=FORM_CHOICES)

    class Meta:
        model = DiaryEntry        
        fields = ('body', 'mind', 'insights')

models.py

from __future__ import unicode_literals

from django.db import models
from django.utils import timezone
from django.conf import settings
from django import forms

# Create your models here.

FORM_CHOICES = [
    ('very bad', 'very bad'),
    ('bd', 'bad'),
    ('OK', 'OK'),
    ('good', 'good'),
    ('very good', 'very good'),
]

class DiaryEntry(models.Model):
    """
    Define the diary entry model here
    """

    author = models.ForeignKey(settings.AUTH_USER_MODEL) # link author to the registered user
    title = models.CharField(max_length=200) # set this to be the date later on
    created_date = models.DateTimeField(auto_now_add=True)
    body = models.IntegerField(blank=True, null=True, choices=FORM_CHOICES)
    mind = models.IntegerField(blank=True, null=True, choices=FORM_CHOICES)
    insights = models.TextField()

    def publish(self):
        self.save()

    def __unicode__(self):
        return self.title

非常感谢。

FORM_CHOICES 是字符串。所以你不能指望 IntegerField 来验证这些选择。

  • 要么将您的 FORM_CHOICES 更改为整数值(例如 (1, 'very bad'), (2, 'bad')...)
  • 或者将模型的 IntegerField 更改为 CharField