image uploading trouble in django - python

i have uploaded image but it is not showing up in page.
Uploaded image is also not showing up in media folder.
Used django forms for uploading image.
have a look at my code snippets:
my models.py:
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
published_date = models.DateTimeField(blank=True, null=True)
blog_img = models.ImageField(upload_to='images/',null=True, blank=True)
#property
def img(self):
if self.blog_img and hasattr(self.blog_img, 'url'):
return self.blog_img.url
else:
return "#"
my views.py:
def post_new(request):
if request.method =="POST":
form = PostForm(request.POST , request.FILES)
if form.is_valid():
post = form.save(commit=False)
post.author= request.user
post.save()
return redirect('post_detail',pk=post.pk)
else:
form=PostForm()
return render(request, 'blog/post_edit.html',{'form':form})
def post_edit(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = PostForm(request.POST, request.FILES, instance=post)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm(instance=post)
return render(request, 'blog/post_edit.html', {'form': form})
i have added this in settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
my post_list.html:
{% extends 'blog/base.html' %}
{% block content %}
<div class="h2">
<h2>Recent Posts</h2>
</div>
{% for post in posts %}
<div class="">
<div class="post">
<h2>{{ post.title }}</h2>
Comments: {{ post.approved_comments.count }}
<img src=" {{ post.img }} " width="200px" alt="images">
<p>{{ post.text|linebreaksbr }}</p>
<div class="date">
<p>published: {{ post.published_date }}</p>
</div>
</div>
</div>
{% endfor %}
{% endblock %}
form template used for getting input from user
django forms are used here..
post_edit.html
{% extends 'blog/base.html' %}
{%block content%}
<h2>New post</h2>
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
{%endblock%}

Related

Django Update User form photo saves but doesnt update in the site itself

So I am trying my hand out at my first django project on my own after tutorials, and I am trying to add an update user profile page. The username and email update perfectly fine, but when i try to update the profile picture, it doesnt update.Even though the file is saved in my media folder.
forms.py:
class UserUpdateForm(forms.ModelForm):
email = forms.EmailField()
class Meta:
model = User
fields = ('username', 'email')
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('image',)
views.py
#login_required
def profile(request, pk):
user = User.objects.get(id=pk)
profile = Profile(user=user)
user_form = UserUpdateForm(instance=request.user)
profile_form = ProfileUpdateForm(instance=request.user.profile)
if request.method == 'POST':
user_form = UserUpdateForm(request.POST, instance=request.user)
profile_form = ProfileUpdateForm(
request.POST, request.FILES, instance=request.user.profile)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
return redirect('home')
return render(request, 'registration/profile.html', {'user': user, 'profile': profile, 'user_form': user_form, 'profile_form': profile_form})
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<h3 class="display-3 mb-3">
{{ user.username }}
</h3>
<p>
{{ user.bio }}
</p>
<br>
<img src="{{ user.profile.image.url }}" alt="ok">
<hr>
<hr>
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend>Profile Info</legend>
{{ user_form|crispy }}
{{ profile_form|crispy }}
</fieldset>
<button type="submit" class="btn btn-sm btn-primary">Update</button>
</form>
{% endblock %}
If you need any more code i will update the question.
What exactly is the problem here?
Try removing instance=request.user.profile from your bound ProfileUpdateForm. And perhaps adding profile.image = request.FILES['image'] and profile.save() after your profile_form.is_valid() check. Or a combination of the two.

Django Blog - I can't add new comment

Problem with a comment system in my Django project.
When I add a new comment in 127.0.0.1:8000 or localhost:8000 the page just reloads and nothing happens.
In "blog/views.py" in post_detail(request, year, month, day, slug): I guess there is something wrong at if request.method == 'POST': and then move on to else: comment_form = CommentForm() so that I can only see the page just reloads. However, I don't know how to fix it...
This is a full code of my Django project.
my github repository
from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.core.mail import send_mail
from django.views.generic import ListView
from taggit.models import Tag
from .models import Post, Comment
from .forms import EmailPostForm, CommentForm
def post_list(request, tag_slug=None):
object_list = Post.published.all()
tag = None
if tag_slug:
tag = get_object_or_404(Tag, slug=tag_slug)
object_list = object_list.filter(tags__in=[tag])
paginator = Paginator(object_list, 3) # 3 posts in each page
page = request.GET.get('page')
try:
posts = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer deliver the first page
posts = paginator.page(1)
except EmptyPage:
# If page is out of range deliver last page of results
posts = paginator.page(paginator.num_pages)
return render(request, 'blog/post/list.html', {'page': page, 'posts': posts})
def post_detail(request, year, month, day, slug):
post = get_object_or_404(Post, slug=slug, status='published', publish__year=year, publish__month=month, publish__day=day)
# List of active comments for this post
comments = post.comments.filter(active=True)
new_comment = None
# Comment posted
if request.method == 'POST':
# A comment was posted
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
# Create Comment object but don't save to database yet
new_comment = comment_form.save(commit=False)
# Assign the current post to the comment
new_comment.post = post
# Save the comment to the database
new_comment.save()
else:
comment_form = CommentForm()
return render(request, 'blog/post/detail.html', {'post': post, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form})
def post_share(request, post_id):
# Retrieve post by id
post = get_object_or_404(Post, id=post_id, status='published')
sent = False
if request.method == 'POST':
# Form was submitted
form = EmailPostForm(request.POST)
if form.is_valid():
# Form fields passed validation
cd = form.cleaned_data
post_url = request.build_absolute_uri(post.get_absolute_url())
subject = '{} ({}) recommends you reading "{}"'.format(cd['name'], cd['email'], post.title)
message = 'Read "{}" at {}\n\n{}\'s comments: {}'.format(post.title, post_url, cd['name'], cd['comments'])
send_mail(subject, message, 'ecrire06#korea.ac.kr', [cd['to']])
sent = True
else:
form = EmailPostForm()
return render(request, 'blog/post/share.html', {'post': post, 'form': form, 'sent': sent})
class PostListView(ListView):
queryset = Post.published.all()
context_object_name = 'posts'
paginate_by = 3
template_name = 'blog/post/list.html'
{% extends "blog/base.html" %}
{% block title %}{{ post.title }}{% endblock %}
{% block content %}
<!-- title -->
<h1>{{ post.title }}</h1>
<!-- date -->
<p class="date">
Published {{ post.publish }} by {{ post.author }}
</p>
<!-- body-->
{{ post.body|linebreaks }}
<p>
<a href="{% url 'blog:post_share' post.id %}">
Share this post
</a>
</p>
<!-- number of comments-->
{% with comments.count as total_comments %}
<h2>
{{ total_comments }} comment{{ total_comments|pluralize }}
</h2>
{% endwith %}
<!-- content of comments -->
{% for comment in comments %}
<div class="comments">
<p class="font-weight-bold">
Comment {{ forloop.counter }} by {{ comment.name }}
{{ comment.created }}
</p>
{{ comment.body | linebreaks }}
</div>
{% empty %}
<p>There are no comments yet.</p>
{% endfor %}
<!-- add comments -->
<div>
{% if new_comment %}
<h2>Your comment has been added.</h2>
{% else %}
<h2>Add a new comment</h2>
<form methon="post" enctype="multipart/form-data">
{{ comment_form.as_p }}
{% csrf_token %}
<p><input type="submit" value="Add comment"></p>
</form>
{% endif %}
</div>
{% endblock %}

My comment system in Django is not working as expected

I'm creating an application where a user can create their own posts, and other users can comment on the posts.
I have already tried retrieving comments from the database, and displaying them for that certain post, however this has been unsuccessful
Here is my code to tackle this problem:
views.py
def comment(request, pk):
form = CommentForm()
comments = Comment.objects.filter(post=pk)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = Comment()
comment.body = form.cleaned_data['body']
comment.user = request.user
comment.post = Post.objects.get(pk=pk)
comment.save()
return redirect('home')
return render(request, 'posts/comments.html')
else:
return render(request, 'posts/comments.html', {'error': 'Please submit valid data'})
else:
return render(request, 'posts/comments.html', {'form': form}, {'comments': comments})
comments.html
{% block content %}
<div class="container">
{% for com in comments.all %}
<p>{{ com.body }}</p>
<br>
{% endfor %}
{% if error %}
{{ error }}
<br>
<br>
{% endif %}
<br>
<br>
<br>
<br>
<br>
<form method="post">
<h2> Comment</h2>
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary">
Comment</button>
</form>
</div>
{% endblock %}
models.py
class Comment(models.Model):
body = models.CharField(max_length=130)
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
def __str__(self):
return self.body
urls.py
path('create/', post_views.Create.as_view(), name='create'),
path('post/<int:pk>/', post_views.DetailPost.as_view(), name='detail'),
path('comment/<int:pk>/', post_views.comment, name='comment'),
urls.py for home
path('admin/', admin.site.urls),
#HOME
path('', post_views.home, name='home'),
This is expected to display a posts comments when a button is pressed to view the post, however the comments do not show. See this here

Python Django How to save choice using model class "CHOICE"?

In my models.py, I have class with LEVEL_CHOICES and Level.
First I builded my project with a textfield Level and it worked. Then I decided to change my Level in order to give users only certain choices. Therefore I edited my models.py and I have now:
class Eleve(models.Model):
FIRST = 'FIRST'
SECOND = 'SECOND'
THIRD = 'THIRD'
LEVEL_CHOICES = (
('FIRST', 'School'),
('SECOND', 'HighSchool'),
('THIRD', 'University'),
)
Level = models.CharField(max_length=3, choices=LEVEL_CHOICES, default='FIRST')
I think that there is a problem in my views.py because I'am able to save class Eleve through Admin app. I'm also using a decorator in order to have REcaptchaV2.
def Form(request):
form = ResgisterStud(request.POST)
if request.recaptcha_is_valid and form.is_valid():
form.save(commit=False)
form.save()
return render(request, 'form.html', {'form': form})
else:
return render(request, 'form.html', {'form': form})
my forms.py
class ResgisterStud(forms.ModelForm):
class Meta:
model = Eleve
My Form.html
<form action="{% url "form" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="col-md-6 form-group">
{{ form.Level|add_class:"form-control" }}
</div>
<script src='https://www.google.com/recaptcha/api.js'></script>
<div class="form-group g-recaptcha" data-sitekey="***"></div>
{% if messages %}
{% for message in messages %}
{{ message }}
{% endfor %}
{% endfor %}
{% endif %}
</form>

Want to display an image

I am having a slight problem. I want a django app that can upload and display an image. Currently, it can upload the image but I cannnot display that image.
So for example, {{comment.photo}} will print out the path C:/Users/AQUIL/Desktop/myproject/images/P1000992.JPG. But I want to see that image on the screen. Not the path. How do I print out the image to the screen?
Here is some information that may help.
models.py
class Comment(models.Model):
name = models.CharField(max_length = 40)
datetime = models.DateTimeField(default=datetime.now)
photo = models.ImageField(upload_to='C:/Users/AQUIL/Desktop/myproject/media/images', blank=True, null=True)
note = models.TextField()
def __unicode__(self):
return unicode(self.name)
views.py
def home(request):
comments = None
try:
comments = Comment.objects.order_by('-datetime')
except:
return HttpResponseNotFound()
return render_to_response('home.html', {'comments':comments}, context_instance=RequestContext(request))
def add_notes(request):
comments = Comment.objects.all()
if request.method == 'POST':
form = CommentForm(request.POST or None, request.FILES)
if form.is_valid():
comments.datetime = datetime.now()
form.save(True)
return HttpResponseRedirect(reverse(home))
else:
form = CommentForm()
return render_to_response('form.html', {'form':form,'comments':comments}, context_instance = RequestContext(request))
home.html
{% extends "base.html" %}
{% block content %}
<H2>List of Comments</H2>
<div style="overflow:auto;padding: 10px; border:1px solid black; height:150px; width:700px;">
{% for comment in comments %}
{{comment.photo}} <br/>
<b>Posted by: {{ comment.name }} Date: {{ comment.datetime.date }} Time: {{comment.datetime.time}}</b><br/>
<div style="font-size:125%">{{ comment.note }}</div><br/>
{% endfor %}
</div>
{% endblock %}
form.html
{% extends "base.html" %}
{% block content %}
<h3>Add Notes</h3>
<form enctype="multipart/form-data" action="" method="POST">
{% csrf_token %}
<table>
{{form.as_table}}
<br/>
</table>
<input type="submit" value="Save" STYLE="background-color:#E8E8E8; color:#181818 "/>
</form>
{% endblock %}
{% if comment.photo %} <img src="{{ comment.photo.url }}" alt="Photo" /> {% endif %}
See Geoffrey's comment for how to upload the image correctly.
The upload parameter of ImageField must be a local path, so replace:
photo = models.ImageField(upload_to='C:/Users/AQUIL/Desktop/myproject/media/images', blank=True, null=True)
by:
photo = models.ImageField(upload_to='images', blank=True, null=True)
Then set the MEDIA_ROOT in settings.py as:
MEDIA_ROOT = 'C:/Users/AQUIL/Desktop/myproject/media/'
Finally your image 'myImage.png' will be accessible at:
C:/Users/AQUIL/Desktop/myproject/media/images/myImage.png
And this tag should load the image:
<img src="/media/images/myImage.png" alt=""/>
depends of your MEDIA_URL in settings.py which should be:
MEDIA_URL = '/media/'
Rather then {{comment.photo}}
use {{comment.photo.url}}
see sample in the docs

Categories