Commits

Svyatoslav Bulbakha committed 373ab35

Add tags'

  • Participants
  • Parent commits 92a190e

Comments (0)

Files changed (9)

djangoschool/apps/core/admin.py

 from django.contrib import admin
 
-from core.models import Entry, Comment, Blog
+from core.models import Entry, Comment, Blog, Tag
+from .forms import EntryForm
 
 
 class CommentInline(admin.TabularInline):
 
 
 class EntryAdmin(admin.ModelAdmin):
+    form = EntryForm
     inlines = (CommentInline,)
 
 
 admin.site.register(Entry, EntryAdmin)
 admin.site.register(Comment)
 admin.site.register(Blog)
+admin.site.register(Tag)

djangoschool/apps/core/forms.py

 from django import forms
+from django.utils.translation import ugettext_lazy as _
 
-from .models import Entry, Comment, Blog
+from .models import Entry, Comment, Blog, Tag
 
 
 class EntryForm(forms.ModelForm):
+    tags = forms.CharField(label=_('Tags'))
+
     class Meta:
         model = Entry
-        exclude = ('user',)
-        
+        exclude = ('user', 'tags')
+
+    def __init__(self, *args, **kwargs):
+        super(EntryForm, self).__init__(*args, **kwargs)
+
+        if self.instance:
+            self.fields['tags'].initial = ', '.join([
+                i.name for i in self.instance.tags.all()])
+
+    def clean_tags(self):
+        tags = self.cleaned_data.get('tags')
+        tag_list = []
+
+        for tag in tags.split(','):
+            tag = tag.strip()
+            obj, created = Tag.objects.get_or_create(name=tag)
+            tag_list.append(obj.pk)
+
+        return tag_list
+
+    def save(self, request, *args, **kwargs):
+        entry = super(EntryForm, self).save(commit=False, *args, **kwargs)
+        entry.user = request.user
+        entry.save()
+
+        entry.tags = self.cleaned_data.get('tags')
+        entry.save()
+
+        return entry
+
         
 class CommentForm(forms.ModelForm):
     class Meta:

djangoschool/apps/core/migrations/0005_auto__add_tag.py

+# -*- coding: utf-8 -*-
+import datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+
+class Migration(SchemaMigration):
+
+    def forwards(self, orm):
+        # Adding model 'Tag'
+        db.create_table('core_tag', (
+            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
+            ('name', self.gf('django.db.models.fields.CharField')(max_length=50)),
+        ))
+        db.send_create_signal('core', ['Tag'])
+
+        # Adding M2M table for field tags on 'Entry'
+        db.create_table('core_entry_tags', (
+            ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
+            ('entry', models.ForeignKey(orm['core.entry'], null=False)),
+            ('tag', models.ForeignKey(orm['core.tag'], null=False))
+        ))
+        db.create_unique('core_entry_tags', ['entry_id', 'tag_id'])
+
+    def backwards(self, orm):
+        # Deleting model 'Tag'
+        db.delete_table('core_tag')
+
+        # Removing M2M table for field tags on 'Entry'
+        db.delete_table('core_entry_tags')
+
+    models = {
+        'auth.group': {
+            'Meta': {'object_name': 'Group'},
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
+            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
+        },
+        'auth.permission': {
+            'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
+            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
+        },
+        'auth.user': {
+            'Meta': {'object_name': 'User'},
+            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
+            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
+            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
+            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
+            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
+        },
+        'contenttypes.contenttype': {
+            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
+            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
+        },
+        'core.blog': {
+            'Meta': {'object_name': 'Blog'},
+            'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
+            'desc': ('django.db.models.fields.TextField', [], {}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'title': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
+            'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
+            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
+        },
+        'core.comment': {
+            'Meta': {'ordering': "['created']", 'object_name': 'Comment'},
+            'content': ('django.db.models.fields.TextField', [], {}),
+            'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
+            'entry': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Entry']"}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
+        },
+        'core.entry': {
+            'Meta': {'object_name': 'Entry'},
+            '_content_rendered': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
+            'blog': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Blog']"}),
+            'content': ('markitup.fields.MarkupField', [], {'no_rendered_field': 'True'}),
+            'content_short': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
+            'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'tags': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['core.Tag']", 'symmetrical': 'False'}),
+            'title': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
+            'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
+            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
+        },
+        'core.tag': {
+            'Meta': {'object_name': 'Tag'},
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
+        }
+    }
+
+    complete_apps = ['core']

djangoschool/apps/core/models.py

 from markitup.fields import MarkupField
 
 
+class Tag(models.Model):
+    name = models.CharField(_('name'), max_length=50)
+    
+    class Meta:
+        verbose_name = _('tag')
+        verbose_name_plural = _('tags')
+
+    def __unicode__(self):
+        return self.name
+
+
 class Blog(models.Model):
     title = models.CharField(_('title'), max_length=200)
     desc = models.TextField(_('description'))
             blank=True)
     user = models.ForeignKey(User, verbose_name=_('user'))
     blog = models.ForeignKey(Blog, verbose_name=_('blog'))
+    tags = models.ManyToManyField(Tag, verbose_name=_('tags'))
     
     created = models.DateTimeField(auto_now_add=True)
     updated = models.DateTimeField(auto_now=True)

djangoschool/apps/core/urls.py

 urlpatterns = patterns('core.views',
     # Entry
     url(r'^$', 'entry_list', name='core_entry_list'),
+    url(r'^tag/(?P<tag_name>\w+)/$', 'entry_tag', name='core_entry_tag'),
     url(r'^(?P<entry_id>\d+)/$', 'entry_detail',
         name='core_entry_detail'),
     url(r'^add/$', 'entry_add', name='core_entry_add'),

djangoschool/apps/core/views.py

 from django.contrib import messages
 from django.utils.translation import ugettext_lazy as _
 
-from .models import Entry, Blog
+from .models import Entry, Blog, Tag
 from .forms import EntryForm, CommentForm, BlogForm
 
 
     })
 
 
+def entry_tag(request, tag_name):
+    tag = get_object_or_404(Tag, name=tag_name)
+    entry_list = Entry.objects.filter(tags__in=[tag])
+    paginator = Paginator(entry_list, settings.ENTRY_PER_PAGE)
+
+    page = request.GET.get('page')
+    try:
+        entries = paginator.page(page)
+    except PageNotAnInteger:
+        entries = paginator.page(1)
+    except EmptyPage:
+        entries = paginator.page(paginator.num_pages)
+
+    return render(request, 'core/entry_tag.html', {
+        'entries': entries,
+        'tag': tag,
+    })
+
+
 def blog_list(request):
     blog_list = Blog.objects.all()
     paginator = Paginator(blog_list, settings.BLOG_PER_PAGE)
     form = EntryForm(request.POST or None)
 
     if form.is_valid():
-        entry = form.save(commit=False)
-        entry.user = request.user
-        entry.save()
+        entry = form.save(request)
         return redirect(entry)
 
     return render(request, 'core/entry_add.html', {
     form = EntryForm(request.POST or None, instance=entry)
 
     if form.is_valid():
-        form.save()
+        form.save(request)
         return redirect(entry)
 
 

djangoschool/templates/core/entry_detail.html

 {% else %}
     <p>{{ entry.votes_count }}</p>
 {% endif %}
+<p><strong>{% trans 'Tags' %}</strong>: {{ entry.tags.all|join:', ' }}</p>
 
 <h2>{% trans "Comments" %}</h2>
 

djangoschool/templates/core/entry_list.html

         </h3>
         <p class="metainfo">{{ entry.created }}</p>
         {{ entry.content_short|default:entry.content|linebreaks }}
+        <p>
+            <strong>{% trans 'Tags' %}</strong>:
+            {% for tag in entry.tags.all %}
+                <a href="{% url core_entry_tag tag.name %}">{{ tag }}</a>{% if not forloop.last %}, {% endif %}
+            {% endfor %}
+        </p>
     </div>
 {% empty %}
     <p>{% trans 'Empty list' %}</p>

djangoschool/templates/core/entry_tag.html

+{% extends "core/entry_list.html" %}
+
+{% load i18n %}
+
+{% block title %}
+    {% block content_title %}{% blocktrans %}Entries tagged with "{{ tag }}" tag{% endblocktrans %}{% endblock %}
+{% endblock %}