列中的空值" user_id"违反了非空约束Django

时间:2017-02-01 23:58:09

标签: python django psql

我知道这个问题有很多解决方案,但它们似乎与我的有点不同。这是我的models.py:

from __future__ import unicode_literals

from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.postgres.fields import HStoreField
# Create your models here.

class Events(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    name = models.CharField(max_length=32)
    start = models.CharField(max_length=32)
    end = models.CharField(max_length=32)

非常简单的表,我希望Auth_user中的主键成为Events表中的外键。因此,这当然意味着必须登录User并对其进行身份验证才能正常工作。在我的views.py中,我有:

def createEvent(request):
    if request.method == "POST":
        user = request.user
        print (user)        # Check for Authentication
        name = request.POST['name']
        start = request.POST['start']
        end = request.POST['end']
        Events.objects.create(
            name = name,
            start = start,
            end =end,
        )

print语句将打印出当前登录的用户。我可以确认此部分确实显示用户已登录,并且该用户位于具有唯一auth_user的{​​{1}}表中。但是,当我尝试提交表单时,我会为id列获取空值。有什么想法吗?

3 个答案:

答案 0 :(得分:0)

只需添加用户实例,因为Events需要它。我认为您应该在开始和结束字段中使用DateFieldDateTimeField。不确定,但我认为你打算在那里放一个日期值。


Events.objects.create(user=request.user, name=name, start=start, end=end)

您还应为您的功能添加@login_required

答案 1 :(得分:0)

我的解决方案是:


    from django.contrib.auth.models import User
    user = request.user
    user_id = User.objects.get(username=user).pk
    name = request.POST['name']
    start = request.POST['start']
    end = request.POST['end']
    Events.objects.create(
        user_id=user_id,
        name = name,
        start = start,
        end =end,
    )

这是一个好的解决方案吗?能有更好的东西吗?

答案 2 :(得分:0)

立即制作工作

def createEvent(request):
    if request.method == "POST":
        user = request.user
        print (user)        # Check for Authentication
        name = request.POST['name']
        start = request.POST['start']
        end = request.POST['end']
        # The user has to be included before being saved
        Events.objects.create(name=name, start=start, end=end, user=user)

一些更好的做法: 使用ModelForm(注意class based generic views也可以让这更容易),以及login_required装饰器

# forms.py
from django.forms import ModelForm
from .models import Event

class EventForm(ModelForm):
    class Meta:
        model = Event
        fields = ('user', 'start', 'end', 'name')

# views.py
from django.contrib.auth.decorators import login_required

@login_required
def create_event(request):
    if request.POST:
        form = EventForm(request.POST)
        if form.is_valid():
            form.save()
    else:
        form = EventForm()
        return render(..., {'form': form})