My problem
Make comment model, and form for Django
Use {% for i in post.comment_set.all %}
no change html
Information saved in the comment form does not appear
how can i fix it?
MY top_detail.html
<form method="POST" action="{% url 'create_comment' post.id %}">
{% csrf_token %}
{{ comment_form }}
<input type="submit">
{% for i in post.comment_set.all %}
<p>comment: {{ i.subject }}</p>
<p>time: {{ i.created_at }}</p>
<hr>
{% endfor %}
</form>
MY models.py
from django.db import models
class Top(models.Model):
product_name = models.CharField(blank=True, null=True, max_length=30)
product_price = models.CharField(blank=True, null=True, max_length=30)
product_image = models.ImageField(blank=True, null=True, upload_to="images")
product_explain = models.TextField(blank=True, null=True, )
class Question(models.Model):
post = models.ForeignKey(Top, null=True, on_delete=models.CASCADE)
subject = models.CharField(null=True, max_length=150)
created_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.subject
MY urls.py
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
from .views import PostList
urlpatterns = [
path('home/', views.home, name='home'),
path('home/top', PostList.as_view(), name='top'),
path('home/top/<int:pk>/', views.top_detail, name='top_detail'),
path('search/', views.search, name='search'),
path('signup/', views.signup, name='signup'),
path('login/', auth_views.LoginView.as_view(template_name='main/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
path('create_comment/<int:post_id>', views.create_comment, name='create_comment'),
]
My views.py
def top_detail(request,pk):
post = get_object_or_404(Top, pk=pk)
post_list = Top.objects.get(pk=pk)
comment_form = CommentForm()
return render(request, 'main/top_detail.html', {'post':post, 'post_list':post_list,'comment_form':comment_form})
def create_comment(request, post_id):
filled_form = CommentForm(request.POST)
if filled_form.is_valid():
form = filled_form.save(commit=False)
form.post = Top.objects.get(id=post_id)
form.save()
return redirect('top_detail',post_id)
MY forms.py
class CommentForm(forms.ModelForm):
class Meta:
model = Question
fields = ('subject',)
Should the pk parts of top_detail and create_comment (request, post_id) in VIEWS.py be the same?
CodePudding user response:
You are mixing names. If you name something Question, don't call it by Comment. Same thing with Post and Top. It matters for your code.
For now, you have to use:
{{ post.question_set.all }}
But if I were you I would change naming, because it seems even you don't understand how it works :)
Like:
class Post(models.Model):
...
class Comment(models.Model):
post = models.ForeignKey(Post, null=True, on_delete=models.CASCADE)
...
then in template:
{{ post.comment_set.all }}
