I have a model Books with one field 'name' and i have set max_length to 10.
class Books(models.Model):
name = models.CharField(max_length=10)
However, in the modelform BookForm i have defined the max_length to 20.
class BookForm(forms.ModelForm):
name = forms.CharField(max_length=20)
class Meta:
fields = ['name']
model = Books
Now while submitting the form with more than 10 length it gives me error saying that the field can at most 10 characters.
def book(request):
if request.method == 'POST':
fm = BookForm(data=request.POST)
print(fm.is_valid())
print(fm)
if fm.is_valid():
fm.save()
return render(request, 'enroll/books.html', {'form':fm})
fm = BookForm()
return render(request, 'enroll/books.html', {'form':fm})
enter image description here Can anyone explain why this is happening and any specific article or link where i can read how the model form and models work with each other in terms of validation.
CodePudding user response:
The model form will automatically define the fields based on your Model and its constraints. Since you have defined a name field with max_length validation in Model, you don't require to give it in the form.
class BookForm(forms.ModelForm):
class Meta:
fields = ['name']
model = Books