Search code examples
djangoformsmodels

Django : Excluded fields are saved


I have a model :

from django.db import models
from tinymce.models import HTMLField

class Team(models.Model):
    name = models.CharField(max_length=100, verbose_name='Team name')
    city = models.CharField(max_length=100, verbose_name='Team city')
    biography = HTMLField(verbose_name='Team biography')
    country = models.ForeignKey('Country')
    slug = models.SlugField(max_length=100)

    def __str__(self):
        return self.name


class Country(models.Model):
    name = models.CharField(max_length=100, verbose_name='Country name')
    code = models.CharField(max_length=5, verbose_name='Country code')

    def __str__(self):
        return self.code

And a form for this model:

from django import forms
from teams.models import Team

class TeamForm(forms.ModelForm):
    class Meta:
        model = Team
        fields = (
            'biography',
            'city',
            'country'
        )

And this is my view:

def add(request):
    if request.method == 'POST':
        form = TeamForm(request.POST)

        if form.is_valid():
            send = True
            form.save()
    else:
        form = TeamForm()
    return render(request, 'teams/add.html', locals())

As you can see, all my model fields are required because I don't add argument 'null' to True in my model attributes. In my ModelForm, for testing, I just specify fields biography, city and country.

But when I fill the form and send-it, data are saved in database, however is missing name and slug....

Why dont i have a django exception ? Thanks for youre help


Solution

  • Neither of those fields are saved as Null, though. They are both character fields (SlugField is a subclass of CharField), and an empty charfield is saved as an empty string - which is perfectly valid from the database point of view.