Django blog post_update function not working as intended - django

I am following a youtube channel to create a blog. I am stuck at post_update function. when i try to update the post the comment is getting updated, which should not happen in this scenario. where am I going wrong?
def post_update(request, id):
title = 'Update'
post = get_object_or_404(Post, id=id)
form = PostForm(
request.POST or None,
request.FILES or None,
instance=post)
author = get_author(request.user)
if request.method == "POST":
if form.is_valid():
form.instance.author = author
form.save()
return redirect(reverse("post-detail", kwargs={
'id': form.instance.id
}))
context = {
'title': title,
'form': form
}
return render(request, "post_create.html", context)
views.py
from django.db.models import Count, Q
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render, get_object_or_404, redirect, reverse
from .forms import CommentForm, PostForm
from .models import Post, Author
from marketing.models import Signup
def get_author(user):
qs= Author.objects.filter(user=user)
if qs.exists():
return qs[0]
return None
def search(request):
queryset = Post.objects.all()
query = request.GET.get('q')
if query:
queryset = queryset.filter(
Q(title__icontains = query) |
Q(overview__icontains = query)
).distinct()
context = {
'queryset' : queryset
}
return render(request, 'search_results.html', context)
def get_category_count():
queryset = Post \
.objects \
.values('categories__title') \
.annotate(Count('categories__title'))
return queryset
def index(request):
featured = Post.objects.filter(featured=True)
latest = Post.objects.order_by('-timestamp')[:3]
if request.method == "POST":
email = request.POST['email']
new_signup = Signup()
new_signup.email = email
new_signup.save()
context = {
'object_list' : featured ,
'latest' :latest
}
return render(request, 'index.html', context)
def blog(request):
category_count = get_category_count()
#print(category_count)
most_recent = Post.objects.order_by('-timestamp')[:3]
post_list = Post.objects.all()
paginator = Paginator(post_list, 4)
page_request_var ='page'
page = request.GET.get(page_request_var)
try:
paginated_queryset = paginator.page(page)
except PageNotAnInteger:
paginated_queryset = paginator.page(1)
except EmptyPage:
paginated_queryset = paginator.page(paginator.num_pages)
context = {
'queryset' : paginated_queryset,
'most_recent' : most_recent,
'page_request_var': page_request_var,
'category_count': category_count
}
return render(request, 'blog.html', context)
def post(request, id):
most_recent = Post.objects.order_by('-timestamp')[:3]
category_count = get_category_count()
post = get_object_or_404(Post, id=id)
form = CommentForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
form.instance.user= request.user
form.instance.post = post
form.save()
return redirect(reverse("post-detail", kwargs={
'id' : post.id
}))
context ={
'form' : form,
'post' : post,
'most_recent' : most_recent,
'category_count': category_count
}
return render(request, 'post.html', context)
def post_create(request):
title = 'Create'
form = PostForm(request.POST or None, request.FILES or None)
author = get_author(request.user)
if request.method == "POST":
if form.is_valid():
form.instance.author= author
form.save()
return redirect(reverse("post-detail", kwargs={
'id' : form.instance.id
}))
context = {
'title': title,
'form' : form
}
return render(request, "post_create.html", context)
def post_update(request, id):
title = 'Update'
post = get_object_or_404(Post, id=id)
form = PostForm(
request.POST or None,
request.FILES or None,
instance=post)
author = get_author(request.user)
if request.method == "POST":
if form.is_valid():
form.instance.author = author
form.save()
return redirect(reverse("post-detail", kwargs={
'id': form.instance.id
}))
context = {
'title': title,
'form': form
}
return render(request, "post_create.html", context)
def post_delete(request, id):
post = get_object_or_404(Post, id=id)
post.delete()
return redirect(reverse("post-list"))
Whatever is present in content is getting updated as comment which should not happen I am not able to understand the flow. And also <P> tag is visible which I have not used in html.
post_create.html
{% extends 'base.html ' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="col-4 offset-4 mb-5 mt-5">
<h3>{{ title }} an Article</h3>
{{ form.media }}
<form method="POST" action="." enctype="multipart/form-data">
{% csrf_token %}
{{ form|crispy }}
<button class="btn btn-primary" type="submit">Submit</button>
</form>
</div>
{% endblock content %}
model.py
from django.db import models
from django.contrib.auth import get_user_model
from django.urls import reverse
from tinymce import HTMLField
User = get_user_model()
# class PostView(models.Model):
# user = models.ForeignKey(User, on_delete=models.CASCADE)
# post = models.ForeignKey('Post', on_delete=models.CASCADE)
# def __str__(self):
# return self.user.username
class Author(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE)
profile_picture = models.ImageField()
def __str__(self):
return self.user.username
class Category(models.Model):
title = models.CharField(max_length = 20)
def __str__(self):
return self.title
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=100)
overview = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
content = HTMLField()
comment_count = models.IntegerField(default =0)
view_count = models.IntegerField(default =0)
author = models.ForeignKey(Author, on_delete = models.CASCADE)
thumbnail = models.ImageField()
categories = models.ManyToManyField(Category)
featured = models.BooleanField()
previous_post = models.ForeignKey('self', related_name = 'previous', on_delete = models.SET_NULL, blank=True, null = True)
next_post = models.ForeignKey('self', related_name = 'next', on_delete = models.SET_NULL, blank=True, null = True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={
'id': self.id
})
def get_update_url(self):
return reverse('post-update', kwargs={
'id': self.id
})
def get_delete_url(self):
return reverse('post-delete', kwargs={
'id': self.id
})
#property
def get_comments(self):
return self.comments.all().order_by('-timestamp')
class Comment(models.Model):
user = models.ForeignKey(User, on_delete = models.CASCADE)
timestamp = models.DateTimeField(auto_now_add=True)
content = models.TextField()
#profile_picture = models.ImageField()
post = models.ForeignKey(Post, related_name='comments', on_delete = models.CASCADE)
def __str__(self):
return self.user.username
post.html
{% extends 'base.html ' %}
{% load static %}
{% block content %}
<style>
.post-body img {
width: 100%;
}
</style>
<div class="container">
<div class="row">
<!-- Latest Posts -->
<main class="post blog-post col-lg-8">
<div class="container">
<div class="post-single">
<div class="post-thumbnail"><img src="{{ post.thumbnail.url }}" alt="..." class="img-fluid"></div>
<div class="post-details">
<div class="post-meta d-flex justify-content-between">
<div class="category">
{% for cat in post.categories.all %}
{{ cat }}
{% endfor %}
</div>
<div>
Update
Delete
</div>
</div>
<h1>{{ post.title }}<i class="fa fa-bookmark-o"></i></h1>
<div class="post-footer d-flex align-items-center flex-column flex-sm-row"><a href="#" class="author d-flex align-items-center flex-wrap">
<div class="avatar"><img src="{{ post.author.profile_picture.url }}" alt="..." class="img-fluid"></div>
<div class="title"><span>{{ post.author.user.username }}</span></div></a>
<div class="d-flex align-items-center flex-wrap">
<div class="date"><i class="icon-clock"></i> {{ post.timestamp|timesince }} ago</div>
<div class="views"><i class="icon-eye"></i> {{ post.view_count }}</div>
<div class="comments meta-last"><i class="icon-comment"></i>{{ post.comment_count }}</div>
</div>
</div>
<div class="post-body">
{{ post.content|safe }}
</div>
<div class="posts-nav d-flex justify-content-between align-items-stretch flex-column flex-md-row">
{% if post.previous_post %}
<a href="{{ post.previous_post.get_absolute_url }}" class="prev-post text-left d-flex align-items-center">
<div class="icon prev"><i class="fa fa-angle-left"></i></div>
<div class="text"><strong class="text-primary">Previous Post </strong>
<h6>{{ post.previous.title }}</h6>
</div>
</a>
{% endif %}
{% if post.next_post %}
<a href="{{ post.next_post.get_absolute_url }}" class="next-post text-right d-flex align-items-center justify-content-end">
<div class="text"><strong class="text-primary">Next Post </strong>
<h6>{{ post.next.title }}</h6>
</div>
<div class="icon next"><i class="fa fa-angle-right"> </i></div>
</a>
{% endif %}
</div>
<div class="post-comments">
<header>
<h3 class="h6">Post Comments<span class="no-of-comments">{{ post.comments.count }}</span></h3>
</header>
{% for comment in post.get_comments %}
<div class="comment">
<div class="comment-header d-flex justify-content-between">
<div class="user d-flex align-items-center">
<div class="image">
{% if comment.user.author %}
<img src="{{ comment.user.author.profile_picture.url }}" alt="NA" class="img-fluid rounded-circle">
{% else %}
<img src="{% static 'img/user.svg' %}" alt="..." class="img-fluid rounded-circle">
{% endif %}
</div>
<div class="title"><strong>{{ comment.user.username }}</strong><span class="date">{{ comment.timestamp|timesince }} ago</span></div>
</div>
</div>
<div class="comment-body">
<p>{{ comment.content }}</p>
</div>
</div>
{% endfor %}
</div>
{% if request_user.is_authenticated %}
<div class="add-comment">
<header>
<h3 class="h6">Leave a reply</h3>
</header>
<form method ="POST" action="." class="commenting-form">
{% csrf_token %}
<div class="row">
<div class="form-group col-md-12">
{{ form }}
</div>
<div class="form-group col-md-12">
<button type="submit" class="btn btn-secondary">Submit Comment</button>
</div>
</div>
</form>
</div>
{% endif %}
</div>
</div>
</div>
</main>
{% include 'sidebar.html' with most_recent=most_recent category_count=category_count %}
</div>
</div>
{% endblock %}

Related

AttributeError at /create_order/4 in Django

I am making inline formsets for create new products in each client, but when I try to save it throw me this error
views.py
Here im focus in the fuction "createOrder" for create the orders of customers
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import *
from django.forms import inlineformset_factory
from .forms import OrderForm
# Create your views here.
def home(request):
orders_value = Order.objects.all()
customer_value = Customer.objects.all()
total_orders_value = orders_value.count()
total_customers_value = customer_value.count()
pending_value = orders_value.filter(status='Pending').count()
delivered_value = orders_value.filter(status='Delivered').count()
context = {'orders_key': orders_value, 'customer_key': customer_value,
'total_orders_key':total_orders_value, 'pending_key': pending_value,
'delivered_key': delivered_value}
return render (request, 'accounts/dashboard.html', context)
def products(request):
products_value = Product.objects.all()
return render (request, 'accounts/products.html', {'products_key': products_value})
def customer(request, pk_test):
customer_value = Customer.objects.get(id=pk_test)
orders_value = customer_value.order_set.all()
orders_value_count = orders_value.count()
myFilter_value = OrderFilter()
context = {'customer_key':customer_value,
'orders_key': orders_value,
'orders_key_count': orders_value_count,
'myFilter_key':myFilter_value}
return render (request, 'accounts/customer.html', context)
def createOrder(request, pk):
OrderFormSet= inlineformset_factory(Customer, Order, fields=('product', 'status'), extra=10)
customer = Customer.objects.get(id=pk)
form_set_value= OrderFormSet(queryset=Order.objects.none() ,instance=customer)
if request.method == 'POST':
form_set_value= OrderFormSet(request.POST, instance=customer)
if form_set_value.is_valid:
form_set_value.save()
return redirect('/')
context = {'form_set_key':form_set_value}
return render(request, 'accounts/order_form.html', context)
def updateOrder(request, pk):
order = Order.objects.get(id=pk)
form_value = OrderForm(instance=order)
if request.method == 'POST':
form_value = OrderForm(request.POST, instance=order)
if form_value.is_valid:
form_value.save()
return redirect('/')
context = {'form_key':form_value}
return render(request, 'accounts/order_form.html', context)
def deleteOrder(request, pk):
order = Order.objects.get(id=pk)
if request.method == 'POST':
order.delete()
return redirect('/')
context={'item':order}
return render (request, 'accounts/delete.html', context)
forms.py
from django.forms import ModelForm, fields
from .models import Order
class OrderForm(ModelForm):
class Meta:
model = Order
fields = '__all__'
models.py
class Customer(models.Model):
name = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
data_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.name
class Order(models.Model):
STATUS = (
('Pending', 'Pending'),
('Out for delivery', 'Out for delivery'),
('Delivered', 'Delivered'),
)
customer = models.ForeignKey(Customer, null=True, on_delete=SET_NULL)
product = models.ForeignKey(Product, null=True, on_delete=SET_NULL)
status = models.CharField(max_length=200, null=True, choices=STATUS)
data_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.product.name
order_form.html
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<div class="row">
<div class="col-md-6">
<div class="card card-body">
<form action="" method="POST">
{% csrf_token %}
{{ form_set_key.management_form }}
{% for form in form_set_key %}
{{form}}
<hr>
{% endfor %}
<input type="submit" name="Submit">
</form>
</div>
</div>
</div>
{% endblock %}
customer.html
{% extends 'accounts/main.html' %}
{% block content %}
<br>
<div class="row">
<div class="col-md">
<div class="card card-body">
<h5>Customer:</h5>
<hr>
<a class="btn btn-outline-info btn-sm btn-block" href="">Update Customer</a>
<a class="btn btn-outline-info btn-sm btn-block" href="{% url 'create_order' customer_key.id %}">Place Order</a>
</div>
</div>
<div class="col-md">
<div class="card card-body">
<h5>Contact Information</h5>
<hr>
<p>Email: {{customer_key.email}}</p>
<p>Phone: {{customer_key.phone}}</p>
</div>
</div>
<div class="col-md">
<div class="card card-body">
<h5>Total Orders</h5>
<hr>
<h1 style="text-align: center;padding: 10px">{{orders_key_count}}</h1>
</div>
</div>
</div>
<br>
<div class="row">
<div class="col">
<div class="card card-body">
<form method="get">
<button class="btn btn-primary" type="submit">Search</button>
</form>
</div>
</div>
</div>
<br>
<div class="row">
<div class="col-md">
<div class="card card-body">
<table class="table table-sm">
<tr>
<th>Product</th>
<th>Category</th>
<th>Date Orderd</th>
<th>Status</th>
<th>Update</th>
<th>Remove</th>
</tr>
{% for order in orders_key %}
<tr>
<td>{{order.product}}</td>
<td>{{order.product.category}}</td>
<td>{{order.data_created}}</td>
<td>{{order.status}}</td>
<td>{{order.product}}</td>
<td><a class="btn btn-sm btn-info" href="{% url 'update_order' order.id %}">Update</a></td>
<td><a class="btn btn-sm btn-danger" href="{% url 'delete_order' order.id %}">Delete</a></td>
</tr>
{% endfor %}
</table>
</div>
</div>
</div>
{% endblock %}
Traceback
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\le\Desktop\django-course\Django(02-09-21)\crm1\accounts\views.py", line 51, in createOrder
form_set_value.save()
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\forms\models.py", line 681, in save
return self.save_existing_objects(commit) + self.save_new_objects(commit)
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\forms\models.py", line 817, in save_new_objects
if self.can_delete and self._should_delete_form(form):
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\forms\formsets.py", line 314, in _should_delete_form
return form.cleaned_data.get(DELETION_FIELD_NAME, False)
AttributeError: 'OrderForm' object has no attribute 'cleaned_data'
I guess the problem is create Order function but i can't find it.

Can't add comment form in Django web application

I have a trouble adding form-group (I believe it's bootstrap class).
The form-group doesn't do anything at all, or maybe it's a problem with form.author and form-body variables!?
More simply, I need UI comment section (now only I can add and edit comments from django admin page). Some code:
post_details.html
<article class="media content-section">
<form action="/post/{{ post.slug }}/" method="post">
{% csrf_token %}
<div class="form-group">
{{ form.author }}
</div>
<div class="form-group">
{{ form.body }}
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<ul>
{% for comment in post.comments.all %}
<p>
<b>#{{ comment.author }}</b>
<small>{{ comment.created_date }} </small>
</p>
<p> {{ comment.text }}</p>
<hr>
{% if comment.replies.all %}
<ul>
{% for reply in comment.replies.all %}
<p>{{ reply.text }}</p>
<hr>
{% endfor %}
</ul>
{% endif %}
{% endfor %}
<ul>
</article>
forms.py
from django import forms
class CommentForm(forms.Form):
author = forms.CharField(
max_length=60,
widget=forms.TextInput(
attrs={"class": "form-control", "placeholder": "Your Name"}
),
)
body = forms.CharField(
widget=forms.Textarea(
attrs={"class": "form-control", "placeholder": "Leave a comment!"}
)
)
views.py
def comment(request):
form = CommentForm()
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = Comment(
author=form.cleaned_data["author"],
body=form.cleaned_data["body"],
post=post,
)
comment.save()
context = {"post": post, "comments": comments, "form": form}
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = Comment(
author=form.cleaned_data["author"],
body=form.cleaned_data["body"],
post=post
)
comment.save()
comments = Comment.objects.filter(post=post)
context = {
"post": post,
"comments": comments,
"form": form,
}
models.py
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
author = models.ForeignKey(User, on_delete=models.CASCADE)
text = models.TextField()
created_date = models.DateField(auto_now_add=True)
def __str__(self):
return self.text
EDIT:
urls.py
from django.urls import path
from django.conf.urls import include, url
from . import views
from .views import PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView, UserPostListView
urlpatterns = [
#Blog section
path("", PostListView.as_view(), name='blog-home'),
path("user/<str:username>", UserPostListView.as_view(), name='user-posts'),
path('post/<slug:slug>/', PostDetailView.as_view(), name='post-detail'),
path("posts/new/", PostCreateView.as_view(), name='post-create'),
path("post/<slug:slug>/update/", PostUpdateView.as_view(), name='post-update'),
path("post/<slug:slug>/delete/", PostDeleteView.as_view(), name='post-delete'),
path("about/", views.about, name="blog-about"),
path("<category>/", views.blog_category, name="blog_category"),
]
I really need something like this (tried to follow this tutorial, but nothing works well :
My comment section:
I've looked into that tutorial and implemented myself. Here goes the answer:
urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.blog_index, name="blog_index"),
path("<slug:slug>/", views.post_detail, name="post_detail"),
path("<category>/", views.blog_category, name="blog_category"),
]
models.py
from django.db import models
from django.utils.text import slugify
class Category(models.Model):
name = models.CharField(max_length=20)
class Post(models.Model):
title = models.CharField(max_length=255)
body = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
categories = models.ManyToManyField("Category", related_name="posts")
slug = models.SlugField(unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
class Comment(models.Model):
author = models.CharField(max_length=60)
body = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
post = models.ForeignKey("Post", on_delete=models.CASCADE)
post_detail.html
{% extends "blog_app/base.html" %}
{% block page_content %}
<div class="col-md-8 offset-md-2">
<h1>{{ post.title }}</h1>
<small>
{{ post.created_on.date }} |
Categories:
{% for category in post.categories.all %}
<a href="{% url 'blog_category' category.name %}">
{{ category.name }}
</a>
{% endfor %}
</small>
<p>{{ post.body | linebreaks }}</p>
<h3>Leave a comment:</h3>
<form action="/blog/{{ post.pk }}/" method="post">
{% csrf_token %}
<div class="form-group">
{{ form.author }}
</div>
<div class="form-group">
{{ form.body }}
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<h3>Comments:</h3>
{% for comment in comments %}
<p>
On {{comment.created_on.date }}
<b>{{ comment.author }}</b> wrote:
</p>
<p>{{ comment.body }}</p>
<hr>
{% endfor %}
</div>
{% endblock %}
views.py
def post_detail(request, slug):
post = Post.objects.get(slug=slug)
comments = Comment.objects.filter(post=post)
form = CommentForm()
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = Comment(
author=form.cleaned_data["author"],
body=form.cleaned_data["body"],
post=post,
)
comment.save()
context = {"post": post, "comments": comments, "form": form}
return render(request, "blog_app/post_detail.html", context)
Edit
I've changed the code to support slug field generation from the title. I'm not handling exception, thus you gonna have look into it by yourself. Good luck.
I think the problem is you're using a Form and not a ModelForm.
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['author', 'text']
...
In your file views.py you have duplicated code and you don't have the return
statement:
return render(request, "post_details.html", context)

Why does my reply appear as a normal comment instead of being a reply to the a particular comment?

I am trying to make a reply function that will allow users to reply the comments but it is not able to display the reply as a child element . After getting posted it displays them as a normal comment.
Here,s the models.py for comments
class CommentManager(models.Manager):
def all(self):
qs = super(CommentManager,self).filter(parent = None)
return qs
class Comment(models.Model):
post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name = "comments")
name = models.CharField(max_length = 200)
body = models.TextField(default = True)
pub_date = models.DateTimeField(auto_now_add = True)
parent = models.ForeignKey('self',null = True,blank = True)
class Meta:
ordering = ['-pub_date']
def __str__(self):
return self.name
def replies(self):
return Comment.objects.filter(parent = self)
#property
def is_parent(self):
if self.parent is not None:
return False
return True
Here, s the views.py of comments
def BlogDetail(request,pk):
post = get_object_or_404(Post,pk = pk)
comment = CommentForm(request.POST or None)
subscribe = Subscribe()
parent_obj = None
if request.method == 'POST':
subscribe = Subscribe(request.POST)
comment = CommentForm(request.POST)
if comment.is_valid():
comment.instance.post = post
comment.save()
try:
parent_id = int(request.POST.get('parent_id'))
except:
parent_id = None
if parent_id:
parent_qs = Comment.objects.filter(id = parent_id)
if parent_qs.exists():
parent_obj = parent_qs.first()
elif subscribe.is_valid():
subscribe = subscribe.save(commit = True)
return render(request,'app/blog.html',{'blog_object':post,'comment':comment,
'subscribe':subscribe,'parent':parent_obj
})
Here,s the html for comments and replies
{% for i in blog_object.get_comments %}
<div class="container">
<div class="row">
<div class="col comment_head">
<strong>{{i.name}}</strong>
<div class="col comment_body">
<p>{{i.body}}</p>
</div>
</div>
</div>
<div class="border"></div>
<form action="." method="POST">
{% csrf_token %}
<div class="col">
<div class="form-group form-group-with-icon">
{{comment}}
<div class="form-control-border"></div>
</div>
</div>
<div class="col">
<p class="form-submit">
<input type="hidden" name="parent_id" id="parent_id" value="{{i.id}}">
<input name="submit" type="submit" value="Reply Comment">
</p>
</div>
</form>
</div>
</div>
{% for u in i.replies.all %}
<div class="container">
<div class="row">
<div class="col comment_head">
<strong>{{u.name}}</strong>
<div class="col comment_body">
<p>{{u.body}}</p>
</div>
</div>
</div>
<div class="border"></div>
{% endfor %}
{% endfor %}

Django creating update post function

I want to create a post update/edit function but I have a problem. When I click "Update" button there is no error but there is no change. I think reason of that a mistake that I made in models.py but I can not figure it out. And here is my code
models.py
class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=200)
.
.
.
def get_update_url(self):
return reverse('post:post_update', kwargs={'slug': self.slug})
views.py
def post_update(request, slug):
if not request.user.is_authenticated():
return Http404()
post = get_object_or_404(Post, slug=slug)
form = PostForm(request.POST or None, request.FILES or None, instance=post)
if form.is_valid():
form.save()
messages.success(request, "Updated")
return HttpResponseRedirect(get_absolute_url())
context = {
'form': form
}
return render(request, "blog/post_update.html", context)
post_update.html
{% extends 'blog/base.html' %}
{% load crispy_forms_tags %}
{% block body %}
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h1>Form</h1>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form|crispy }}
{{ form.media }}
<input class="btn btn-primary" type="submit" value="Create post">
</form>
</div>
</div>
</div>
{% endblock %}
post_detail.html
//update link
<p >update</p>
urls.py
url(r'^(?P<slug>[\w-]+)/update/$', post_update, name="update"),
forms.py
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'text',)
Where is my mistake? What can I do?

invalid literal for int() with base 10: 'a'

I am trying to create a comment model for a post in django.I want to print the user name along with the comment.
This is my comment model
class Comment(models.Model):
item = models.ForeignKey('app.Item', related_name='comments')
user = models.ForeignKey('auth.User', blank=True, null=True)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
approved_comment = models.BooleanField(default=False)
def approve(self):
self.approved_comment = True
self.save()
def __str__(self):
return self.text
This is my view
def add_comment_to_post(request, pk):
item = get_object_or_404(Item, pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.user = user.username
comment.item = item
comment.save()
return redirect('item_detail', pk=item.pk)
else:
form = CommentForm()
return render(request, 'app/add_comment_to_post.html', {'form': form}
)
This is my html code
{% for comment in item.comments.all %}
{% if user.is_authenticated or comment.approved_comment %}
<div class="comment">
<div class="date">
{{ comment.created_date }}
{% if not comment.approved_comment %}
<a class="btn btn-default" href="{% url 'comment_remove' pk=comment.pk %}"><span class="glyphicon glyphicon-remove"></span></a>
<a class="btn btn-default" href="{% url 'comment_approve' pk=comment.pk %}"><span class="glyphicon glyphicon-ok"></span></a>
{% endif %}
</div>
<p> {{comment.user}} <p>
<p>{{ comment.text|linebreaks }}</p>
</div>
{% endif %}
{% empty %}
<p>No comments here yet :(</p>
{% endfor %}