我尝试通过其URL获取图像并将其保存到数据库但是我在/ images / create /中得到 IntegrityError - NOT NULL约束失败:images_image.user_id 向我抛出。以下是可能涉及的文件
models.py
(包含覆盖save()
方法的代码,以根据slug
字段的值自动生成title
字段
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})
怎么了?请有人帮忙
答案 0 :(得分:1)
我觉得你在import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class fileToMatrix {
public static void main(String[] args) throws IOException {
File f = new File("./src/floatMat.txt");
Scanner s = null;
int m=-1;
float value = -0.1f;
try {
s = new Scanner(f);
if(s.hasNextLine()) { // Firstly, read the dimension number
m = s.nextInt();
System.out.println("Dimension of the matrix = " + m + "x" + m);
}
float [][] mat = new float[m][m]; //creates a matrix of dimension m
for(int i=0; i< m; i++){ //and initializes to 0
for(int j=0; j< m; j++){
mat[i][j] = 0.0f;
}
}
if(s.hasNextLine()) {
for(int r=0; r< m; r++){
for(int c=0; c< m; c++){
value = s.nextFloat(); //PROBABLY HERE'S THE MISTAKE!!!!!
mat[r][c] = value; //set value on the current cell of the array
}
}
}
for(int i=0; i< m; i++){ //print the matrix
for(int j=0; j< m; j++){
System.out.print(mat[i][j]+ " ");
}
System.out.println();
}
} catch (Exception ex) {
System.out.println("Message catch: " + ex.getMessage());
} finally {
if (s != null)
s.close();
}
}
}
方法中遇到麻烦,当你试图保存图片时,django需要保存实例,所以你有错误,我的解决方案是添加用户来形成数据:
表格
save
在视图中
class ImageCreateForm(forms.ModelForm):
class Meta:
model = Image
fields = ('title', 'url', 'description', 'user')
widgets = {
'url': forms.HiddenInput,
'user': forms.HiddenInput,
}