I need slider in my website and I have tried these things as mentioned below but I cannot get the data from the database in template. Is the process of getting data from database is wrong. How to get the data in template I am really confused how to do these things.
Model.py
class AddImage(models.Model):
name=models.CharField(max_length=100,blank=False)
image=models.ImageField(upload_to='img')
publish=models.BooleanField(default=True)
def __str__(self):
return self.name
views.py
def index(request):
slider_img=AddImage.objects.all()
context = {
'slider_img':slider_img
}
return render(request,'home.html',context)
home.html
<div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
{% for img in slider_img %}
{% if img.publish %}
<div class="carousel-item active">
<img class="d-block w-100" src="{{ img.image.url }" alt="First slide">
</div>
<a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
{% endif %}
{% endfor %}
</div>
</div>
Reference : https://docs.djangoproject.com/en/dev/howto/static-files/#serving-files-uploaded-by-a-user-during-development
Check your settings.py, that you have defined MEDIA_ROOT and 'MEDIA_URL' (and they are correct).
And add these lines to the end of your urls.py file:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Related
I uploaded a picture in the Django database but when I try to show this picture in Django templates, it's not showing anything but showing the image title.
Here is my index.html
{% for value in data %}
<div class="product-box">
<div class="img-wrapper">
<div class="front">
<a href="product-page(no-sidebar).html"><img
src="{{ value.product_img.url }}"
class="img-fluid blur-up lazyload bg-img" alt=""></a>
</div>
<div class="back">
<a href="product-page(no-sidebar).html"><img
src="{{ value.product_img.url }}"
class="img-fluid blur-up lazyload bg-img" alt=""></a>
</div>
<div class="cart-info cart-wrap">
<button data-bs-toggle="modal" data-bs-target="#addtocart"
title="Add to cart"><i class="ti-shopping-cart"></i></button> <a
href="javascript:void(0)" title="Add to Wishlist"><i
class="ti-heart" aria-hidden="true"></i></a> <a href="#"
data-bs-toggle="modal" data-bs-target="#quick-view"
title="Quick View"><i class="ti-search" aria-hidden="true"></i></a>
<a href="compare.html" title="Compare"><i class="ti-reload"
aria-hidden="true"></i></a>
</div>
</div>
<div class="product-detail">
<div class="rating"><i class="fa fa-star"></i> <i class="fa fa-star"></i> <i
class="fa fa-star"></i> <i class="fa fa-star"></i> <i
class="fa fa-star"></i></div>
<a href="product-page(no-sidebar).html">
<h6>{{ value.product_title }}</h6>
</a>
<h4>{{ value.price }}</h4>
<ul class="color-variant">
<li class="bg-light0"></li>
<li class="bg-light1"></li>
<li class="bg-light2"></li>
</ul>
</div>
</div>
{% endfor %}
Here is my views.py
def home(request):
context={
'data': Products.objects.all()
}
return render(request, 'auctionApp/index.html',context)
Just add below code in urls.py file in the project directory:
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Hi I'm trying to display an uploaded user image in django but when I try to display it only a blank box appears. However when I click on the image it brings up a new page with the image. I don't know why it isn't displaying on the page.
html
{% load mptt_tags %}
{% recursetree location %}
<div class="card">
<div class="card-body">
<a class="btn btn-primary" type="button" href="/AddClimb/{{node.id}}">Add Climb</a>
</div>
</div>
<img source="{{node.img.url}}" width="500" height="400">
<div class="container">
<div class="row equal">
<div class="col-md-6 col-sm-6">
<div class="card-header bg-primary text-white text-center">{{ node.name }}</div>
<div class="card" style="background-color: #eee;">
<p class="font-weight-bold">Image: <img source="{{node.img.url}}"></p>
<p class="font-weight-bold">Description: <span class="font-weight-normal">{{node.description}}</span></p>
<p class="font-weight-bold">Directions: <span class="font-weight-normal">{{node.directions}}</span></p>
<p class="font-weight-bold">Elevation: <span class="font-weight-normal">{{node.elevation}}</span></p>
<p class="font-weight-bold">Latitude: <span class="font-weight-normal">{{node.latitude}}</span></p>
<p class="font-weight-bold">Longitude: <span class="font-weight-normal">{{node.longitude}}</span></p>
<p class="font-weight-bold">Added By: <span class="font-weight-normal">{{node.author}}</span></p>
<p class="font-weight-bold">Date Added: <span class="font-weight-normal">{{node.date}}</span></p>
<a class="btn btn-primary float-center" type="button" href="/EditLocation/{{node.id}}/">Edit Location</a>
</div>
</div>
{% endrecursetree %}
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'Choss_App/media')
urls.py
from django.conf.urls import url
from django.contrib import admin
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('Choss_App.urls')),
]
# if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
It is src=…, not source=…:
<img src="{{ node.img.url }}" …>
I have a sample Django 2.2 project that has a search bar in the top right corner of the nav bar (taken from the Bootstrapers):
navbar.html:
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="/">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a>
</li>
{% if user.is_authenticated %}
<li class="nav-item">
<a class="nav-link" href="/search/">Search</a>
</li>
...
{% endif %}
<li class="nav-item">
<a class="nav-link" href="/a/">A</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/b/">B</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0" action = '/search/'>
<input class="form-control mr-sm-2" type="search" name="q" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
It returns "You searched for [search argument]" to the url '/search/' and works fine. I would like to bring it from the nav bar under the 'Search' menu in the nav bar. I have the following:
searches/models.py
from django.db import models
from django.conf import settings
# Create your models here.
class SearchQuery(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, blank = True, null=True, on_delete=models.SET_NULL)
query = models.CharField(max_length=220)
timestamp = models.DateTimeField(auto_now_add=True)
searches/views.py:
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.contrib.admin.views.decorators import staff_member_required
from .models import SearchQuery
# Create your views here.
#login_required
# staff_member_required
def search_view(request):
query = request.GET.get('q', None)
user = None
if request.user.is_authenticated:
user = request.user
SearchQuery.objects.create(user=user, query=query)
context = {"query": query}
return render(request, 'searches/view.html',context)
searches/templates/searches/view.html:
{% extends "base.html" %}
{% block content %}
{% if user.is_authenticated %}
<form action = '/search/'>
<input type="search" name="q" aria-label="Search">
<button type="submit">Search</button>
</form>
<div class='row'>
<div class='col-12 col-8 mx-auto'>
<p class='lead'>You searched for {{ query }}</p>
</div>
</div>
{% endif %}
{% endblock %}
When I search from the search bar in the navigational pane, it returns the argument. But when I want to run the search from the search bar and click on the Search tab, I get this:
IntegrityError at /search/
NOT NULL constraint failed: searches_searchquery.query
...
...searches\views.py in search_view
SearchQuery.objects.create(user=user, query=query)
Why am I getting this ?
EDIT:
After making this change in searches/views.py:
query = request.POST.get('q', None)
I get this error in the runtime:
django.db.utils.IntegrityError: NOT NULL constraint failed: searches_searchquery.query
and in the browser:
I am using Django I am trying to make image slider using bootstrap, this is my code so far
{% extends "blog/modelsbase.html"%}
{% block content%}
<body>
<div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img class="d-block w-100" src= "/media/models/dd08-43fc-ae2b-c6bc75ade6f6.jpg" alt="First slide">
</div>
{% for image in images %}
<div class="carousel-item">
<img class="d-block w-100" src= "{{image}}" alt="Second slide">
</div>
{% endfor %}
</div>
<a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</body>
{% endblock content%}
</html>
this is my views.py
from django.shortcuts import render
import os
images = os.listdir('/media/models/model1')
def test_model_bt(request):
return render(request,'blog/model1.html',{'title':'TEST_MODEL','images':images})
The images are showing correctly,I would like to place the images inside some sort of container to give them max size [800x800] (if they are larger than it reduce size else pass), how can I do it ?
Note:for now my code is "mobile friendly" I would like to keep that
I got my slider from Carousel · Bootstrap
one way you can do it with sorl thumbnail and you can do as follows
{% load thumbnail %}
{% thumbnail image "800x800" crop="center" as im %}
{{ im }}
So, I have setup django-registration's simple backend where the user registers and is immediately logged in to the display to my other django app fileuploader. Here is the urls.py:
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
from registration.backends.simple.views import RegistrationView
class MyRegistrationView(RegistrationView):
def get_success_url(self, request, user):
# return "/upload/new"
return "/upload/" + user.get_absolute_url()
urlpatterns = patterns('',
url(r'^accounts/register/$', MyRegistrationView.as_view(), name='registration_register'),
url(r'^accounts/', include('registration.backends.simple.urls')),
url(r'^upload/', include('mysite.fileupload.urls')),
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^mysite/', include('mysite.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
)
import os
urlpatterns += patterns('',
(r'^media/(.*)$', 'django.views.static.serve', {'document_root': os.path.join(os.path.abspath(os.path.dirname(__file__)), 'media')}),
)
So after the user registers at accounts/register he/she is taken directly to the url upload/users/username
Here is the mysite.fileuplaod.urls that contains the url patterns for upload/:
from django.conf.urls import patterns, include, url
from mysite.fileupload.views import PictureCreateView, PictureDeleteView
from mysite.registration.backends.simple.views import RegistrationView
from django.contrib.auth.models import User
from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth import login
from mysite.registration import signals
from mysite.registration.views import RegistrationView as BaseRegistrationView
class MyRegistrationView(RegistrationView):
def get_success_url(self, request, user):
# return "/upload/new"
return "/upload/" + user.get_absolute_url()
urlpatterns = patterns('',
(r'$'+get_absolute_url(),PictureCreateView.as_view(), {}, 'upload-new'),
(r'^new/$', PictureCreateView.as_view(), {}, 'upload-new'),
(r'^delete/(?P<pk>\d+)$', PictureDeleteView.as_view(), {}, 'upload-delete'),
)
I want to setup the exact same view as upload/new for upload/users/username. r'$'+get_absolute_url() doesn't look like the right way to do it. I would really appreciate if someone could show me the right way to do this.
Also I would like to display the user name on the fileupload view page as something like "Welcome
{% extends "base.html" %}
{% load upload_tags %}
{% block content %}
<div class="container">
<div class="page-header">
<h1>Wordseer File Uploader</h1>
</div>
<form id="fileupload" method="post" action="." enctype="multipart/form-data">{% csrf_token %}
<div class="row fileupload-buttonbar">
<div class="span7">
<span class="btn btn-primary fileinput-button">
<i class="icon-plus icon-white"></i>
<span>Add files...</span>
<input type="file" name="file" multiple>
</span>
<button type="submit" class="btn btn-success start">
<i class="icon-upload icon-white"></i>
<span>Start upload</span>
</button>
<button type="reset" class="btn btn-warning cancel">
<i class="icon-ban-circle icon-white"></i>
<span>Cancel upload</span>
</button>
<button type="button" class="btn btn-danger delete">
<i class="icon-trash icon-white"></i>
<span>Delete files</span>
</button>
<input type="checkbox" class="toggle">
</div>
<div class="span5 fileupload-progress fade">
<div class="progress progress-success progres-striped active">
<div class="bar" style="width:0%"></div>
</div>
<div class="progress-extended"> </div>
</div>
</div>
<div class="fileupload-loading"></div>
<table class="table table-striped"><tbody class="files" data-toggle="modal-gallery" data-target="#modal-gallery"></tbody></table>
</form>
<div class="fileupload-content">
<table class="files"></table>
<div class="fileupload-progressbar"></div>
</div>
<div>
{% if pictures %}
<h2>Already uploaded</h2>
<table class="table table-striped">
{% for picture in pictures %}
<tr>
<td class="preview">
<img src="{{ picture.file.url }}">
</td>
<td class="name">{{ picture.slug }}</td>
<td class="delete">
<a class="btn btn-danger" href="{% url 'upload-delete' picture.id %}">
<i class="icon-trash icon-white"></i>
<span>Delete</span>
</button>
</td>
</tr>
{% endfor %}
</table>
<p>(Removing from this list is left as an exercise to the reader)</p>
{% endif %}
</div>
</div>
<!-- modal-gallery is the modal dialog used for the image gallery -->
<div id="modal-gallery" class="modal modal-gallery hide fade" data-filter=":odd">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3 class="modal-title"></h3>
</div>
<div class="modal-body"><div class="modal-image"></div></div>
<div class="modal-footer">
<a class="btn modal-download" target="_blank">
<i class="icon-download"></i>
<span>Download</span>
</a>
<a class="btn btn-success modal-play modal-slideshow" data-slideshow="5000">
<i class="icon-play icon-white"></i>
<span>Slideshow</span>
</a>
<a class="btn btn-info modal-prev">
<i class="icon-arrow-left icon-white"></i>
<span>Previous</span>
</a>
<a class="btn btn-primary modal-next">
<span>Next</span>
<i class="icon-arrow-right icon-white"></i>
</a>
</div>
</div>
{% upload_js %}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="{{ STATIC_URL }}js/jquery.ui.widget.js"></script>
<script src="{{ STATIC_URL }}js/tmpl.min.js"></script>
<script src="{{ STATIC_URL }}js/load-image.min.js"></script>
<script src="{{ STATIC_URL }}js/canvas-to-blob.min.js"></script>
<script src="{{ STATIC_URL }}js/bootstrap.min.js"></script>
<script src="{{ STATIC_URL }}js/bootstrap-image-gallery.min.js"></script>
<script src="{{ STATIC_URL }}js/jquery.iframe-transport.js"></script>
<script src="{{ STATIC_URL }}js/jquery.fileupload.js"></script>
<script src="{{ STATIC_URL }}js/jquery.fileupload-fp.js"></script>
<script src="{{ STATIC_URL }}js/jquery.fileupload-ui.js"></script>
<script src="{{ STATIC_URL }}js/locale.js"></script>
<script src="{{ STATIC_URL }}js/main.js"></script>
<script src="{{ STATIC_URL }}js/csrf.js"></script>
{% endblock %}
Thanks in advance.
To set url use something like:
url(r"^(?P<username>\w+)/$", PictureCreateView.as_view(), {}, 'upload-new')
and move it after 'new/' url.
To display user name in template use:
{{ request.user.username }} or {{ request.user.get_full_name }}