6. Testimonials - zdimon/pizza_store GitHub Wiki

Testimonials

Model

from django.db import models

class Testimonial(models.Model):
    email = models.EmailField(verbose_name='Email', max_length=100)
    name = models.CharField(verbose_name='Name', max_length=150, default='')
    message = models.TextField(verbose_name='Message')
    is_public = models.BooleanField(default=False)

Admin

class TestimonialAdmin(admin.ModelAdmin):
    list_display = ['email', 'message', 'is_public']

admin.site.register(Testimonial, TestimonialAdmin)

Template tag for messages

mkdir shop/templatetags
touch shop/templatetags/__init__.py

testimonials.py

from django import template
from django.template import Context
from shop.models import Testimonial
register = template.Library()

@register.simple_tag(takes_context=True)
def testimonial_tag(context, pizza):
    messages = Testimonial.objects.filter(pizza=pizza)
    t = context.template.engine.get_template('shop/testimonials_list.html')
    return t.render(Context({'messages': messages},autoescape=context.autoescape))

Template

<h4>Testimonials</h4>
{% for m in messages %}
    <div class="row">
       Name: {{ m.name  }}
    
       Message:  {{ m.message  }}
    </div>
{% endfor %}

Using

{% load testimonials %}    

{% testimonial_tag pizza %}

Object manager

# models/managers.py

from django.db.models.query import QuerySet

class TestimonialQuerySet(QuerySet):
    def public_posts(self):
        return self.filter(is_public=True)

TestimonialManager = TestimonialQuerySet.as_manager

Model

class Testimonial(models.Model):
    ...

    objects = TestimonialManager()        

Template tag

messages = Testimonial.objects.public_posts().filter(pizza=pizza)

Form

Captcha

https://django-simple-captcha.readthedocs.io/en/latest/usage.html

pip install django-simple-captcha        
    

INSTALLED_APPS = [
...
'captcha'
]

./manage.py migrate


from django import forms
from django.forms import ModelForm
from captcha.fields import CaptchaField
from shop.models import Testimonial

class TestimonialForm(ModelForm):
    'Testimonial model form'
    captcha = CaptchaField()
    class Meta:
        model = Testimonial
        fields = ['email', 'name', 'message', 'captcha']
⚠️ **GitHub.com Fallback** ⚠️