Django - images upload in wrong folder - django

Making some kind of blog website and can't make homepage to show article images...
Images should be uploaded to media/profile_pics , but it just makes profile_pics folder in app folder and uploads images there.
my models.py :
class Post(models.Model):
title = models.CharField(max_length=255)
title_tag = models.CharField(max_length=255, default="YNTN")
#author = models.ForeignKey(User, on_delete=models.CASCADE)
body = RichTextField(blank=True, null=True)
image = models.ImageField(upload_to="profile_pics", blank=True, null=True)
#body = models.TextField()
post_date = models.DateField(auto_now_add=True)
likes = models.ManyToManyField(User, related_name="blog_posts")
def total_likes(self):
return self.likes.count()
def __str__(self):
return (self.title + " | " + str(self.author))
def get_absolute_url(self):
return reverse("home")
my views.py:
class AddPostView(CreateView):
model = Post
form_class = PostForm
template_name = 'add_post.html'
my forms.py
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'title_tag', 'body', 'image')
widgets = {
'title': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Title of the Blog'}),
'title_tag': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Copy the title with no space and a hyphen in between'}),
'body': forms.Textarea(attrs={'class':'form-control', 'placeholder':'Content of the Blog'}),
}
my home.html
<div class="row">
{% for post in object_list %}
<div class="col-lg-4 my-4">
<div class="card shadow" style="width: 20rem; height: 33rem;">
<img src="/media/{{post.image}}" class="card-img-top" alt="..." height="250px">
<div class="card-body">
<h5 class="card-title">{{post.title}} <br><small>by {{ post.author.first_name }} {{ post.author.last_name }}</small></h5>
<p class="card-text">{{post.body|slice:":100"|safe}}</p>
Read More {% if user.is_superuser %}<a href="delete_blog_post/{{post.slug}}/" class="btn btn-danger mx-4">Delete Blog{% endif %}</a>
</div>
</div>
</div>
{% endfor %}
</div>
```
my settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR, 'yntn/yntnapp/media')
MEDIA_URL = '/media/'
Images should be in media/profile_pics, but instead, it is making profile_pics folder in my project folder and uploading images there...

I think you should set your MEDIA_ROOT like the following line.
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

Related

generic createview and django form only rendering a button in a template

I have encountered a funny challenge, as am building some apps where they want track some expenses and revenues profits ...
I used generic views to create and get details and delete, all work fine with expenses, but I copied the same code and I used it for revenues from expenses you can't imagine this view is rendering a button only yet it has a form, NOTE SAME CODE WORK WELL ON EXPENSES. I even exchanged templates but it kept rendering the former content even after changing the template. it doesn't matter what's in the template the view just renders the same thing even when I remove the form, even when I put pass.
class AccountsRevenueCreate(CreateView):
template_name='dashboard/expense_create.html'
model= AccountsExpense
success_url = reverse_lazy('dashboard:expenses')
form_class=AccountsExpenseForm
and the form
class AccountsRevenueForm(forms.ModelForm):
class Meta:
model = AccountsRevenue
fields = '__all__'
and in the template
<div class="row">
<div class="col-12">
<h5 class="form-title"><span>revenue Update
</span></h5>
</div>
<form method="post", action="{% url
'dashboard:revenue_add' %}">
{% csrf_token %}
{% comment %} {{ form|crispy }} {% endcomment %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary col-12 col-sm-12">Save
</button>
</form>
</div>
and the URLs
path ('accounts/revenues/create/', AccountsRevenueCreate.as_view(), name='revenue_create'),
I have chosen to show you only where the problem is not paste unnecessary code
here are the models you requested me to update
from django.db import models
class AccountsRevenue(models.Model):
revenue_of = models.CharField(max_length=250, default='',null=False)
revenue_by = models.CharField(max_length=250, default='',null=False)
amount = models.IntegerField( default='100,000')
day_on_which = models.DateField(null=True, blank=True)
evidence_document = models.ImageField(upload_to = 'uploads/', blank=True, default='')
signature = models.ImageField(upload_to = 'uploads/', blank=True, default='')
def __str__(self):
return str(self.revenue_of)
def get_absolute_url(self):
return reverse('dashboard:revenue', kwargs= {'pk':self.pk} )
def get_document(self):
if self.evidence_document and hasattr(self.evidence_document, 'url'):
return self.evidence_document.url
else:
return "/static/assets/img/user.png"
class AccountsExpense(models.Model):
expense_of= models.CharField(max_length=250, default='',null=False)
expense_by = models.CharField(max_length=250, default='',null=False)
amount = models.IntegerField( default='100,000')
day_on_which = models.DateField(null=True, blank=True)
evidence_document = models.ImageField(upload_to = 'uploads/',
blank=True, default='')
signature = models.ImageField(upload_to = 'uploads/', blank=True,
default='')
def __str__(self):
return str(self.expense_of)
def get_absolute_url(self):
return reverse('dashboard:expense', kwargs= {'pk':self.pk} )
def get_document(self):
if self.evidence_document and hasattr(self.evidence_document,
'url'):
return self.evidence_document.url
else:
return "/static/assets/img/user.png"
from django.urls import URLPattern, path
from django.conf.urls.static import static
from. views import profiles, Profile_detail, Profile_update,
Profile_delete, dashboard, Profile_create,\
AccountsRevenues, revenue_detail_view, AccountsRevenueUpdate,
AccountsRevenue_delete, \
AccountsExpenses, AccountsExpenseDetail, AccountsExpenseCreate,
AccountsExpenseUpdate, AccountsExpenseDelete,\
userprofileupdate, revenue_add, AccountsRevenueCreate
app_name = "dashboard"
urlpatterns = [
path ('accounts/revenues', AccountsRevenues.as_view(), name='revenues'),
path ('accounts/revenues/<str:pk>/', revenue_detail_view,
name='revenue'),
path ('accounts/revenues/<str:pk>/update/',
AccountsRevenueUpdate.as_view(), name='revenue_update'),
path ('accounts/revenues/<str:pk>/delete/',
AccountsRevenue_delete.as_view(), name='revenue_delete'),
path ('accounts/revenues/create/', AccountsRevenueCreate.as_view(),
name='revenue_create'),
# accounts expenses
path ('accounts/expenses', AccountsExpenses.as_view(), name='expenses'),
path ('accounts/expenses/<str:pk>', AccountsExpenseDetail.as_view(),
name='expense'),
path ('accounts/expenses/<str:pk>/update/',
AccountsExpenseUpdate.as_view(), name='expense_update'),
path ('accounts/expenses/<str:pk>/delete/',
AccountsExpenseDelete.as_view(), name='expense_delete'),
path ('accounts/expenses/create/', AccountsExpenseCreate.as_view(),
name='expense_create'),
]
I have added a screenshot of what it comes out as enter image description here
left model.py, forms.py, urls.py as it was.
views.py
in the line: template_name = 'bboard/expense_create.html' replace bboard with the name of the folder where the templates are located. I have it templates/bboard. Also in your field: form_class=AccountsExpenseForm changed to form_class = AccountsRevenueForm.
And the return goes to the same page with the form: success_url = reverse_lazy('revenue_create').
success_url can then be returned to what it was, now you need to make sure that everything works.
views.py
class AccountsRevenueCreate(CreateView):
template_name = 'bboard/expense_create.html'
model = AccountsExpense
success_url = reverse_lazy('revenue_create')
form_class = AccountsRevenueForm
expense_create.html
in the template you have an error form method="post", there should not be a comma.
<div class="row">
<div class="col-12">
<h5 class="form-title"><span>revenue Update
</span></h5>
</div>
<form method="post" action="{% url 'revenue_create' %}">
{% csrf_token %}
{% comment %} {{ form|crispy }} {% endcomment %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary col-12 col-sm-12">Save
</button>
</form>
</div>
Followed the link: http://localhost:8000/accounts/revenues/create/
Screenshot attached:

Django imagefield don't shows on template

i've a model with an imageField and when i upload file works and in database adds file path to img field
but when i try call it in my template seem is always empity item.img instead other fields works well, to show it i use a listview model
def content_file_name(instance, filename):
ext = filename.split('.')[-1]
# filename = "%s_%s.%s" % (instance, instance.questid.id, ext)
return f"uploads/items/{instance.id}.{ext}"
class Item(models.Model):
type = models.IntegerField(choices=TYPE, blank=False, default=NO_CAT)
name = models.CharField(max_length=250 )
description = models.CharField(max_length=250, blank=True )
img = models.ImageField(upload_to=content_file_name, blank=True)
tags = models.ManyToManyField(Tag, through='Item_Tags')
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING)
active = models.BooleanField(default=False)
created = models.DateTimeField(default=timezone.now)
updated = models.DateTimeField(auto_now=True)
def __str__(self): #metodo righiesto
return self.name
my template
<div class="card-columns">
{% for item in page_obj %}
<div class="card">
{% if item.img %}
<img class="card-img-top" src="{{item.image.url}}" alt="Card image cap">
{% else %}
NO image
{% endif %}
<div class="card-body">
<h5 class="card-title">{{item.name}}</h5>
<p class="card-text">{{item.description}}</p>
<p class="card-text"><small class="text-muted"></small></p>
</div>
</div>
{% endfor %}
</div>

Django queryset Product model and Product_images model, TemplateSyntaxError

I am developing an ecommerce website with Django. I had Product and Product_images models as below:
class Product(models.Model):
tags = models.ManyToManyField(Tag, related_name='products')
same_product = models.ManyToManyField('self', related_name='same_products', blank=True)
category = models.ForeignKey('Category', on_delete=models.CASCADE, related_name='product_categories')
who_like = models.ManyToManyField(User, related_name='liked_products', blank=True)
title = models.CharField('Title', max_length=100, db_index=True)
slug = models.SlugField('Slug', max_length=110, unique = True)
sku = models.CharField('SKU', max_length=50, db_index=True)
description = models.TextField('Description', null=True, blank=True)
sale_count = models.IntegerField('Sale Count', default=0)
is_new = models.BooleanField('is_new', default=True)
is_featured = models.BooleanField('is_featured', default=False)
is_discount = models.BooleanField('is_discount', default=False)
price = models.DecimalField('Price', max_digits=7, decimal_places=2)
discount_value = models.IntegerField('Discount Value', null=True, blank=True)
def __str__(self):
return self.title
class Product_images(models.Model):
# relations
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='images')
# informations
image = models.ImageField('Image', upload_to='media/product_images')
is_main = models.BooleanField('Main Image', default=False)
is_second_main = models.BooleanField('Second Main Image', default=False)
# moderations
status = models.BooleanField('Status', default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
db_table = 'image'
verbose_name = 'Image'
verbose_name_plural = 'Images'
ordering = ('created_at',)
def __str__(self):
return f'{self.image}'
In my Product_images model I store several images for one Product, in Product_images model I wrote
boolean fields with names is_main and is_second_main. In my template I want to get these images, in my terminal (interactive shell) when I write single_product.images.get(is_main=True).image.url can get image url, but in template I can't get image, but get an error as below:
TemplateSyntaxError at /
Could not parse the remainder: '(is_main=True).image.url' from 'product.images.get(is_main=True).image.url'
Below is my view and template:
def index(request):
products = Product.objects.all()
context = {
'products': products
}
return render(request, 'index/index.html', context)
{% for product in products %}
<div class="front">
<a href="product-page(no-sidebar).html">
<img src="{{ product.images.get(is_main=True).image.url }}" class="img-fluid blur-up lazyload bg-img" alt="">
</a>
</div>
<div class="back">
<a href="product-page(no-sidebar).html">
<img src="{{ product.images.get(is_main=True).image.url }}" class="img-fluid blur-up lazyload bg-img" alt="">
</a>
</div>
{% endfor %}
Please, help me with this problem and properly display these images, thanks in advance.
I already solve this problem, maybe it is not the best way, but work.
{% for product in products %}
<div class="product-box">
<div class="img-wrapper">
<div class="front">
<a href="{% url 'product-detail' product.slug %}">
{% for image in product.images.all %}
{% if image.is_main %}
<img src="{{ image.image.url }}" class="img-fluid blur-up lazyload bg-img" alt="">
{% endif %}
{% endfor %}
</a>
</div>
<div class="back">
<a href="{% url 'product-detail' product.slug %}">
{% for image in product.images.all %}
{% if image.is_second_main %}
<img src="{{ image.image.url }}" class="img-fluid blur-up lazyload bg-img" alt="">
{% endif %}
{% endfor %}
</a>
</div>
{% endfor %}

Blog post with image Django3

Hi i'm trying to add some funcionality to my blog post app, i'd like to paste image into post content so i figured is this waw that ive created new model just for images and set it as OneToOne with my Post model
i wonder if ther is any way to set this image to content field in the post model
models.py
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
class PostImage(models.Model):
post = models.OneToOneField(Post, on_delete=models.CASCADE)
image = models.ImageField(default=None, upload_to='post_pics', blank=True)
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
img = Image.open(self.image.path)
if img.height > 500 or img.width > 500:
output_size = (500, 500)
img.thumbnail(output_size)
img.save(self.image.path)
vievs.py
def home(request):
context = {
'posts': Post.objects.all(),
'user_posts': "active",
}
return render(request, 'blog/home.html', context)
class PostListView(ListView):
model = Post
template_name = 'blog/home.html'
context_object_name = 'posts'
ordering = ['-date_posted']
paginate_by = 5
post_template.html
{% extends "blog/base.html" %}
{% load static %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Blog Post</legend>
{{form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Post</button>
</div>
</form>
</div>
{% endblock content %}
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
Well i've found another solution i've used CKEditor and now everything works fine
pip install pillow
& in static/post_pics (see the img.jpg ...png ) it's save ?

Displaying images "not featured" with featured images in Django template language

I am trying to display small thumbnail under featured images using django template language but for some reason main image displays fine but not small image. Idea is to display one featured image and rest as "not featured" images.
My single-page code to display "Featured Images" with "Not Featured" images is given below.
{% extends 'base.html' %}
{% block content %}
<h1>{{ product.title }}</h1>
{% for img in images %}
{% if img.featured %}
<h1>Featured</h1>
<img class='img-responsive' src="{{ MEDIA_URL }}{{ img.image }}"/>
{% else %}
<div class="col-xs-6 col-md-3">
<a href="#" class="thumbnail">
<img class='img-responsive' src="{{ MEDIA_URL }}{{ img.image }}"/>
</a>
</div>
{% endif %}
{% endfor %}
{% endblock %}
Please advise.
My models.py is....
from django.core.urlresolvers import reverse
from django.db import models
class Product(models.Model):
title = models.CharField(max_length=120)
description = models.TextField(null=True, blank=True)
price = models.DecimalField(decimal_places=2, max_digits=100, default=29.99)
sale_price = models.DecimalField(decimal_places=2, max_digits=100, null=True, blank=True)
slug = models.SlugField(unique=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
active = models.BooleanField(default=True)
def __unicode__(self):
return str(self.title)
class Meta:
unique_together = ('title', 'slug')
def get_price(self):
return self.price
def get_absolute_url(self):
return reverse('single_product', kwargs={'slug': self.slug})
class ProductImage(models.Model):
product = models.ForeignKey(Product)
image = models.ImageField(upload_to='products/images/')
featured = models.BooleanField(default=False)
thumbnail = models.BooleanField(default=False)
active = models.BooleanField(default=True)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __unicode__(self):
return self.product.title
All the images were set as featured and that was causing issue. Thanks for help #f43d65. Also consulted project on Github at: https://github.com/codingforentrepreneurs/ecommerce/blob/master/ecommerce/templates/products/single.html.
Try to replace
{{ MEDIA_URL }}{{ img.image }}
to
{{ img.image.url }}