i can add comments in db and see its in admin panel but dont see added comments in posts (view_post.html).
i dont understand reason for this
models:
class Comment(models.Model):
name = models.CharField('Имя:', max_length=100)
create_date = models.DateField(blank=True, null=True)
text = models.TextField()
def __str__(self):
return '%s' % self.name
forms:
class CommentForm(ModelForm):
class Meta:
model = Comment
fields = ['name', 'create_date', 'text']
views:
def view_post(request, slug):
post_detail = get_object_or_404(Article, slug=slug)
form = CommentForm(request.POST or None)
if form.is_valid():
comment = form.save(commit=False)
comment.post_detail = post_detail
comment.save()
return redirect(request.path)
return render_to_response('view_post.html', {
'post_detail': post_detail, 'form': form },
context_instance=RequestContext(request))
post template:
{% extends 'base.html' %}
{% block head_title %}{{ post_detail.title }}{% endblock %}
{% block title %}{{ post_detail.title }}{% endblock %}
{% block content %}
{{ post_detail.body }}
{% if post_detail.comment_set.all %}
{% for comment in post_detail.comment_set.all %}
{{ comment.name }}
{{ comment.text }}
{% endfor %}
{% endif %}
<form action="" method="POST">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" name="submit" value="Submit" />
</form>
{% endblock %}
You set comment.post_detail to the current Article when saving, but there you don't actually seem to have a post_detail ForeignKey. In fact you don't seem to have any relationship between Comment and Article at all, or between Comment and anything.
Related
I have got an error when I tried to display a form in function-based view in Django. I could display it in another HTML file and users can make their comments to the blog. But, I think it can be more convenient for users if they can make a comment on the same blog-detail HTML file, so I wanna implement it.
When I tried, this error showed up. "NoReverseMatch at /blogs/blog/30/
Reverse for 'blog' with no arguments not found. 1 pattern(s) tried: ['blogs/blog/(?P[0-9]+)/$']"
Any comments can help me and thanks for your time in advance!!
Here are the codes I wrote...
from django import forms
from .models import Comment
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('user', 'text',)
#views.py
#login_required
def blog(request, pk):
blog = get_object_or_404(Blog, pk=pk)
form = CommentForm()
# if request.method == 'POST':
# form = CommentForm(request.POST)
# if form.is_valid():
# comment = form.save(commit=False)
# comment.blog = blog
# comment.save()
# return redirect('blog', pk=blog.pk)
# else:
# form = CommentForm()
if blog.link_1 is not None and blog.link_2 is not None:
link_1 = blog.link_1
link_2 = blog.link_2
context = {
'blog': blog,
'link_1': link_1,
'link_2': link_2,
'form': form,
}
elif blog.link_1 is not None or blog.link_2 is not None:
link_1 = blog.link_1
link_2 = blog.link_2
context = {
'blog': blog,
'link_1': link_1,
'link_2': link_2,
'form': form,
}
else:
context = {
'blog': blog,
'form': form,
}
return render(request, 'blog/blog.html', context)
#login_required
def add_comment(request, pk):
blog = get_object_or_404(Blog, pk=pk)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.blog = blog
comment.save()
return redirect('blog', pk=blog.pk)
else:
form = CommentForm()
context = {
'form': form,
}
return render(request, 'blog/blog.html', context)
#urls.py
path('blog/<int:pk>/', views.blog, name='blog'),
path('blog/<int:pk>/comment/', views.add_comment, name='add_comment'),
#blog.html
{% extends 'base.html' %}
{% block title %}|{{ blog.title }}{% endblock %}
{% block content %}
<div class="header-bar">
← 戻る
</div>
<div class="body-container">
<div class="created-edit-delete">
<p>
{% if request.user == blog.user %}
あなたが{{ blog.created }}に作成</p>
{% else %}
{{ blog.user }}が{{ blog.created }}に作成</p>
{% endif %}
<div class="icons">
{% if request.user == blog.user %}
{% endif %}
</div>
</div>
<h1>{{ blog.title }}</h1>
<p class="blog-content">{{ blog.content_1 }}</p>
{% if blog.content_2 %}
<p class="blog-content">{{ blog.content_2 }}</p>
{% endif %}
{% if blog.content_2 %}
<p class="blog-content">{{ blog.content_3 }}</p>
{% endif %}
<div class="ref-links">
{% if link_1 %}
参考リンク
{% endif %}
{% if link_2 %}
参考リンク
{% endif %}
</div>
<hr>
<div class="comment-area">
<div class="comment-form">
<h2>New comment</h2>
<form action="{% url 'add_comment' blog.id %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="button">追加</button>
</form>
</div>
<div class="comment-all">
{% for comment in blog.comments.all %}
<div class="comment">
<div class="date">{{ comment.created }}</div>
<strong>{{ comment.user }}</strong>
<p>{{ comment.text|linebreaks }}</p>
</div>
{% empty %}
<p>No comments here yet :(</p>
{% endfor %}
</div>
</div>
</div>
{% endblock %}
You have called blog URL here ← 戻る and forgot to pass id inside your URL that's why it's showing this error
NoReverseMatch at /blogs/blog/30/ Reverse for 'blog' with no arguments not found. 1 pattern(s) tried: ['blogs/blog/(?P[0-9]+)/$']
you have to pass id here like this
← 戻る
I am new to Django, and am stuck. I am creating a survey using two models: one to describe the survey question, and one to store the response (either a choice of answers defined by QUESTION_ANSWER_CHOICES, or a text field):
class PassengerRequirement (models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
...
question_number = models.CharField(max_length=12, default=0, unique=False)
is_yes_no_question = models.BooleanField(default=False, verbose_name='Is this a Yes/No Question?')
question_text = models.TextField(max_length=256, null=True, blank=True, help_text="Put the question in this field.")
...
class PassengerRequirementMeasurement (models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
survey_question = models.ForeignKey('PassengerRequirement',
related_name='passenger_requirement_answer',
on_delete=models.CASCADE)
survey_instance = models.ForeignKey('SurveyInstance',
related_name='passenger_requirement_measurements',
on_delete=models.CASCADE,
null=True)
answer_choice = models.CharField(max_length=1,
choices=QUESTION_ANSWER_CHOICES,
default=YES)
answer_text = models.TextField(max_length=256,
null=True,
blank=True,
help_text="Add Details")
Then using the modelformset_factory a formset in forms.py:
prFormSet = modelformset_factory(PassengerRequirementMeasurement,
fields=('answer_choice', 'answer_text'),
extra=0
)
And my view:
def passenger_requirements_pretravel(request):
surveyquestions = PassengerRequirement.objects.filter(...)
if request.method == 'POST':
formset = prFormSet(queryset=PassengerRequirement.objects.filter(...),
data=request.POST)
if formset.is_valid():
print('no problem')
else:
print(formset.errors)
...
else:
formset = prFormSet(queryset=PassengerRequirement.objects.filter(...)
return render(request, 'surveys/passenger_requirements_pretravel.html',
{'formset': formset, 'surveyquestions': surveyquestions})
I am looping through the surveyquestions and formset to display the questions and form fields:
<form action="{% url 'pr_pretravel' %}" method="post" class="mt-5">
{% csrf_token %}
{{ formset.management_form }}
{% for question in surveyquestions %}
{% with cntr=forloop.counter0 %}
<div class="q_{{ question.question_number|length }} form-group">
<h5 class="font-weight-bold">{{ question.question_number }}: {{ question.question_text }}</h5>
{% if question.is_yes_no_question == True %}
{% for form in formset %}
{% if cntr == forloop.counter0 %}
{{ form.answer_choice }}
{% endif %}
{% endfor %}
{% else %}
{% for form in formset %}
{% if cntr == forloop.counter0 %}
{{ form.answer_text }}
{% endif %}
{% endfor %}
{% endif %}
</div>
{% endwith %}
{% endfor %}
<input type="submit" value="Submit"/>
</form>
It's awkward I know but the only way I could figure out how to use both formset and surveyquestions.
The issue is, I can't get past the is_valid() method; it always returns a list of:
[{'id': ['This field is required.']}, {'answer_choice': ['This field is required.'],...
for each question in the list.
I've tried an approach modelled after this question but still get something similar:
<ul class="errorlist"><li>answer_choice<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
Any suggestions? Thank you!
The form doesn't display in the browser. The navbar and submit button show up but no form in between. The problem must be straightforward but I haven't been able to find the issue. Thank you for your help.
views.py
def ProductCreateView(request):
if request.method == 'POST':
form = ProductForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('set_app/product_list.html'))
else:
product_form = ProductForm()
return render(request, 'set_app/product_form.html', {'product_form':product_form})
forms.py
class ProductForm(forms.Form):
class Meta():
model = models.Product
fields = ('code', 'barcode', 'name', 'description', 'brand', 'status')
product_form.html
{% extends "set_app/basic_app_base.html" %}
{% block body_block %}
<h1>
{% if not form.instance.pk %}
Create Product
{% else %}
Update Product
{% endif %}
</h1>
<form method="post">
{% csrf_token %}
{{ product_form.as_p }}
<input type="submit" class="btn btn-primary" value="Submit">
</form>
{% endblock %}
Found the issue:
in forms.py
instead of
class ProductForm(forms.Form):
it should be
class ProductForm(forms.ModelForm):
I'm modifying the default article.html template that came with Aldryn Newsblog to allow for a comment form and listing of the comments for that specific article. I have included the form without a problem. But I can't figure out how to query the comments.
EDITED
Here is my list_comments.html template:
{% load cms_tags staticfiles sekizai_tags %}
{% if comments %}
{% for item in comments %}
<div class="comment paragraph">
<h4>{{ item.author }}</h4>
<p>{{ item.comment }}</p>
<p>{{ item.date }}</p>
</div>
{% endfor %}
{% else %}
<p>No comments exist on this blog. Be the first to comment!</p>
{% endif %}
and comment_form.html
{% load cms_tags staticfiles sekizai_tags %}
<div id="comment_form">
<div class="container constrained paragraph">
<h5>Submit a comment</h5>
<form method="post">
{% csrf_token %}
{{ comment_form }}
<input type="hidden" name="page" value="{{ article.id }}">
<input type="submit" value="Submit Comment">
</form>
</div>
And models.py:
class BlogComment(models.Model):
ip_address = models.CharField(max_length=255, verbose_name="IP Address")
date = models.DateTimeField(default=datetime.now)
article = models.CharField(max_length=255)
author = models.CharField(max_length=255)
comment = models.CharField(max_length=1000)
And in views.py I have these:
def display_form(request):
comment_form = CommentForm()
return render(request, 'comment_form.html', {'comment_form': comment_form})
def get_blog_comments(request):
qs = BlogComment.objects.all()
context = {'comments': qs, 'another': 'test'}
return render(request, 'list_comments.html', context)
And in both templates, the context variables are outputting nothing. I am at a loss for what I'm doing wrong. django.template.context_processors.request is included in my settings.py context_processors.
As already stated, the querying is done in your views.py file.
# views.py
def get_blog_comments(request):
if request.method == "GET":
qs = BlogComment.objects.all()
template = # location of template, ex. blog_list.html
context = {'obj_list': qs}
return render(request, template, context)
I am using haystack (2.1.1) and whoosh in my django (1.7) website. i am happy because it is working, but not completely. the app show the right searches but when i click in the results it doesn't go to the product page. it looks like i haven't configured something that make {{ result.object.get_absolute_url }} doesnt work properly. I hope any of you can help me (as reference i am putting all the code)
this is my app models (products/models)
from django.db import models
class Products(models.Model):
name = models.CharField(max_length=120)
description = models.TextField()
image1 = models.ImageField(upload_to='product_images', blank=True, null=True)
price = models.FloatField(default=0.00)
slug = models.CharField(max_length=50, blank=False, null=True)
pub_date = models.DateTimeField()
def __unicode__(self):
return str(self.name)
class Meta:
ordering =['-id']
verbose_name = ('Product')
verbose_name_plural = ('Products')
this is my search_indexes.py, that i put in the same folder of my app (products/search_indexes.py)
import datetime
from haystack import indexes
from products.models import Products
class ProductsIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
name = indexes.CharField(model_attr='name')
description = indexes.CharField(model_attr='description')
pub_date = indexes.DateTimeField(model_attr='pub_date')
def get_model(self):
return Products
def index_queryset(self, using=None):
return self.get_model().objects.filter(pub_date__lte=datetime.datetime.now())
I did the changes in the settings file
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
'PATH': os.path.join(os.path.dirname(__file__), 'whoosh_index'),
},
}
create the file in my template folder "templates/search/indexes/products/products_text.txt"
{{ object.name }}
{{ object.description }}
the HTML and urls are the same as in the website of haystack (just change the result.object.title for result.object.name). in URLS: (r'^search/', include('haystack.urls')) and html (templates/search/search.html)
{% extends 'base.html' %}
{% block content %}
<h2>Search</h2>
<form method="get" action=".">
<table>
{{ form.as_table }}
<tr>
<td> </td>
<td>
<input type="submit" value="Search">
</td>
</tr>
</table>
{% if query %}
<h3>Results</h3>
{% for result in page.object_list %}
<p>
{{ result.object.name }}
</p>
{% empty %}
<p>No results found.</p>
{% endfor %}
{% if page.has_previous or page.has_next %}
<div>
{% if page.has_previous %}{% endif %}« Previous{% if page.has_previous %}{% endif %}
{% if page.has_next %}{% endif %}Next »{% if page.has_next %}{% endif %}
</div>
{% endif %}
{% else %}
{# Show some example queries to run, maybe query syntax, something else? #}
{% endif %}
</form>
{% endblock %}
as i said before it does the search and show it. but i don't know why the {{ result.object.get_absolute_url }} is not working, so it shows the product tittle but doesn't link them to their pages.
You just need to define a get_absolute_url method explicitly on your model class:
class Products(models.Model):
...
def get_absolute_url(self):
return "/products/%s/" % self.slug
It would be even better to use reverse within this method, which will depend on your urlconf. More details here.