Heisenberg
Heisenberg

Reputation: 495

Django Error: "You are trying to add a non-nullable field 'author' to entry without a default"

I was trying to make migrations after adding an author field in my models.py file but Django asked me this:

You are trying to add a non-nullable field 'author' to entry without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
 2) Quit, and let me add a default in models.py

My Models.py File:

from django.db import models
from django.utils import timezone
from django.urls import reverse
from django.contrib.auth.models import User


class Entry(models.Model):
    title = models.CharField(max_length=50, default=timezone.now)
    date = models.DateTimeField(default=timezone.now)
    content = models.TextField()
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def get_absolute_url(self):
        return reverse('diary:index')

    def __str__(self):
        return self.title

I wanted to add the user who's currently active as the author, so I did this on my views.py file:

class EntryCreate(CreateView):
    model = Entry
    fields = ['title', 'content']

    def form_valid(self, form):
        form.instance.author = self.request.author
        return super().form_valid(form)

What Should I Do To Avoid This?

Thanks In Advance!

Upvotes: 1

Views: 9176

Answers (2)

Manuel Minguez
Manuel Minguez

Reputation: 31

This may be due to the migrations you already have in your project. If you don't mind deleting some previous migrations I suggest you delete the migration where you create the Author model and all the following ones. After deleting the local database, you can do a makemigrations and migrate without having to set a default value.

Obviously, this approach is not feasible if you don't want to delete the database or if you do want to delete migrations.

Upvotes: -1

add a default=None to your author

Upvotes: 10

Related Questions