Commenti e Form

Modello per i commenti

Nel file didattica/models.py aggiungere:

from django.core.urlresolvers import reverse

class Comment(models.Model):
       body = models.TextField()
       date = models.DateTimeField(null=True)
       course = models.ForeignKey(Course)
       created = models.DateTimeField(auto_now_add=True)
       class Meta:
           ordering = ('created',)
       def get_absolute_url(self):
           return reverse('comment-detail', kwargs={'pk': self.pk})
       def __str__(self):
           return 'Comment created {}'.format(self.created)

Configurazione URL

Nel file didattica/urls.py aggiungere a urlpatterns:

    url(r'^comments/$', views.CommentListView.as_view()),
    url(r'^comments/(?P<pk>[0-9]+)/$', views.CommentDetailView.as_view(), name='comment-detail'),

Viste per i commenti

Definiamo due viste per i commenti (lista e dettaglio) nel file didattica/views.py:

from .models import Comment

class CommentListView(ListView):
    model = Comment

class CommentDetailView(DetailView):
    model = Comment

Template per le viste

Per la lista dei commenti occorre creare un nuovo file con il template:

  • nella cartella didattica/templates/didattica/ creiamo il file comment_list.html

  • nel file appena creato didattica/templates/didattica/comment_list.html inseriamo il seguente codice HTML per il template:

<!DOCTYPE html>
<html>
<body>
<h1>Comments</h1>
{% regroup object_list|dictsort:"course.slug" by course as course_list %}
<ul>
{% for course in course_list %}
   <li>{{ course.grouper }}
    <ul>
        {% for item in course.list %}
          <li><a href="{% url 'comment-detail' pk=item.pk %}">{{ item.created|date:"D d M Y" }}</a> - {{ item.body|truncatechars:40 }}</li>
        {% endfor %}
    </ul>
    </li>
{% endfor %}
</ul>
</body>
</html>

Per il dettaglio sul contenuto dei commenti occorre creare un nuovo file con il template:

  • nella cartella didattica/templates/didattica/ creiamo il file comment_detail.html

  • nel file appena creato didattica/templates/didattica/comment_detail.html inseriamo il seguente testo HTML come template:

<!DOCTYPE html>
<html>
<body>
<h1>{{ object.pk }}</h1>
<p>Course: {{ object.course }}</p>
<p>Body: {{ object.body }}</p>
<p>Date: {{ object.date }}</p>
<p>Created: {{ object.created }}</p>
</body>
</html>

Aggiornamento del DB

Al termine, prima di poter utilizzare il tutto compiamo ancora i seguenti passi:

  • aggiorniamo il database eseguendo i seguenti comandi nella shell, sempre a partire dalla cartella in cui è presente il file manage.py:
python manage.py makemigrations
python manage.py migrate
  • registriamo i commenti nell'interfaccia di amministrazione inserendo al fondo del file didattica/admin.py le seguenti righe di python:
from didattica.models import Comment
admin.site.register(Comment)

results matching ""

    No results matching ""