我设置了表单并且没有错误,但在我添加了一个带有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
非常感谢提前。
答案 0 :(得分:1)
FORM_CHOICES
是字符串。因此,您不能指望IntegerField
使用这些选项进行验证。
FORM_CHOICES
更改为int值(例如(1,'非常糟糕'),(2,'糟糕')......)IntegerField
更改为CharField
。