I have been trying to make my code able to post images but when I create the post, the picture doesnt appear but the image gets save on media/images I was wondering if there is any way to make the code work, ther might be something wrong in the base.html when I call the image {{ request.user.image.url }}
views.py
def create(request):
if request.method == 'POST':
created_date = timezone.now()
header1 = request.POST['header']
content1 = request.POST['content']
user = request.user
uploded_file = request.FILES['image']
created_obj = Create.objects.create(added_date=created_date, title=header1, content=content1, user=user, image=uploded_file)
created_obj.save()
print('create created')
return redirect('home')
else:
print('create not created')
return render(request, 'create.html')
models.py
class Create(models.Model):
added_date = models.DateTimeField()
title = models.CharField(max_length=200)
content = models.CharField(max_length=200)
image = models.ImageField(null=True, blank=True, upload_to='images/')
user = models.ForeignKey(User, related_name='user', on_delete=models.CASCADE, default=1)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
create.html
{% extends 'home.html' %}
{% block body %}
<div style="margin-top: 200px; margin-left:200px;">
<form action="create" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" name="header" placeholder="Add here...">
<input type="text" name="content" placeholder="Add here...">
<input type="file" name="image">
<button type="submit"name="action" class="btn btn-primary mb-2">submit</button>
</form>
</div>
{% endblock %}
base.html
{% extends 'home.html' %}
{% block body %}
<ul action="{% url 'create' %}" class="container-sm list-group" style="margin-top: 200px;">
{% for created_post in created_posts %}
<li class="list-group-item">{{ created_post.title }}
<a href="{% url 'profile_pk' pk=created_post.user.pk %}">{{ created_post.user }}</a>
<img class="image" src="{{ create.image.url }}">
<p>{{ created_post.content }}</p>
<div class="float-right">
<form action="delete_create/{{ created_post.id }}/" action="post">
<button type="submit" class="btn btn-outline-danger btn-sm">Delete</button>
</form>
</div>
<div class="float-right">
<a href="{% url 'edit' created_post.id %}" class="btn btn-outline-warning btn-sm" style="margin-right: 5px;" role="button">Edit</a>
</div>
</li>
{% endfor %}
</ul>
{% endblock %}