Django - Как добавить форму комментария в конец опроса
Пожалуйста, помогите с этим. Я создал приложение для опроса (следуя учебнику TraversyMedia). Я хочу, чтобы пользователь мог добавить комментарий вместе с опросом. Я создал модель "Комментарий" и из админки могу установить комментарий к определенному вопросу и на первой странице могу отобразить его вместе с опросом по этому вопросу. Но я не знаю, как перенести эту форму "комментарий" на страницу пользователя, чтобы пользователь, выбрав один из вариантов опроса, оставил комментарий и он был сохранен вместе с вариантами опроса. Ниже вы найдете мои настройки. (Я создал form.py и установил класс и т.д., но я не знаю, что делать дальше). Спасибо
модели
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('publicat la:')
def __str__(self):
return self.question_text
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
class Comment(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="comments")
comment_text = models.TextField(null=True, blank=True)
def __str__(self):
return self.comment_text
просмотров
from .models import Question, Choice, Comment
# preluare si afisare intrebari din sondaj
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, 'sondaj/index.html', context)
# afisare optiuni aferente fiecarei intrebari din sondaj si intrebare in sine
def detail(request, question_id):
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404("Nu exista sondaje publicate")
return render(request, 'sondaj/detail.html', {'question' : question})
# preluare si afisare rezultate la nivelul fiecarei intrebari sondaj
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
comments = question.comments
return render(request, 'sondaj/results.html', {'question': question, 'comments' : comments})
# listare optiuni de ales pentru fiecare intrebare din sondaj
def vote(request, question_id):
#print (request.POST['choice'])
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# reafisare intrebare sondaj daca nu s-a ales nimic
return render(request, 'sondaj/detail.html', {
'question' : question,
'error_message' : "Trebuie sa selectezi una din variantele existente",
})
else:
selected_choice.votes += 1
selected_choice.save()
# redirectionare dupa vor; acum arata rezultatele dar trebuie sa creez mai bine o pagina de "multumesc pentru vot, adaud in url etc"
return HttpResponseRedirect(reverse('sondaj:results', args=(question.id,)))
формы
from dataclasses import fields
from django.forms import ModelForm
from .models import Comment
class CommentForm(ModelForm):
class Meta:
model = Comment
fields = ('__all__')
урлы
from django.urls import path
from . import views
app_name = 'sondaj'
urlpatterns = [
path('', views.index, name='index'),
path('<int:question_id>/', views.detail, name='detail'),
path('<int:question_id>/results/', views.results, name='results'),
path('<int:question_id>/vote/', views.vote, name='vote')
]
detail.html (здесь я хочу добавить "comment" пользователю и после отправки иметь возможность зарегистрировать комментарий alog с выбранным вариантом опроса)
<form action=" {% url 'sondaj:vote' question.id %} " method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
<label for="choice{{ forloop.counter }}" class="form-check custom-icon mt-4 mb-4">
<input type="radio" name="choice" class="form-check-input" id="choice{{ forloop.counter }}"
value="{{ choice.id }}">
<span class="form-check-label">
<span class="content">
<span for="choice{{ forloop.counter }}" class="heading mb-1 d-block lh-1-25">{{choice.choice_text }}</span>
<span class="d-block text-small text-muted">04.05.2021 - 12:00 </span>
</span>
</span>
</label>
{% endfor %}
<button class="m-auto btn btn-icon btn-icon-start btn-outline-primary mb-1" type="submit">
<i data-acorn-icon="send"></i>
<span>Trimite</span>
</button>
</form>