我对Django和Python都很新。这是我第一次使用表单并使用django上传文件。我可以将上传和保存到数据库中工作正常,但无法验证电子邮件或检查用户是否选择了要上载的文件。我花了很多时间阅读文档试图解决这个问题。谢谢!
views.py
def submit_photo(request):
if request.method == 'POST':
def store_in_s3(filename, content):
conn = S3Connection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
bucket = conn.create_bucket(AWS_STORAGE_BUCKET_NAME)
mime = mimetypes.guess_type(filename)[0]
k = Key(bucket)
k.key = filename
k.set_metadata("Content-Type", mime)
k.set_contents_from_file(content)
k.set_acl('public-read')
if imghdr.what(request.FILES['image_url']):
qw = request.FILES['image_url']
filename = qw.name
image = filename
content = qw.file
url = "http://bpd-public.s3.amazonaws.com/" + image
data = {image_url : url, user_email : request.POST['user_email'], user_twittername : request.POST['user_twittername'], user_website : request.POST['user_website'], user_desc : request.POST['user_desc']}
s = BeerPhotos(data)
if s.is_valid():
#import pdb; pdb.set_trace()
s.save()
store_in_s3(filename, content)
return HttpResponseRedirect(reverse('photos.views.thanks'))
return s.errors
else:
return errors
else:
form = BeerPhotoForm()
return render_to_response('photos/submit_photos.html', locals(),context_instance=RequestContext(request)
forms.py
class BeerPhotoForm(forms.Form):
image_url = forms.ImageField(widget=forms.FileInput, required=True,label='Beer',help_text='Select a image of no more than 2MB.')
user_email = forms.EmailField(required=True,help_text='Please type a valid e-mail address.')
user_twittername = forms.CharField()
user_website = forms.URLField(max_length=128,)
user_desc = forms.CharField(required=True,widget=forms.Textarea,label='Description',)
template.html
<div id="stylized" class="myform">
<form action="." method="post" enctype="multipart/form-data" width="450px">
<h1>Photo Submission</h1>
{% for field in form %}
{{ field.errors }}
{{ field.label_tag }} {{ field }}
{% endfor %}
<label><span>Click here</span></label>
<input type="submit" class="greenbutton" value="Submit your Photo" />
</form>
</div>
答案 0 :(得分:0)
我认为问题在于您使用forms.ImageField()
来验证网址。您可能希望使用forms.UrlField()
。
或者
你根本不应该将url传递给文件。相反,您可以执行s = BeerPhoto(request.POST, request.FILES)
并在运行s.is_valid()
http://docs.djangoproject.com/en/dev/topics/http/file-uploads/