Django ModelForm没有保存在db上创建帖子的用户

时间:2017-01-30 22:26:20

标签: python django django-forms django-views django-1.10

这是一个Django初学者,在表单工作方面遇到了很多麻烦。我尝试过不同的方法,但我无法将用户保存在数据库中。我收到这个错误:

  

/ n_post /的IntegrityError   NOT NULL约束失败:learning_logs_post.owner_id“

views.py:

def nuovo_post(request):
    if request.method != 'POST':
        # No data submitted; create a blank form.
        form = PostForm()
    else:
        # POST data submitted; process data.
        form = PostForm(request.POST)
        if form.is_valid():
            n_post = form.save(commit=False)
            n_post.owner = request.user
            n_post.save()
            return HttpResponseRedirect(reverse('learning_logs:posts'))
    context = {'form': form}
    return render(request, 'learning_logs/nuovo_post.html', context)

models.py:

class Post(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField()
    image = models.ImageField(blank=True)
    date_added = models.DateTimeField(auto_now_add=True)
    owner = models.ForeignKey(User)

forms.py:

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['title', 'description', 'image']
        labels = {'title': "Title", 'description': "Description"}
        widgets = {'description': forms.Textarea(attrs={'cols': 80})}

urls.py:

urlpatterns = [
# Home Page [[ ^$ = stringa vuota ]]
url(r"^$", views.index, name="index"),
url(r"^servizi/$", views.servizi, name="servizi"),


url(r"^catering/$", views.catering, name="catering"),
url(r"^eventi_degustazioni/$", views.eventi_degustazioni, name="eventi_degustazioni"),
url(r"^academy/$", views.academy, name="academy"),

url(r"^corsi/$", views.corsi, name="corsi"),
url(r'^corsi/(?P<corso_id>\d+)/$', views.corso, name='corso'),


url(r"^shop/$", views.shop, name="shop"),
url(r"^chi_siamo/$", views.chi_siamo, name="chi_siamo"),
url(r"^lavora_con_noi/$", views.lavora_con_noi, name="lavora_con_noi"),


url(r"^spazio_utenti/$", views.spazio_utenti, name="spazio_utenti"),
url(r'^posts/$', views.post, name="posts"),
url(r'^posts/(?P<post_id>\d+)/$', views.post, name='post'),
url(r'^nuovo_post/$', views.nuovo_post, name="nuovo_post"),
url(r'^modifica_post/(?P<post_id>\d+)/$', views.modifica_post, name='modifica_post'),

] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

1 个答案:

答案 0 :(得分:1)

用户未登录您的网站时。 request.userAnonymousUser的一个实例。此实例没有id。因此,模型中的owner_id字段变为null,数据库约束不允许这样做。尝试这样的事情:

def nuovo_post(request):

    if request.user.is_authenticated():
        if request.method != 'POST':
            # No data submitted; create a blank form.
            form = PostForm()
        else:
            # POST data submitted; process data.
            form = PostForm(request.POST)
            if form.is_valid():
                n_post = form.save(commit=False)
                n_post.owner = request.user
                n_post.save()
                return HttpResponseRedirect(reverse('learning_logs:posts'))
        context = {'form': form}
        return render(request, 'learning_logs/nuovo_post.html', context)
    else :
        return HttpResponseRedirect('/login/')

注意重定向到相应的登录网址

  

/ n_post / NOT NULL约束中的IntegrityError失败:   learning_logs_post.owner_id

对于您提出的问题,这个答案基本上是正确的。但是您的更新显示您的错误与您发布的代码无关。 (此代码会产生相同的错误,但您看到的错误是其他地方的类似代码。)

以下行显示nuovu_post未映射到错误中的网址。

url(r'^nuovo_post/$', views.nuovo_post, name="nuovo_post"),