I saved image in database, there are multiple images and i want to retrive it in my website.
my image is stored in static folder inside app folder that is card/static/images.
my images is showing when i enter link http://127.0.0.1:8000/images/p.jpeg
this is my urls.py
`
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('card.urls')),
path('index/', include('card.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
this is my models.py
class dish(models.Model):
dish_name = models.CharField(max_length=255)
dish_size = models.CharField(max_length=7)
dish_price = models.IntegerField()
dish_description = models.CharField(max_length=255)
dish_image = models.ImageField()
dish_date = models.DateField()
this is my index.html file
<img src="{{ request.dish.dish_image.url }}" height="100px" width="100px">
this is my setting.py
STATIC_URL = 'static/'
MEDIA_URL = 'images/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
MEDIA_ROOT = os.path.join(BASE_DIR, 'card/static/images')
`
this is my card/urls.py
urlpatterns = [
path('', views.index),
path('/', views.index),
path('/index', views.index),
path('index/', views.index),
path('index', views.index),
]
this is my views file
def index(request):
if request.method == "POST":
dish_name = request.POST.get('dish_name')
dish_size = request.POST.get('dish_size')
dish_price = request.POST.get('dish_price')
dish_description = request.POST.get('dish_description')
dish_image = request.POST.get('dish_image')
item = dish(dish_name = dish_name, dish_size = dish_size, dish_price = dish_price, dish_description = dish_description, dish_image = dish_image, dish_date = datetime.today())
item.save()
return render(request, "card/index.html")
Related
I've launched my project into production, CKEditior and CKEditor_uploader both worked on my local server but now doesn't show on my production admin panel. Any ideas why it may not be showing would be greatly appreciated. Or any alternative ways to implement richtext and image uploading to blog posts in django admin.
*UPDATE
I have some how got the CKEditor back but I cannot get the uploader to work, I have followed all documentation to a tee.
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/static/images/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
MEDIA_ROOT = os.path.join(BASE_DIR, '/home/martinhenso/public_html/static/images/')
STATIC_ROOT = os.path.join(BASE_DIR, '/home/martinhenso/public_html/static')
CKEDITOR_UPLOAD_PATH = "uploads/"
urls
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('martinhensonphotography.urls')),
path('ckeditor/', include('ckeditor_uploader.urls')),
]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.MEDIA_ROOT)
models
class Topic(models.Model):
title = models.CharField(max_length=100)
content = RichTextUploadingField()
def __str__(self):
return self.title
class BlogPost(models.Model):
blog_title = models.CharField(max_length=255)
blog_article = RichTextField(null=True, blank=True)
blog_image = models.ImageField(null=True, blank=True, upload_to="images", default="default.png")
def __str__(self):
return self.blog_title
admin
from django.contrib import admin
from . models import PostImage, EnterImage, BlogPost, Topic
# Register your models here.
admin.site.register(PostImage)
admin.site.register(BlogPost)
admin.site.register(EnterImage)
admin.site.register(Topic)
Try:
settings.py
STATIC_ROOT = [
os.path.join(BASE_DIR,'static','static_files')
]
python manage.py collectstatic
Location of static files are must be mension in nginx config file
Or
After entering the comment there will be a folder created 'static_files' inside static folder copy all the static files to to main static folder
my model have an imagefield which stores the image for post . I want to add default image to that in case if not is not uploaded.But I am getting error The 'title_image' attribute has no file associated with it. If I upload image then its working fine.
Models.py
class Post(models.Model):
title_image = models.ImageField(
upload_to='Images/PostTitleImages/',
max_length=None,
default = 'Images/Image_not_found.jpg',
blank = True,
null = True)
home.html
<img src="{{post.title_image.url}}" height="350px"/>
Settings.py
STATIC_URL = 'static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static/'),
]
MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('MainSite.urls'), name = "Main"),
path('account/',include('account.urls'), name = 'Accounts')
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
what I am doing wrong here I checked the file is in this directory /media/Images/PostTitleImages/
In case of media you need to include the media tag in your template like so:
# template
<img src="{{ media_url }}{{ post.title_image.url }}>
and in your settings add the context processor
# settings.py
'django.template.context_processors.media'
So I recently was trying to deploy my website and I was able to get everything working. However, the images are broken for some reason. I can actually add images to the database fine (easily able to add and change the image itself). However, when I click on the link I go nowhere instead of seeing the image and just see the part of my site that pops up whenever the URL entered isn't part of the API (no error, instead nothing basically shows up). The strange part is that the uploaded images actually get added to my images folder in my project but it seems like Django can't find them afterwards (you can see the image is in the database in my images folder). Here is how my project is laid out and: Here is some of my code:
SETTINGS.PY
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles')
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'build/static'),
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
REST_FRAMEWORK = {
'DEFAULT_AUTHETICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication'
]
}
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR),'EZtrade')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'build')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
URLS.PY
urlpatterns = [
path('api-auth/', include('rest_framework.urls')),
path('admin/', admin.site.urls),
path('api/', include('articles.api.urls')),
path('rest-auth/', include('rest_auth.urls')),
path('rest-auth/registration/', include('rest_auth.registration.urls')),
re_path('.*',TemplateView.as_view(template_name='index.html')),
url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT,})
] + static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT)
API URLS
router = DefaultRouter()
router.register(r'articles', ArticleViewSet, basename='articles')
router.register(r'trade', TradeViewSet, basename='trade')
router.register(r'users', UserDataViewSet, basename='users')
urlpatterns = router.urls + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
MODEL
class Article(models.Model):
title = models.CharField(max_length=120)
content = models.TextField()
image = models.ImageField(upload_to = 'images', blank=True)
createdBy = models.CharField(max_length=120)
traded = models.BooleanField(default=False)
city = models.CharField(max_length=120)
def __str__(self):
return self.title
VIEWS.PY
class ArticleViewSet(viewsets.ModelViewSet):
serializer_class = ArticleSerializer
queryset = Article.objects.all()
filter_backends = [DjangoFilterBackend,filters.SearchFilter]
filterset_fields = ['createdBy','traded']
search_fields = ['title']
authentication_classes = (TokenAuthentication,) # Add this line
permission_classes = (IsAuthenticated,)
def get_permissions(self):
if self.action == 'list' or self.action == 'retrieve':
return [AllowAny(), ]
return super(ArticleViewSet, self).get_permissions()
def patch(self, request, pk):
testmodel_object = self.get_object(pk)
serializer = TestModelSerializer(testmodel_object, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return JsonResponse(code=201, data=serializer.data)
return JsonResponse(code=400, data="wrong parameters")
SERIALIZERS.PY
class ArticleSerializer(PatchModelSerializer):
class Meta:
model = Article
fields = ('id','title','content','image','createdBy','traded','city')
I have tried many different things and have not been able to find anything else like this on the internet since I dont even get an error when trying to access the image. Im pretty stuck with this so if anyone could help that would be awsome!
you have to make an another serializer using method and pass image url on that like this
class ArticleSerializer(PatchModelSerializer):
image_url = serializers.SerializerMethodField('get_image_url')
class Meta:
model = Article
fields = ('id','title','content','image','image_url','createdBy','traded','city')
def get_image_url(self, obj):
return obj.image.url
I figured out that I had to put the re_path at the end since it was overriding my image url.
i just figured out that the problem is in the urls.py file
it's missing some code
here is mine before
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('api.urls'))
]
and here is after i saw this article
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('api/', include('api.urls'))
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
I made a project using Django 1.5.4 and have now a problem with serving files being uploaded locally. My urls.py look like this now:
urlpatterns = patterns('',
url(r'^$', views.home),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
) + static(settings.MEDIA_ROOT, document_root='')
In models.py there is an ImageField of a class Product:
photo = models.ImageField(upload_to=MEDIA_ROOT)
and a method for displaying it:
def display_photo(self):
return '<img src="%s" />' % (self.photo)
display_photo.short_description = 'Photo of a product'
display_photo.allow_tags = True
And, finally, MEDIA_ROOT in settings.py:
MEDIA_ROOT = '/home/nervosa/DjangoProjects/Sit_test/uploads/'
Still firebug shows an error:
GET http://127.0.0.1:8000/home/nervosa/DjangoProjects/Sit_test/uploads/cover.jpg 404 (NOT FOUND)
What did i do wrong?
Solved. I just needed to modify urls.py:
urlpatterns = patterns('',
url(r'^$', views.home),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
)
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^uploads/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
)
The whole class Product contained by models.py now looks like this:
class Product(models.Model):
title = models.CharField(max_length=50)
height = models.FloatField(max_length=10)
weight = models.FloatField(max_length=10)
color = models.CharField(max_length=7)
photo = models.ImageField(upload_to='products_photo/')
thumbnail = ThumbnailerImageField(default='', upload_to='products_photo_thumbnails')
def __unicode__(self):
return self.title
def display_photo(self):
return '<img src="%s" />' % (self.photo.url)
display_photo.short_description = 'Photo of a product'
display_photo.allow_tags = True
Sorry for not providing my ModelAdmin - here it is:
class ProductAdmin(admin.ModelAdmin):
fieldsets = [
('Title of a product', {'fields':['title']}),
('Parameters of a product', {'fields':['height', 'weight', 'color']}),
('Upload a photo', {'fields':['photo']}),
('Photo', {'fields':['display_photo']}),
]
list_display = ['title', 'height', 'weight', 'color']
readonly_fields = ('display_photo',)
admin.site.register(Product, ProductAdmin)
And finally - MEDIA_ROOT and MEDIA_URL - in my case they should be:
MEDIA_ROOT = '/home/nervosa/DjangoProjects/Sit_test/'
MEDIA_URL = '/uploads/'
Now image is displayed properly after uploading. Thanks for attention and answers.
I can upload images in Django admin and they appear in the correct directory, but when I have these issues when I try to view them in my templates:
{% if city.main_image %} returns false in my template
{{ city.main_image.url }} returns nothing
{{ city.main_image }} returns None
When I click the admin preview I get this 404:
Request URL: http://127.0.0.1:8000/admin/search/city/1/test/test.jpg/
city object with primary key u'1/test/test.jpg' does not exist.
The rest of the template outputs the correct information associated with the city object.
Here are my settings.py urls:
MEDIA_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), "html/static")
MEDIA_URL = '/media/'
STATIC_ROOT = ''
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = '/static/admin/'
My urls.py:
from django.conf.urls.defaults import patterns, include, url
from test import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('test.search.views',
url('^search/$', 'search', name="home_page"),
url(r'^(\d+)/$', 'city', name="city_page"),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
)
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
)
My models.py:
class City(models.Model):
name = models.TextField("Course Name", blank=False)
address = models.TextField("Address", blank=False)
city = models.TextField("City", blank=False)
state = models.TextField("State", blank=False)
country = models.TextField("Country", blank=False)
main_image = models.ImageField(upload_to="test", blank=True)
Can anyone spot what I'm doing wrong here?
Interesting, after re-syncing my database I'm no longer having issues.