gpt4 book ai didi

python - IntegrityError at/images/create/- NOT NULL 约束失败 : images_image. user_id

转载 作者:太空宇宙 更新时间:2023-11-03 14:47:39 24 4
gpt4 key购买 nike

我尝试通过其 URL 获取图像并将其保存到数据库,但我收到 IntegrityError at/images/create/- NOT NULL 约束失败:images_image.user_id 抛出给我。以下是可能涉及的文件

models.py

(包含重写 save() 方法的代码,以根据 title 字段的值自动生成 slug 字段)

from django.db import models
from django.conf import settings
from django.utils.text import slugify

class Image(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='images_created')
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, blank=True)
url = models.URLField()
image = models.ImageField(upload_to='images/%Y/%m/%d')
description = models.TextField(blank=True)
created = models.DateField(auto_now_add=True, db_index=True)
users_like = models.ManyToManyField(settings.AUTH_USER_MODEL,
related_name='images_liked', blank=True)

def __str__(self):
return self.title

def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Image, self).save(*args, **kwargs)

forms.py

(包含重写 save() 方法以检索给定图像并保存它的代码)

from urllib import request
from django import forms
from django.core.files.base import ContentFile
from django.utils.text import slugify
from .models import Image

class ImageCreateForm(forms.ModelForm):
class Meta:
model = Image
fields = ('title', 'url', 'description')
widgets = {
'url' : forms.HiddenInput,
}

def clean_url(self):
url = self.cleaned_data['url']
valid_extensions = ['jpg', 'jpeg']
extension = url.rsplit('.', 1)[1].lower()
if extension not in valid_extensions:
raise forms.ValidationError('the given URL doesn\'t match valid image extensions')
return url

def save(self, force_insert=False, force_update=False, commit=True):
image = super(ImageCreateForm, self).save(commit=False)
image_url = self.cleaned_data['url']
image_name = '{}.{}'.format(slugify(image.title),
image_url.rsplit('.', 1)[1].lower())

# Download image from given URL
response = request.urlopen(image_url)
image.image.save(image_name, ContentFile(response.read()))

if commit:
image.save()
return image

views.py

from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .forms import ImageCreateForm

@login_required
def image_create(request):
if request.method == 'POST':
# Form is sent
form = ImageCreateForm(data=request.POST)
if form.is_valid():
# Form data is valid
cd = form.cleaned_data
new_item = form.save(commit=False)

# Assign current user to the item
new_item.user = request.user
new_item.save()
messages.success(request, 'Image added successfully')

# Redirect to the newly created item detail view
return redirect(new_item.get_absolute_url())
else:
# Build form with data provided by the bookmarklet via GET
form = ImageCreateForm(data=request.GET)

return render(request, 'images/image/create.html',
{'section' : 'images', 'form' : form})

怎么了?请有人帮忙

最佳答案

我认为你在表单save方法中遇到麻烦,当你尝试保存图像时,django需要保存实例,所以你有一个错误,我的解决方案是将用户添加到表单数据:

以表格形式

class ImageCreateForm(forms.ModelForm):
class Meta:
model = Image
fields = ('title', 'url', 'description', 'user')
widgets = {
'url': forms.HiddenInput,
'user': forms.HiddenInput,
}

在 View 中

# Form is sent
data = request.POST.copy()
data.update({'user': request.user.pk })
form = ImageCreateForm(data=data)
if form.is_valid():
# Form data is valid
new_item = form.save()
messages.success(request, 'Image added successfully')
# Redirect to the newly created item detail view
return redirect(new_item.get_absolute_url())

关于python - IntegrityError at/images/create/- NOT NULL 约束失败 : images_image. user_id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46125974/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com