我想要完成的是获取图片并从网址创建缩略图。但 我一直收到这个错误: / link /'LinkForm'对象的AttributeError没有属性'url'我不知道如何解决这个问题。 PS。我是django和python的新手。
models.py
def upload_location(instance, filename):
return('{}/{}').format(instance.id, filename)
class Link(models.Model):
title = models.CharField("Headline", max_length=100)
submitter = models.ForeignKey(settings.AUTH_USER_MODEL)
submitted_on = models.DateTimeField(auto_now_add=True)
rank_score = models.FloatField(default=0.0)
url = models.URLField("URL", max_length=250, unique=True)
description = models.TextField(blank=True)
slug = models.SlugField(unique=True)
image_file = models.ImageField(upload_to=upload_location, blank=True)
with_votes = LinkVoteCountManager()
objects = models.Manager()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('link:link_detail', kwargs={"slug": self.slug,
'pk': str(self.id)
})
def get_remote_image(self):
if self.url and not self.image_file:
result = urllib.request.urlretrieve(self.url)
self.image_file.save(
os.path.basename(self.url),
File(open(result[0]))
)
self.save()
views.py
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView
from .models import Link, Vote
from .forms import LinkForm
from django.shortcuts import get_object_or_404
import uuid, requests
from PIL import Image
from django.core.files import File
fixed_width = 256
get_size = lambda width, height: (fixed_width, height*fixed_width/width)
class LinkListView(ListView):
model = Link
queryset = Link.with_votes.all()
paginate_by = 5
class LinkDetailView(DetailView):
model = Link
class LinkCreateView(CreateView):
model = Link
form_class = LinkForm
def form_valid(self, form):
hash = str(uuid.uuid1())
with open("tmp_img_original_{}.png".format(hash), "wb") as f:
res = requests.get(form.url, stream=True) #Code working until this line
if not res.ok: raise Exception("URL'de dosya yok: 404")
for block in res.iter_content(1024): f.write(block)
img = Image.open(f
width, height = img.size
img.thumbnail(get_size(width, height), Image.ANTIALIAS)
img.save()
djfile = File(f)
form.img.save("img_tn_{}.png".format(hash), djfile, save=True)
f.close()
f = form.save(commit=False)
f.rank_score = 0.0
f.submitter = self.request.user
f.save()
return super(CreateView, self).form_valid(form)
forms.py
from django import forms
from .models import Link
import requests
class LinkForm(forms.ModelForm):
url = forms.URLField()
img = forms.ImageField(required=False)
class Meta:
model = Link
exclude = ('submitter', 'rank_score')
fields = [
'title',
'url',
'description'
]
答案 0 :(得分:0)
您应该通过form.instance
访问该表单:
res = requests.get(form.instance.url, stream=True)