I am working on a commerce app wher a user can create a listing and also upload the image of the listing. The data is handled by a ModelForm:
class ListingForm(ModelForm):
class Meta:
model = Listing
exclude = [
'date_made',
'user',
'category',
'is_active',
]
The ModelForm inherits from the Listing model. Pay particular attention to the upload_image attribute:
class Listing(models.Model):
NAME_CHOICES = [
('Fashion', 'Fashion'),
('Toys','Toys'),
('Electronic','Electronics'),
('Home', 'Home'),
('Other', 'Other')
]
title = models.CharField(max_length= 64)
date_made = models.DateTimeField(auto_now_add=True)
description = models.TextField()
user = models.ForeignKey(User, to_field='username', on_delete=models.CASCADE, related_name='user_listings', null=True)
starting_bid = models.DecimalField(decimal_places=2, max_digits=264, default=10.00)
upload_image= models.ImageField(blank=True, upload_to='media/')
category = models.ForeignKey(Category, on_delete=models.CASCADE, to_field='name', related_name='category_listings', default=NAME_CHOICES[4][0], db_constraint=False)
listing_category = models.CharField(max_length=12, choices=NAME_CHOICES, null=True, default=NAME_CHOICES[4][0])
is_active = models.BooleanField(default=True)
def __str__(self):
return f'{self.title}'
I also have tried to make some media file configurations to my app.
settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
(global/project) urls.py:
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("auctions.urls"))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
my views.py looks like this, im not sure if it is relevant to the problem:
def create_listing(request):
if request.method == 'POST':
import datetime
listing_form = ListingForm(request.POST)
# bid = request.POST['starting_bid']
if listing_form.is_valid():
bid = listing_form.cleaned_data['starting_bid']
listing_form.save(commit=False)
# listing_form.user = request.user
listing_form.user = request.user
listing_form.date_made = datetime.datetime.today()
listing_form.is_active = True
listing_form.category = Category.objects.get(name=listing_form.cleaned_data['listing_category'])
listing_form.save()
Bid.objects.create(value=bid, listing=listing_form.instance)
return HttpResponse('Listing has been saved successfully!')
Lastly the html tag that i cant get to work looks like this:
<img src="{{MEDIA_URL}}{{listing.upload_image}}"class="img-fluid rounded-start" alt="Picture not available">
I've tried to look at other stackoverflow answers but they dont seem to solve the problem. How do I get the page to display the images?
