how to download BinaryField Data/file using template. like we did for FileField.
<td><a href={{certificate.bytes.url}} download></a>
I past all url.py and view.py file below please look This may give extract view of my code. and please help me with this i am new to Django. ............................................................................................................................................................
url.py
from django.conf.urls.static import static
from django.conf.urls import url
from django.views.defaults import page_not_found
urlpatterns=[
path('',views.index, name = 'index'),
url(r'^list/$', views.list, name='list'),
url(r'^list/create$', views.certificate_create, name='certificate_create'),
url(r'^list/(?P<id>\d+)/update$', views.certificate_update, name='certificate_update'),
url(r'^list/(?P<id>\d+)/delete$', views.certificate_delete, name='certificate_delete'),
path('download',views.download, name = 'download'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
So, we need Django models which contains BinaryField for example.
models.py
class Person(models.Model):
name = models.CharField(max_length=55)
surname = models.CharField(max_length=55)
image = models.BinaryField()
class Meta:
db_table = 'person'
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('download/<int:pk>/', views.download, name='download'),
]
views.py
import io
from django.shortcuts import render
from django.http import FileResponse
from .models import Person
def index(request):
# there are listed all models.
persons = Person.objects.all()
return render(request, 'index.html', {'persons': persons})
def download(request, pk):
# this url is for download
try:
obj = Person.objects.get(pk=pk)
except Person.DoesNotExist as exc:
return JsonResponse({'status_message': 'No Resource Found'})
get_binary = obj.image
if get_binary is None:
return JsonResponse({'status_message': 'Resource does not contian image'})
if isinstance(get_binary, memoryview):
binary_io = io.BytesIO(get_binary.tobytes())
else:
binary_io = io.BytesIO(get_binary)
response = FileResponse(binary_io)
response['Content-Type'] = 'application/x-binary'
response['Content-Disposition'] = 'attachment; filename="{}.png"'.format(pk) # You can set custom filename, which will be visible for clients.
return response
index.html
{% for person in persons %}
{{ person.name }}<br />
{% endfor %}
This is solution to send binary file from server and download. All components are shown. Good luck !
Related
my project was running ok I used my admin page at it was all all right today I tried to open it and it gives a Page not found (404)
No Product matches the given query.
Request Method: GET
Request URL: http://127.0.0.1:8000/admin
Raised by: store.views.product_detail
No Product matches the given query.
Request Method: GET
Request URL: http://127.0.0.1:8000/admin
Raised by: store.views.product_detail
I havent touched the store app or project files at all at it was waking just fine yesterday now i cannot access admin page
project urls
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('store.urls', namespace='store')),
path('basket/', include('basket.urls', namespace='basket')),
path('account/', include('account.urls', namespace = 'account')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
store urls
from django.urls import path
from . import views
app_name = 'store'
urlpatterns = [
path('', views.product_all, name='product_all'),
path('<slug:slug>', views.product_detail, name='product_detail'),
path('shop/<slug:category_slug>/', views.category_list, name='category_list'),
]
store views
from urllib import request
from django.shortcuts import get_object_or_404, render
from store.context_processors import categories
from .models import Category, Product
def product_all(request):
products = Product.products.all()
return render(request, 'store/home.html', {'products': products})
def category_list(request, category_slug=None):
category = get_object_or_404(Category, slug=category_slug)
products = Product.objects.filter(category=category)
return render(request, 'store/products/category.html', {'category': category, 'products': products})
def product_detail(request, slug):
product = get_object_or_404(Product, slug=slug, in_stock=True)
return render(request, 'store/products/single.html', {'product': product}) ```
context_processors.py wicht i have includet in my project settings
from .models import Category
def categories(request):
return {
'categories': Category.objects.all()
}
This is the code that causes the error
path('<slug:slug>', views.product_detail, name='product_detail'),
Change it to
path('detail/<slug:slug>/', views.product_detail, name='product_detail'),
The product_detail just overwrites the admin URL
when i upload the image from the form it is just saving name of in database not saving the image and uploading to the path, but when i upload the image from database it stores perfectly
urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('',include('students.urls')),
path('admin/', admin.site.urls),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py
from django.db import models
# Create your models here.
class student_registration(models.Model):
registration_number = models.CharField(primary_key=True,max_length=100)
student_name = models.CharField(max_length=100)
student_father_name = models.CharField(max_length=100)
student_image=models.FileField(default='default.jpg', upload_to='media', blank=True)
views.py
from django.shortcuts import render
from .models import student_registration
from django.contrib import messages
from django.conf import settings
# Create your views here.
def student_registeration(request):
if ("registration_no" in request.POST and "student_name" in request.POST
and "student_fname" in request.POST and "student_image" in request.POST):
registration_no = request.POST["registration_no"]
student_name = request.POST["student_name"]
student_fname = request.POST["student_fname"]
student_image = (settings.MEDIA_URL + request.POST["student_image"],
'JPEG')
s = student_registration(registration_no,student_name, student_fname,
student_image)
s.save()
messages.success(request, f'Your account has been created! You are now
able to log in')
return render(request,'students/student_registration.html')
else:
return render(request, 'students/student_registration.html')
The file upload is stored in request.FILES not request.POST. You can retrieve it in the same way and assign it to the student_image field:
s = student_registration(
registration_number=registration_no,
student_name=student_name,
student_father_name=student_fname,
student_image=request.FILES['student_image'] # Retrieve from request.FILES
)
s.save()
You should also make sure that your form is set to enctype="multipart/form-data.
i am making a blog application for my website with django-2.0
when i run server i see the following error
File "C:\Users\User\Desktop\djite\djite\djite\urls.py", line 7, in <module>
url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')),
TypeError: include() got an unexpected keyword argument 'app_name'
here is my main urls.py
from django.contrib import admin
from django.conf.urls import url,include
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')),
]
and here's my blog/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>d{2})/(?P<post>
[-/w]+)/$', views.post_detail, name='post_detail'),
]
my views.py:
from django.shortcuts import render, HttpResponse, get_object_or_404
from blog.models import Post
def post_list(request): #list
posts=Post.published.all()
return render(request, 'blog/post/list.html', {'posts': posts})
def post_detail(request, year, month, day, post):
post =get_object_or_404(post, slog=post,
status='published',
publush__year=year,
publish__month=month,
publish__day=day)
return render (request, 'blog/post/detail.html', {'post':post})
models.py:
# -*- coding:utf-8 -*-
from django.db import models
from django.conf import settings
from django.utils import timezone
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.urls import reverse
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager,
self).get_queryset().filter(status='published')
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
title =
models.CharField(max_length=255,verbose_name=_('title'),help_text=_('add
title'))
content = models.TextField(verbose_name=_('content'),help_text=_('write
here'))
publish = models.DateTimeField(default=timezone.now)
createtime = models.DateTimeField(_('create time'),auto_now_add=True,
auto_now=False,help_text=_('create time'))
updatetime = models.DateTimeField(_('update time'),auto_now_add=False,
auto_now=True,help_text=_('update time'))
author = models.ForeignKey(settings.AUTH_USER_MODEL,
verbose_name=_('author'),
on_delete=models.DO_NOTHING,help_text=_('choose author'))
slug = models.SlugField(unique=True, max_length=255,help_text=_('add
slug'))
status = models.CharField(max_length=10, choices=STATUS_CHOICES,
default='draft')
def __unicode__(self):
return self.title
def __str__(self):
return self.title
class Meta:
ordering = ('-publish',)
verbose_name = _('Post')
verbose_name_plural = _('Posts')
def get_absolute_url(self):
return reverse('blog:post_detail', args=[self.publish.year,
self.publish.strftime('%m'),
self.publish.strftime('%d'),
self.slug])
also my views.py has a problem that i don't think that's related to my current error, when i delete
namespace='blog', app_name='blog'
from this line in main urls.py
url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')),
the server runs but when i go to this directory:
http://localhost:8000/blog/
i see this error
AttributeError at /blog/
type object 'Post' has no attribute 'published'
it says that this line of code has problem in views.py
posts=Post.published.all()
Using app_name with include is deprecated in Django 1.9 and does not work in Django 2.0. Set app_name in blog/urls.py instead.
app_name = 'blog'
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
...
]
Then change the include to:
url(r'^blog/', include('blog.urls')),
You don't need namespace='blog', as it will default to the application namespace anyway.
The second error is unrelated. You have forgotten to instantiate your custom manager on the model.
class Post(models.Model):
...
published = PublishedManager()
In Django 2.0 app_name, will not support :
Use of project URLs:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path(r'blog/', include('blog.urls')),//use this
]
I'm getting a 404 error when trying to serve user uploaded files in local. I've tried a lot of suggestions from the forums but I can't get it to work.
This is the error I can see on the logs. The images get uploaded properly to media/images but when I try to use that same image I get a 404 not found. I've tried to put the absolute path and didn't work either. Could anybody please help me? Thanks
[03/Feb/2018 23:32:00] "GET /idealistos/30/ HTTP/1.1" 200 483
Not Found: /media/images/_D3L8637.jpg
[03/Feb/2018 23:32:01] "GET /media/images/_D3L8637.jpg HTTP/1.1" 404 2239
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
# Media files
MEDIA_ROOT = 'media/'
MEDIA_URL = '/media/'
models.py
from django.db import models
from django.forms import ModelForm
from django.utils import timezone
from django.contrib.admin.widgets import AdminDateWidget
# Create your models here.
class Anuncio(models.Model):
title = models.CharField(max_length=40)
description = models.CharField(max_length=300)
price = models.CharField(max_length=10)
city = models.CharField(max_length=20)
state = models.CharField(max_length=20)
country = models.CharField(max_length=20)
postcode = models.CharField(max_length=20)
foto = models.FileField(null=True, blank=True, upload_to='images/')
pub_date = models.DateTimeField(default=timezone.datetime.now())
def __str__(self):
return self.title
def __unicode__(self):
return price
class AnuncioForm(ModelForm):
class Meta:
model = Anuncio
fields = ['title', 'description', 'price', 'city', 'state', 'country','postcode','foto']
views.py
from django.http import Http404, HttpResponseRedirect
from django.views.generic import ListView
from django import forms
from django.utils import timezone
#from django.template import loader
from django.shortcuts import render, get_object_or_404, redirect
from .models import Anuncio, AnuncioForm
#Creates a list from a model. Used for the ad index view.
class AnuncioList(ListView):
model = Anuncio
#Creates a detail view of the Ad
def detail(request, anuncio_id):
try:
anuncio_detalle = get_object_or_404(Anuncio, pk=anuncio_id)
#anuncio_detalle = Anuncio.objects.get(pk=anuncio_id)
except Anuncio.DoesNotExist:
raise Http404("Question does not exist")
return render(request, 'idealistos/detail.html', {'anuncio_detalle':anuncio_detalle})
def add_form(request):
if request.method == 'POST':
form = AnuncioForm(request.POST,request.FILES)
if form.is_valid():
new_add = form.save()
new_add.pub_date = timezone.now()
return redirect ('idealistos:index')
else:
form = AnuncioForm()
return render(request, 'idealistos/create_add.html', {'form':form,})
url.py
from django.conf.urls.static import static
from django.conf import settings
from django.urls import path
from . import views
from idealistos.views import AnuncioList
app_name ='idealistos'
urlpatterns = [
# ex: /idealistos/
path('', AnuncioList.as_view(), name='index'),
# ex: /idealistos/5/
path('<int:anuncio_id>/', views.detail, name='detail'),
#ex: /idealistos/add_form
path('add_form/', views.add_form, name='add_form'),
]
urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
Template
<head>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
</head>
<body>
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'idealistos/idealistos.css' %}" />
<h1>{{ anuncio_detalle }}</h1>
<ul>
<li>{{ anuncio_detalle.description }}</li>
<li>{{ anuncio_detalle.city }}, {{ anuncio_detalle.country }} CP:{{ anuncio_detalle.postcode }}</li>
<li>{{ anuncio_detalle.pub_date }}</li>
<img src={{anuncio_detalle.foto.url}}>
</ul>
</body>
Just try giving MEDIA_ROOT and serving in urls.py when DEBUG=True.
models.py
foto = models.ImageField(upload_to='images/', null=True, blank=True)
settings.py
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media')
MEDIA_URL = '/media/'
urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.views.static import serve
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
#Other Urls
. . . . .
. . . . .
# admin
url(r'^admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
urlpatterns += [
url(r'^media/(?P<path>.*)$', serve, {
'document_root': settings.MEDIA_ROOT
}),
]
I hope that you are seeing the uploaded file correctly.
For local development, try adding the following in your base urls.py
if settings.DEBUG is True:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
sometimes when i want to open the about page, the contact, create or blog
page this error comes: Raised by: blog.views.blog_postDetailView
i donnt know why, but I think it has to do sth with my urlpattterns
or the order of them . here my code.
appreciate your help and improvements
thanks a lot
mainurl
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from blog.views import AboutPageView, ContactPageView, blog_postCreateView
urlpatterns = [
url(r'^about/', AboutPageView.as_view(), name='about'),
url(r'^contact/', ContactPageView.as_view(), name='contact'),
url(r'^create/', blog_postCreateView.as_view(), name='blog_post_create'),
url(r'', include('blog.urls')),
url(r'^blog/', include('blog.urls')),
#admin and login
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('registration.backends.default.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
blog url
from django.conf.urls import url
from .views import blog_postListView, blog_postDetailView, blog_postCreateView
urlpatterns = [
url(r'^$', blog_postListView.as_view(), name='blog_post_list'),
url(r'^(?P<slug>[-\w]+)$', blog_postDetailView.as_view(), name='blog_post_detail'),
]
base html, the nav part
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>
Home
</li>
<li>
About
</li>
<li>
Contact
</li>
<li>
Blog
</li>
<li>
{% if request.user.is_authenticated %}
<li>Logout</li>
{% else %}
<li>Login</li>
<li>Register</li>
{% endif %}
model
rom __future__ import unicode_literals
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models.signals import pre_save, post_save
from django.utils.text import slugify
# Create your models here.
def upload_location(instance, filename):
#filebase, extension = filename.split(".")
#return "%s/%s.%s" %(instance.id, instance.id, extension)
return "%s/%s" %(instance.id, filename)
class blog_post(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
title = models.CharField(max_length=120)
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
image = models.ImageField(upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field="height_field")
#height_field = models.PositiveIntegerField()
#width_field = models.PositiveIntegerField()
slug = models.SlugField(unique=True)
content = models.TextField()
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
def __unicode__(self):
return self.title
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("blog_post_detail", kwargs={"slug": self.slug})
def create_slug(instance, new_slug=None):
slug = slugify(instance.title)
if new_slug is not None:
slug = new_slug
qs = blog_post.objects.filter(slug=slug).order_by("-id")
exists = qs.exists()
if exists:
new_slug = "%s-%s" %(slug, qs.first().id)
return create_slug(instance, new_slug=new_slug)
return slug
def pre_save_post_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = create_slug(instance)
pre_save.connect(pre_save_post_receiver, sender=blog_post)
views
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.views.generic import View
from django.views.generic.base import TemplateView, TemplateResponseMixin, ContextMixin
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.shortcuts import render
from django.utils.decorators import method_decorator
from .models import blog_post
from .forms import blog_postForm
# Create your views here.
class LoginRequiredMixin(object):
#classmethod
def as_view(cls, **kwargs):
view = super(LoginRequiredMixin, cls).as_view(**kwargs)
return login_required(view)
##method_decorator(login_required)
#def dispatch(self, request, *args, **kwargs):
# return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)
class blog_postCreateView(LoginRequiredMixin, CreateView):
#model = blog_post
form_class = blog_postForm
template_name = "form.html"
#fields = ["title", "content"]
def get_success_url(self):
return reverse("blog_post_list")
# #method_decorator(login_required)
# def dispatch(self, request, *args, **kwargs):
# return super(MyView, self).dispatch(request, *args, **kwargs)
class blog_postListView(ListView):
model = blog_post
def get_queryset(self, *args, **kwargs):
qs = super(blog_postListView, self).get_queryset(*args, **kwargs).order_by("-timestamp")
return qs
class blog_postDetailView(DetailView):
model = blog_post
class AboutPageView(TemplateView):
template_name = "about.html"
class ContactPageView(TemplateView):
template_name = "contact.html"
updated urls
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from blog.views import AboutPageView, ContactPageView, blog_postCreateView
urlpatterns = [
url(r'^about/', AboutPageView.as_view(), name='about'),
url(r'^contact/', ContactPageView.as_view(), name='contact'),
url(r'^create/', blog_postCreateView.as_view(), name='blog_post_create'),
url(r'^categories/', include('blog.urls_categories')),
#url(r'', include('blog.urls')),
url(r'^blog/', include('blog.urls')),
#admin and login
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('registration.backends.default.urls')),
url(r'', include('blog.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Put the below line in end of url_patterns list like
urlpatterns = [
#all other urls,
url(r'', include('blog.urls')),
]
OR
url(r'^blogdetail/', include('blog.urls')),