简体   繁体   English

Django:NOT NULL 约束失败:wishlist_wish.user_id

[英]Django: NOT NULL constraint failed: wishlist_wish.user_id

I have a wishlist app with a custom user model.我有一个带有自定义用户 model 的愿望清单应用程序。 I added the user as the foreign key to each wishlist item.我将用户添加为每个愿望清单项目的外键。 However, I am only able to add the foreign key by specifying a default user, even after deleting the existing db files and running makemigrations and migrate.但是,我只能通过指定默认用户来添加外键,即使在删除现有的 db 文件并运行 makemigrations 和 migrate 之后也是如此。 The default user is associated with the wishlist item regardless of which user is logged in, and if I don't include a default user I get the "NOT NULL constraint failed: wishlist_wish.user_id" error.无论哪个用户登录,默认用户都与愿望清单项目相关联,如果我不包括默认用户,我会收到“NOT NULL 约束失败:wishlist_wish.user_id”错误。

How can I update the code so that the wishlist item is associated with the logged-in user creating the item?如何更新代码以使愿望清单项目与创建项目的登录用户相关联?

A related question is whether I need to include a user id in my custom user model?一个相关的问题是我是否需要在我的自定义用户 model 中包含用户 ID? I tried doing this as well and ran into the same problem.我也尝试过这样做并遇到了同样的问题。 Thanks in advance.提前致谢。

Wish Model:希望Model:

class Wish(models.Model):
    name = models.TextField()
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1)

    def __str__(self):
        return self.name

Wish View:愿望视图:

def add_wish(request):

    user = request.user
    wishes = Wish.objects.filter(user=request.user)

    if request.method == 'POST':
        form = WishForm(request.POST)

        if form.is_valid():
            form.save()
            return redirect('home')
    else:
        form = WishForm()

    context = {'form' : form, 'wishes' : wishes}
    return render(request, 'wishlist/add_wish.html', context)

Wish Form:愿望形式:

class WishForm(ModelForm):
    class Meta:
        model = Wish
        fields = ('name', )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['name'].widget.attrs.update({'class' : 'textarea', 'placeholder' : 'Enter wishlist item'})

Custom User (Account) Model:自定义用户(帐户)Model:

class MyAccountManager(BaseUserManager):
    def create_user(self, email, username, first_name, last_name, password=None):
        if not email:
            raise ValueError("Users must provide an email to create an account.")
        if not first_name:
            raise ValueError("Users must provide full name to create an account.")
        if not last_name:
            raise ValueError("Users must provide full name to create an account.")

        user =  self.model(
                email = self.normalize_email(email),
                username = username,
                first_name = first_name,
                last_name = last_name,
            )

        user.set_password(password)
        user.save(using=self._db)
        return user
    
    def create_superuser(self, email, username, first_name, last_name, password):
        user =  self.create_user(
                email = self.normalize_email(email),
                username = username,
                first_name = first_name,
                last_name = last_name,
                password = password
            )
        user.is_admin = True
        user.is_staff = True
        user.is_superuser = True
        user.save(using=self._db)
        return user


class Account(AbstractBaseUser):
    email = models.EmailField(max_length=100, unique=True)
    username = models.CharField(max_length=100, unique=False, blank=True, null=True)
    date_joined = models.DateTimeField(auto_now_add=True)
    last_login = models.DateTimeField(auto_now=True)
    is_admin = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username', 'first_name', 'last_name']

    objects = MyAccountManager()

    def __str__(self):
        return self.first_name + " " + self.last_name

    def has_perm(self, perm, obj=None):
        return self.is_admin

    def has_module_perms(self, app_label):
        return True

You simply need to provide a value for the .user for the Wish you are creating:您只需为您正在创建的Wish提供.user的值:

from django.contrib.auth.decorators import login_required

@login_required
def add_wish(request):
    wishes = Wish.objects.filter(user=request.user)

    if request.method == 'POST':
        form = WishForm(request.POST)

        if form.is_valid():
            form.instance.user = requst.user
            form.save()
            return redirect('home')
    else:
        form = WishForm()

    context = {'form' : form, 'wishes' : wishes}
    return render(request, 'wishlist/add_wish.html', context)

Note : You can limit views to a view to authenticated users with the @login_required decorator [Django-doc] .注意:您可以使用@login_required装饰器 [Django-doc]将视图限制为经过身份验证的用户的视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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