I had my form set up and working with no errors, but after I added an IntegerFIeld with a RadioSelect widget the form no longer validates. (Before this I only had CharFields in the model and no widgets)
I've searched other similar questions but haven't been able to find anything to solve this issue.
At present I just keep getting the error message I coded in views.py.
My set up is as follows:
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
Many thanks in advance.
FORM_CHOICES
are strings. So you can't expect an IntegerField
to validate with these choices.
FORM_CHOICES
to int values (e.g. (1, 'very bad'), (2, 'bad')...) IntegerField
to a CharField
.