Django给出" IntegrityError NOTNULL约束失败"提交django表单数据时

时间:2016-06-30 04:48:49

标签: django forms

我在django中创建一个简单的webapp,用户可以登录,选择一个给定的类别并在所选类别下发布文章。但是当我提交我的django表单以创建一个新帖子时,它会让我感到兴奋。 IntegrityError NOTNULL约束失败"。我在互联网上搜索了很多解决方案并实现了相同但仍然给了我同样的错误。

请帮我解决一下我如何解决这个问题?

以下是代码段:

Models.py

class  Category(models.Model):

    name = models.CharField(max_length=128,unique=True)
    slug = models.SlugField()
    def save(self,*args,**kwargs):
        self.slug = slugify(self.name)
        super(Category,self).save(*args,**kwargs)

    def __unicode__(self):

        return self.name

class Post(models.Model):
    category = models.ForeignKey(Category,null=True,blank=True)
    title = models.CharField(max_length=128,null=True,blank=True)
    content = models.TextField(blank=True,null=True)    


    def __unicode__(self):

        return self.title

views.py

def index(request):

    category_list = Category.objects.all()
    context = {'category_list':category_list}

    return render(request,'index.html',context)

def category(request,category_name_slug):

    context = {}
    try:
        category = get_object_or_404(Category,slug=category_name_slug)
        context['category_name'] = category.name

        post = Post.objects.filter(category=category)   
        context['post'] = post
        context['category'] = category
        context['category_name_slug'] = category_name_slug
    except Category.DoesNotExist:
        pass

    return render(request,'category.html',context)

@login_required     
def create_post(request,category_name_slug):

    created = False
    instance = get_object_or_404(Category,slug=category_name_slug)
    a = Post(category=instance)
    if request.method == 'POST':
        form = PostForm(request.POST,instance=a)
        if form.is_valid():
            post = form.save(commit=False)
            post.save()
            created = True
        else:
            print form.errors
    else:
        form = PostForm()
    context={
        'form':form,
        'instance':instance,        
        'created':created
    }
    return render(request,"add_post.html",context)

forms.py

from django import forms
from app.models import Post,Category,UserProfile
from django.contrib.auth.models import User 

class CategoryForm(forms.ModelForm):
    name = forms.CharField(max_length=128, help_text="Please enter category")
    slug = forms.CharField(widget=forms.HiddenInput(), required=False)

    class Meta:
        model = Category
        fields = ('name',)

class PostForm(forms.ModelForm):
    title = forms.CharField(max_length=128)
    content = forms.CharField(widget=forms.Textarea)
    class Meta:
        model = Post
        fields = ('title','content')

        exclude = ('category',)

urls.py

from django.conf.urls import url
from django.contrib import admin
from app import views

urlpatterns = [
        url(r'^$',views.index,name='index'),
        url(r'^about/$',views.about,name='about'),
        url(r'^add_category/$',views.add_category,name="add_category"),
        url(r'^category/(?P<category_name_slug>[-\w]+)/create_post/$',views.create_post, name='create_post'),
        url(r'^category/(?P<category_name_slug>[-\w]+)/$',views.category, name='category'),
        url(r'^(?P<id>\d+)/$',views.post_detail,name='post'),
        url(r'^register/$',views.register,name="register"),
        url(r'^login/$',views.user_login,name="login"),
        url(r'^logout/$',views.user_logout,name="logout"),
        url(r'^(?P<username>[-\w]+)/$',views.view_profile,name="profile"),

模板/ add_post.html

<html>
<head>
    <title>Create Post</title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">

    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"                   integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
</head>
<body>
    <h1>Create Post under {{ instance.name }}</h1>
        {% if created %}
            <strong>Post created successfully</strong>
            <a href='/app/'>Home</a>
        {% else %}
        <form id='post_form' method='post' action='/app/category/{{ instance.slug }}/create_post/' enctype='multipart/form-data'>
            {% csrf_token %}
            {{ form.as_p }}
            <input type="submit" name="submit" value="Create Post" />
        </form>
        {% endif %}
</body>
</html>

模板/ category.html

<!DOCTYPE html>
<html>
    <head>
        <title>App</title>
        <!-- Latest compiled and minified CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

        <!-- Optional theme -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">

        <!-- Latest compiled and minified JavaScript -->
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"                   integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
    </head>

    <body>
        {% if category %}
        <h1>{{ category_name }}</h1>
            {% if post %}
            <ul>
                {% for poste in post %}
                    <li>{{ poste.title }}</li>
                {% endfor %}
            </ul>
            {% else %}
                <strong>No posts in this Category</strong>
            {% endif %}
        {% else %}
            <strong>No Category found with {{ category_name }}</strong>
        {% endif %}
        <a href='/app/category/{{ category.slug }}/create_post/'>Create post</a>

    </body>
</html>

它在&#34; post.save()&#34; views.py。中的行。

0 个答案:

没有答案