How to Upload Images To Django template - django-views

I'm confused why some ids show pictures and others don't.
html show value
<div class="row">
<div class="col-md-6 mb-4 pb-2">
<div class="form-outline">
<label class="form-label" for="car_picture">Car Picture</label>
{% if crdt.car_picture%}
<img src="{{crdt.car_picture.url}}">
{% endif %}
</div>
</div>
</div>
html add car
<div class="row">
<div class="col-md-6 mb-4 pb-2">
<div class="form-outline">
<label class="form-label" for="car_picture">Car Picture</label>
<input type="file" name="car_picture" multiple class="form-control form-control-sm" />
</div>
</div>
</div>
In the database the displayed image will be saved as Car_images/cat1_QKdSRhQ.jpg The image that is not displayed will be cat1.jpg.
view add
def add_car(request):
if request.method=='POST':
car_brand = request.POST.get('car_brand')
license_p = request.POST.get('license_p')
car_weight = request.POST.get('car_weight')
temp_max = request.POST.get('temp_max')
temp_min = request.POST.get('temp_min')
car_picture = request.POST.get('car_picture')
if Car.objects.count() != 0:
car_id_max = Car.objects.aggregate(Max('car_id'))['car_id__max']
next_car_id = car_id_max[0:3] + str(int(car_id_max[3:7])+1)
else:
next_car_id = "CAR1000"
new_car = Car.objects.create(
car_id = next_car_id,
car_band = car_brand,
total_coolbox_weight = car_weight,
temp_max = temp_max,
temp_min = temp_min,
license_plate = license_p,
car_picture = car_picture
)
new_car.save()
return render(request,'add_car.html',{'message1':"Add car successful."})
return render(request,'add_car.html')
View show value
def view_car(request,pk):
crdt = Car.objects.get(car_id=pk)
return render(request,'view_car.html',{'crdt':crdt})
Url
urlpatterns = [
path("add_car",views.add_car,name='add_car'),`
path("view_car/<str:pk>",views.view_car,name='view_car'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Setting
STATIC_URL = 'static/'
STATTICFILES_DIRS = [
BASE_DIR / "static"
]
STATIC_ROOT = (BASE_DIR/"asert/")
MEDIA_ROOT = (BASE_DIR / 'media')
MEDIA_ROOT = os.path.join(BASE_DIR / 'media')
MEDIA_URL = '/media/'
STATTICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
by this ID showing the picture
But this ID doesn't show pictures.

Related

Page not found (404) error while searching through search page Raised by: blog.views.blogpost

i am unable to search and get 404 error same problem occur in sitemap views for creating static xml file,
it does not return the url for static file and now have this problem with search as it is unable to find search .html gives this Page not found (404) error while searching through search page Raised by: blog.views.blogpost error.
Search_Form
<form method='GET' action="/blog/search/" class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="search" id="search">
<button class="btn btn-outline-success mx-2 my-1 my-sm-0" type="submit">Search</button>
</form>
Search views.py
def search(request):
myposts = Blogpost.objects.all()
query = request.GET['search']
if len(query)>78:
myposts = Blogpost.objects.none()
else:
post_title = Blogpost.objects.filter(Q(title__icontains=query))
posts_content = Blogpost.objects.filter(Q(content__icontains=query))
posts_slug = Blogpost.objects.filter(Q(slug__icontains=query))
myposts = post_title | posts_content | posts_slug
if myposts.count() == 0:
messages.warning(request, "No search results found. Please enter again.")
context = {'myposts': myposts,'query':query}
return render(request, 'blog/search.html', context)
url.py
urlpatterns = [
path('', views.index, name='bloglist'),
path('<slug:post>/', views.blogpost, name='blogpost'),
path("contact/", views.contact, name="contact"),
path("search/", views.search, name="search")
]
My search.html
{% block body %}
<div class="container mt-3">
<h5> <p> Search Results:</p> </h5>
{% if myposts|length < 1 %}
Your Search -<b> {{query}} </b>- did not match any documents please try again. <br>
<br> Suggestions:
<ul>
<li>Make sure that all words are spelled correctly.</li>
<li>Try more general keywords.</li>
<li>Try different keywords.</li>
</ul>
{% endif %}
<div class="container mt-3">
<div class="row my-2">
{% for post in myposts %}
<div class="col-md-6">
<div class="row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative">
<div class="col p-4 d-flex flex-column position-static">
<h3 class="mb-0">{{post.title}}</h3>
<div class="mb-1 text-muted"></div>
<strong class="d-inline-block mb-2 text-primary"><a>{{post.author}} | {{post.created_on}}</a></strong>
<p class="card-text mb-auto">{{post.content|safe}}</p>
Continue reading
</div>
<div class="col-auto d-none d-lg-block">
<img src="/media/{{post.thumbnail}}" class="bd-placeholder-img" width="200" height="250" aria-label="Placeholder: Thumbnail">
<title>Placeholder</title></img>
</div>
</div>
</div>
{% if forloop.counter|divisibleby:2%}
</div>
<div class="row my-2">
{% endif %}
{% endfor %}</div>
</div>
</div>
{% endblock %}
Project urls.py
from django.contrib.sitemaps.views import sitemap
from blog.sitemaps import StaticViewsSitemap
from blog.sitemaps import BlogSitemap
sitemaps ={
'blogpost': BlogSitemap(),
'static': StaticViewsSitemap(),
}
urlpatterns = [
path('admin/', admin.site.urls),
path('shop/', include('shop.urls')),
path('blog/', include('blog.urls', namespace='blog')),
path('', views.index),
path('register/', views.registerPage),
path('login/', views.loginPage),
path('logout/', views.logoutUser),
path('sitemap.xml/', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py
class Blogpost(models.Model):
STATUS_CHOICES= ( ('0', 'Draft'), ('1', 'Publish'),)
post_id = models.AutoField(primary_key= True)
title = models.CharField(max_length=50, unique=True)
slug = models.SlugField(max_length=50, unique=True)
content = models.TextField(max_length=5000, default="")
author = models.ForeignKey(Author, on_delete=models.CASCADE)
thumbnail = models.ImageField(upload_to='shop/images', default="")
created_on = models.DateTimeField(default=timezone.now)
categories = models.ManyToManyField(Category)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
objects = models.Manager()
featured = models.BooleanField()
def get_absolute_url(self):
return reverse('blog:blogpost',
args=[self.slug])
class Meta:
ordering = ('-created_on',)
def __str__(self):
return self.title
Try rewriting your form to something like this:
<form method="POST" action="{% url 'search' %}" class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" arialabel="Search" name="search" id="search">
<button class="btn btn-outline-success mx-2 my-1 my-sm-0" type="submit">Search</button>
</form>
And your search view like this:
def search(request):
myposts = Blogpost.objects.all()
if request.method == 'POST'
query = request.POST.get('search')
if len(query) > 78:
myposts = Blogpost.objects.none()
else:
myposts = Blogpost.objects.filter(Q(title__icontains=query))
myposts = Blogpost.objects.filter(Q(content__icontains=query))
myposts = Blogpost.objects.filter(Q(slug__icontains=query))
if myposts.count() == 0:
messages.warning(request, "No search results found. Please enter again.")
context = {'myposts': myposts, 'query': query}
return render(request, 'blog/search.html', context)
UPDATE
So, after going through your GitHub repository I saw a couple of issues, first off there is no urls.py or views.py in your blog app, its either not added in the repo or just doesn't exist, which would explain the router not finding any paths for your views, hovewer there is one in the question so I'm not sure whats the issue here, please check again so that the file is in the right directory in the root of your blog app folder.
Second off in your main project directory there are files called urls.py, views.py and forms.py, that shouldn't be the case, instead create a seperate app and place them there.

Django not show image field

Not showing image on upload, what is the problem?
setting.py
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = 'media/'
html.
{% for tt in article %}
<div class="content_box">
<div class="content_l left">
<div class="horoscope_box_big">
<div class="blog_img1">
<img src="{{ tt.image.url }}" alt="{{tt.title}}" width="50%" /> {{ tt.image.url }}
</div>
<h1 class="blog_title1"> {{ tt.Title }}
<div class="blog_descr1"><h1>more about</h1>
<p> {{ tt.body }}</p>
</div>
</div>
{% endfor %}
models.py
class Blogmodel(models.Model):
Title = models.TextField(blank=True, null=True)
image = models.ImageField(upload_to="images/",null=True)
body = RichTextField(blank=True, null=True)
slug = AutoSlugField(populate_from='Title', unique=True,blank=True, null=True)
def __str__(self):
return self.Title
views.py
def blog_list(request):
articles = Blogmodel.objects.all()
args = {'articles':articles}
return render(request,'blog.html',args)
def blogDetail(request, slug):
article = Blogmodel.objects.filter(slug=slug)
args = {'article':article}
return render(request,'blogdetail.html',args)
urls.py
from django.urls import path
from .views import singCategory,Home,blog_list,blogDetail
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('',Home,name= "Home"),
path('horoscope/<slug:slug>/<slug:cat>',singCategory,name='singCategory'),
path("blog/",blog_list, name="blog_list"),
path("blog/<slug:slug>",blogDetail, name="blogDetail"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Your settings.py:
MEDIA_URL = '/media/'
Your template:
<img src="{{ article.image.url }}">
check if you have Pillow installed, pip install pillow,

how to upload image in django

Here is my settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Here is 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('admin/', admin.site.urls),
path('', include('laxmi.urls')),
] + static(settings.MEDIA_URL, documents_root=settings.MEDIA_ROOT)
Here is my model:
class Services(models.Model):
title = models.CharField(max_length=250)
desc = models.TextField()
img = models.ImageField(upload_to='img')
def __str__(self):
return self.title
Views:
def index(request):
why_choose_uss = why_choose_us.objects.all()
servicess = Services.objects.all()
return render(request, 'laxmi/index.html', {'servicess': servicess, 'why_choose_uss':
why_choose_uss})
Template:
{% for services in servicess %}
<div class="col mb-4">
<div class="card">
<img src="{{services.img.url}}"class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">{{services.title}}</h5>
<p class="card-text">{{services.desc}}</p>
Lern More
</div>
</div>
</div>
{% endfor %}
And here is an image upload from admin pannel but its not shwoing in template
here it is model in admin panel
output in template
Try to substitute
<img src="{{services.img.url}}"class="card-img-top" alt="...">
with
<img src="{{services.img.url}}" class="card-img-top" alt="..." />

python - Django display uploaded multiple images with foreign key

I have for example the Post with the id 31 after I upload one or more images are displayed in db as:
id (for example: 1,2,3)
url to image(for example: my-images/image.png)
foreing_id (thats is id to post i.e 31)
But I do not know how to display the image in the template for this post (and others of course)
my model:
class Post(models.Model):
title = models.CharField(max_length=20000)
date = models.DateTimeField(editable=True, null=True)
text = models.TextField(max_length=50000)
is_super = models.IntegerField(default=0)
class Image(models.Model):
foreing = models.ForeignKey(Post)
image = models.ImageField(null=True, blank=True, upload_to='my-images')
view where i upload and display all posts(Here i display):
class IndexView(generic.ListView):
paginate_by = 4
template_name = 'home/index.html'
context_object_name = 'all_posts'
def get_queryset(self):
query = self.request.GET.get('q')
if query:
posts = Post.objects.filter(
Q(text__icontains=query.capitalize()) |
Q(title__icontains=query.capitalize()) |
Q(text__icontains=query.lower()) |
Q(title__icontains=query.lower())
).distinct()
return posts
else:
return Post.objects.filter(date__lte=timezone.now()).order_by('-date')
there i create a new post:
def post_new(request):
ImageFormSet = modelformset_factory(Image, form=ImageForm, extra=3)
if request.method == "POST":
form = PostForm(request.POST, request.FILES or None)
formset = ImageFormSet(request.POST, request.FILES, queryset=Image.objects.none())
if form.is_valid() and formset.is_valid():
post = form.save(commit=False)
post.date = timezone.now()
post.save()
for form in formset.cleaned_data:
image = form['image']
photo = Image(foreing_id=post.id, image=image)
photo.save()
return render(request, 'home/page.html')
else:
form = PostForm()
return render(request, 'home/edit_post.html',
{'form': form, 'error_message': 'something error message'})
else:
form = PostForm()
formset = ImageFormSet(queryset=Image.objects.none())
return render(request, 'home/edit_post.html', {'form': form, 'formset': formset})
And here i need to display images for all this posts:
Here is a image displayed
<div class="profile-img-container" style="text-align: center">
<img class="img" src="images">
<a target="_blank" title="****." href="URL to the uploaded image"><span class="fa fa-expand fa-5x" style="color: darkcyan" aria-hidden="true"></span></a>
full index.html if needed:
<div class="content">
{% for post in all_posts %}
<div class="thumbnail">
<p style="text-align: center">{{ post.title }}</p>
<p class="text" style="text-align: center; height: 40px; overflow: hidden">{{ post.text }}</p>
<p><a type="button" class="btn btn-primary" href="{% url 'klass:detail' post.id %}">More...</a></p>
<div class="profile-img-container" style="text-align: center">
<img class="img" src="/media/**display images**" style="height: 150px">
<a target="_blank" title="****." href="**url to images**"><span class="fa fa-expand fa-5x" style="color: darkcyan" aria-hidden="true"></span></a>
</div>
{% if user.is_authenticated %}
<form method="post" style="text-align: right">
<p>
{% csrf_token %}
<a methods="post" role="button" class="btn btn-info" href="{% url 'klass:favorite' post.id %}">
<i class="fa fa-heart" style="color: red" aria-hidden="true"></i>great! {{ post.is_super }}
</a>
</p>
</form>
<span style="margin-left: 90px">Published: {{ post.date }}</span>
{% else %}
<p style="text-align: right">****<br>
<a role="button" class="btn btn-info disabled" style="text-align: right">
<i class="fa fa-heart" aria-hidden="true"></i>great!</a>
{{ post.date }}
</p>
{% endif %}
</div>
{% endfor %}
EDIT
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
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^home_page/', include('home.urls', namespace='home')),
url(r'^captcha/', include('captcha.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'home/static'),
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
another urls in home app:
from django.conf.urls import url
from . import views
app_name = 'home'
urlpatterns = [
***,
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<post_id>[0-9]+)/$', views.comments, name='detail'),
url(r'^(?P<post_id>[0-9]+)/addcomment$', views.addcomment, name='comment'),
url(r'^(?P<post_id>[0-9]+)/favorite/$', views.favorite, name='favorite'),
url(r'^(?P<pk>[0-9]+)/edit/$', views.post_edit, name='edit'),
url(r'^post/new/$', views.post_new, name='post_new'),
url(r'^(?P<post_id>[0-9]+)/delete_album/$', views.delete_post, name='delete_post'),
****,
]
You should loop through post.image_set.all and display each image separately, for example:
{% for image in post.image_set.all %}
<div class="profile-img-container" style="text-align: center">
<img class="img" src="{{ image.image.url }}" style="height: 150px">
<a target="_blank" href="{{ image.image.url }}">
<span class="fa fa-expand fa-5x" style="color: darkcyan" aria-hidden="true"></span>
</a>
</div>
{% endfor %}
A few side notes:
You shouldn't include /media in your image url as it will be automatically appended by Django.
Naming your foreign keys as foreign (also check your spelling) is not recommended for readability reasons. Consider renaming it to use the parent model's name in lowercase (such as post) instead so that it becomes post = models.ForeignKey(Post)
Referencing the foreign key using _id is not recommended. Use the model itself instead, for example: photo = Image(post=post, image=image)

Can't load a form in Django

I need to make a simple form. I can't understand why I don't see it. When I press a button which must show it, I see POST not GET request in my console. Which is not correct. Here is code:
form:
class DeviceAddForm(django.forms.Form):
name = django.forms.CharField(widget = django.forms.TextInput(attrs = {'size':'2','value':'1','class':'device',}))
device_slug = django.forms.CharField(widget = django.forms.HiddenInput())
model_name = django.forms.CharField(widget = django.forms.TextInput(attrs = {'size':'2','value':'1','class':'device',}))
platfrom = django.forms.ComboField(widget = django.forms.CheckboxInput())
sdk = django.forms.ComboField(widget = django.forms.CheckboxInput())
def __init__(self,request=None,*args,**kwargs):
self.request = request
super(DeviceAddForm,self).__init__(*args,**kwargs)
def clean(self):
if self.request:
if not self.request.session.test_cookie_worked():
raise django.forms.ValidationError("Cookies must be enabled")
return self.cleaned_data
saving data:
DEVICE_ID_SESSION_KEY = 'device_id'
def _device_id(request):
if request.session.get(DEVICE_ID_SESSION_KEY,'') == '':
request.session[DEVICE_ID_SESSION_KEY] = _generate_device_id()
return request.session[DEVICE_ID_SESSION_KEY]
def _generate_device_id():
device_id = ''
chars = '0123456789'
device_id_len = 5
for i in range (device_id_len):
device_id +=chars[random.randint(0,len(chars)-1)]
def get_device(request):
return Device.objects.filter(device_id= _device_id(request))
def add_device(request):
postdata = request.POST.copy()
device_slug = postdata.get('device_slug','')
name = postdata.get('name','')
model_name = postdata.get('model_name','')
platform = postdata.get('platform','')
sdk = postdata.get('SDK','')
d = get_list_or_404(Device, slug = device_slug)
dev = Device()
# dev = d
dev.name = name
dev.model_name = model_name
#dev.sdkID
#dev.plID
dev.id = _device_id(request)
dev.save()
view:
#csrf_exempt
def show_device(request, template_name = "onep_web/deviceForm.html"):
d = get_list_or_404(Device,slug = DeviceAddForm.device_slug)
if request.method == 'POST':
postdata = request.POST.copy()
form = DeviceAddForm(request,postdata)
if form.is_valid():
device.add_device(request)
if request.session.test.cookie_worked():
request.session.delete_test_cookie()
url = urlresolvers.reverse('show_device')
return HttpResponseRedirect(url)
else:
form = DeviceAddForm(request=request, label_suffix=':')
form.field['device_slug'].widget.attr['value'] = DeviceAddForm.device_slug
request.session.set_test_cookie()
# return render_to_response(template_name, locals(),csrf(context_instance RequestContext(request)))
return render_to_response(template_name, {'form':form})
urls:
urls form the app
urlpatterns = patterns('onep_web.views',
(r'^$','show_device',{'template_name':'onep_web/deviceForm.html'},'show_device'))
and some more urls:
urls.py from project
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
#url(r'^$', 'welcome_page.home', name='home'),
#url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^welcome_page/', 'one_web.views.welcome_page'),
url(r'^onep_web/', include('onep_web.urls')),
url(r'^device_page/', 'one_web.views.device_page'),
url(r'^configuration_page/', 'one_web.views.configuration_page'),
url(r'^log_page/', 'one_web.views.log_page'),
)
templates :
it's one from which I call the form
<title>OnePK Web Tool - {%block page %}{% endblock %}</title>
</head>
<body>
<div >
<br>
<div> Welcome to OnePK web-tool</div>
</div>
<form >
<br>
<br>
<br>Username:
<input type="text" name="Username">
<br>Password:
<input type="password" name="pwd">
<br>
<br>
{% block content %}
<h4>List of devices and IP addresses:</h4>
<table border="1">
<tr>
<td>Dev1</td>
<td>Dev2</td>
<td>Dev3</td>
<td>Dev4</td>
</tr>
<tr>
<td>{{a.getIP}}</td>
<td>{{a.getIP}}</td>
<td>{{a.getIP}}</td>
<td>{{a.getIP}}</td>
</tr>
</table>
{% endblock %}
<br>
<br>
<br>
<button type="button" onclick="ping()">Ping elenent</button>
<script>
function ping()
{
}
</script>
<br>
<br>
<label>Connection status</label>
<br>
<button type="button" onclick="openDev()">Connect to element</button>
<script>
function openDev()
{
window.open("p2t.html");
}
</script>
</form>
<form method = "post" action = "." class = "device">
{% csrf_token %}
{{form.as_p}}
<br />
<input type="submit" value="Add a new network device" name="submit" alt="Add a new network device"/>
</form>
<div class="cb"></div>
</body>
</body>
</html>
deviceForm:
{ % extends "p1t.html" % }
{ %block content% }
<h1> Add a new Device </h1>
Device info: { { device_data} }
<label for="name">Name</label><input type="text" id = "name" value = ""/>
{ %endblock% }