开发者社区> 问答> 正文

列“user_id”中的空值违反了非空约束Django形式

尝试为用户个人资料页面实现文件上载。我收到以下错误:

列“user_id”中的空值违反非空约束DETAIL:失败行包含(35,profile / {now:%Y /%m / YmdHMSext_xg2iZ6M,null,null)。

我已经读过它可能与User_ID有关,我试过传递form.user = request.user,但是没有用。还有两个空值,而不仅仅是一个空值。

Models.py

class User(AbstractUser):

# First Name and Last Name do not cover name patterns
# around the globe.
name = models.CharField(_('Name of User'), blank=True, 
max_length=255)
#accepted_terms_of_service = models.Booleanfield()

def __str__(self):
    return self.username

def get_absolute_url(self):
    return reverse('users:detail', kwargs={'username': 

self.username})

Profile Image
def upload_to(instance, filename):

now = timezone_now()
base, ext = os.path.splitext(filename)
ext = ext.lower()
return "profile/{now:%Y/%m/%Y%m%d%H%M%S}{ext}"

class Profile(models.Model):

user = models.OneToOneField(settings.AUTH_USER_MODEL, 

on_delete='CASCADE', related_name='user_profile')

school = models.CharField(max_length=30, null=True, blank=True)
image = models.ImageField(_("Picture"), upload_to=upload_to, 

null=True, blank=True)

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

views.py

@login_required
def add_image(request):

 form = ProfileImageForm()
 #form.user = request.user
 if request.method == "POST":
     form = ProfileImageForm(data=request.POST, files=request.FILES)
 if form.is_valid():
     form.save()
     return redirect('userPage')
 else:
     return render(request, "users/user_image_form.html", {"form": form
    })

forms.py

class ProfileImageForm(forms.ModelForm):

class Meta:
    model = Profile
    fields = ["image"]

展开
收起
一码平川MACHEL 2019-01-18 10:15:22 3894 0
1 条回答
写回答
取消 提交回答
  • 我认为没有必要同时拥有Profile Model和Custom User Model。因为,当您自定义用户模型时,为什么不将Profile模型的字段也放到用户模型中。你可以像这样:

    model

    def upload_to(instance, filename):

    now = timezone_now()
    base, ext = os.path.splitext(filename)
    ext = ext.lower()
    return "profile/{now:%Y/%m/%Y%m%d%H%M%S}{ext}"
    

    class User(AbstractUser):

    name = models.CharField(_('Name of User'), blank=True, 
    max_length=255)
    school = models.CharField(max_length=30, null=True, blank=True)
    image = models.ImageField(_("Picture"), upload_to=upload_to, 
                              null=True, blank=True)
    
    def __str__(self):
        return self.username
    
    def get_absolute_url(self):
        return reverse('users:detail', kwargs={'username': 

    self.username})

    views

    @login_required
    def add_image(request):

     form = ProfileImageForm(data=request.POST or None, file=request.FILES or None, instance=request.user)
     if request.method == "POST":
    
        if form.is_valid():
             form.save()
             return redirect('userPage')
    
     return render(request, "users/user_image_form.html", {"form": form
        })
    

    forms.py

    class ProfileImageForm(forms.ModelForm):

    class Meta:
        model = User
        fields = ["image"]
    

    这是因为在您的Profile模型中,您将user列添加为ForeignKey,强制执行NOT NULL以便抛出错误。要解决这个问题,您需要修改add_image类似这样的方法

    @login_required
    def add_image(request):

     form = ProfileImageForm()
     #form.user = request.user
     if request.method == "POST":
         form = ProfileImageForm(data=request.POST, files=request.FILES)
     if form.is_valid():
         form = form.save(commit=False) # change is here
         form.user=request.user.pk # change is here
         form.save()
         return redirect('userPage')
     else:
         return render(request, "users/user_image_form.html", {"form": form

    该request.user.pk值得到,如果您已经登录,但如果你是在您登录需要assisn form.user = your_specified_id其ID存在于User表。如果您的情况是,您是管理员,并且您需要将图像添加到其他用户,因此您需要在add_image方法中传递用户ID 。

    在字段列表中ProfileImageForm.py 添加添加user

    2019-07-17 23:25:48
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载