简体   繁体   中英

IntegrityError NOT NULL constraint failed

I'm building a simple blog app using Django. I want to realize the function of adding a new blog using form. Some problems occurs.

Here is my models.py

from django.db import models
from django.utils import timezone
from django.template.defaultfilters import slugify
from django.contrib.auth.models import User

class Blog(models.Model):
    title=models.CharField(max_length=60)
    content=models.TextField()
    author=models.ForeignKey('auth.User',on_delete=models.CASCADE,)
    date=models.DateTimeField(default=timezone.now)
    slug=models.SlugField(null=True,unique=True)

    def save(self, *args, **kwargs):
      self.slug = slugify(self.title)
      super(Blog, self).save(*args, **kwargs)

    def __str__(self):
        return self.title

class UserProfile(models.Model):
    user=models.OneToOneField(User)
    website=models.URLField(blank=True)

    def __str__(self):
        return self.user.username   

forms.py

 from django.template.defaultfilters import slugify
 from blog.models import UserProfile
 from django.contrib.auth.models import User

 class BlogForm(forms.ModelForm):
     title=forms.CharField(max_length=60,
                      help_text="blog title")
     content=forms.CharField(help_text="blog content")
     author=forms.CharField(help_text="blog author")
     date=forms.DateTimeField(help_text="blog date")

     class Meta:
         model=Blog
         fields=('title',)
 class UserForm(forms.ModelForm):
     password = forms.CharField(widget=forms.PasswordInput())

     class Meta:
         model=User
         fields = ('username','email','password')
 class UserProfileForm(forms.ModelForm):
     class Meta:
         model=UserProfile
         fields=('website',)

the add_blog method in views.py

def add_blog(request):    
form=BlogForm()    
if request.method =='POST':
    form=BlogForm(request.POST)
    if form.is_valid():
        form.save(commit=True)
        return index(request)
    else:
        print(form.errors)

return render(request, 'add_blog.html',{'form':form})

When I want to add a new blog in my webpage, I can't input the record. It shows me

IntegrityError at /add_blog/
NOT NULL constraint failed: blog_blog.author_id

Could anybody help me fix this problem? Thanks a lot!

In your models, your Blog class requires:

  1. Title
  2. An author, of type auth.User
  3. content

The first step, is to remove the author field from your form:

class BlogForm(forms.ModelForm):
     title=forms.CharField(max_length=60,
                      help_text="blog title")
     content=forms.CharField(help_text="blog content")
     # author=forms.CharField(help_text="blog author")
     date=forms.DateTimeField(help_text="blog date")

     class Meta:
         model=Blog
         fields=('title','content','date')

Next, is to add the logged in user as the author in your view:

from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required

# makes sure this view is called with a valid user
# https://docs.djangoproject.com/en/2.0/topics/auth/default/#the-login-required-decorator
@login_required
def add_blog(request):    
   form = BlogForm(request.POST or {})    
   if form.is_valid():
        temp = form.save(commit=False)
        temp.author = request.user # add the logged in user, as the
                                   # author
        temp.save()
        return redirect('/')
   return render(request, 'add_blog.html',{'form':form})

Another way to view this problem... Perhaps you can Try clearing your migration files , and re-run makemigrations to see if it catches anything off about your models. It may ask you for a default value for some of the fields; and this should ring a bell to assign null=True where appropriate. Personally this is quite a common integrity conflict for me (i'm new to the framework) especially when i've done many unplanned on the fly mods to models on the same db.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM