2016-10-17 create a normal Django view¶
Contents
Le fichier singers/models.py¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 | #!/usr/bin/python
# -*- coding: utf8 -*-
"""The singers models.
"""
from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible
from django.db import models
from django.core.urlresolvers import reverse
@python_2_unicode_compatible
class Person(models.Model):
""" an actual singular human being """
name = models.CharField(blank=True, max_length=100)
email = models.EmailField()
def __str__(self):
return self.name
@python_2_unicode_compatible
class Group(models.Model):
""" a music group """
name = models.CharField(max_length=200,
unique=True,
help_text="Name of the group")
members = models.ManyToManyField(Person,
blank=True,
help_text="Enter text to search for and add each member of the group.")
url = models.URLField(blank=True)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Label(models.Model):
""" a record label """
name = models.CharField(max_length=200,
unique=True)
owner = models.ForeignKey(Person,
blank=True,
null=True)
url = models.URLField(blank=True)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Song(models.Model):
""" a song """
title = models.CharField(blank=False, max_length=200)
group = models.ForeignKey(Group)
def __str__(self):
return self.title
def get_absolute_url(self):
"""
https://docs.djangoproject.com/en/dev/ref/class-based-views/generic-editing/
"""
return reverse('singers:song_update',
kwargs={'pk': self.pk})
@python_2_unicode_compatible
class Release(models.Model):
""" a music release/product """
title = models.CharField(max_length=100)
catalog = models.CharField(blank=True,
max_length=100)
group = models.ForeignKey(Group, blank=True, null=True,
verbose_name="Русский текст (group)")
label = models.ForeignKey(Label,
blank=False,
null=False)
songs = models.ManyToManyField(Song,
blank=True)
def __str__(self):
return self.title
@python_2_unicode_compatible
class Author(models.Model):
""" Author has multiple books,
via foreign keys
"""
name = models.CharField(max_length=100)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Book(models.Model):
""" Book has no admin, its an inline in the Author admin"""
author = models.ForeignKey(Author)
title = models.CharField(max_length=100)
about_group = models.ForeignKey(Group)
mentions_persons = models.ManyToManyField(Person,
help_text="Person lookup renders html in menu")
def __str__(self):
return self.title
|
Le fichier singers/forms.py¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.forms.models import ModelForm
from ajax_select import make_ajax_field
from dal import autocomplete
from .models import (Release,
Song,
Author,
Book)
class ReleaseForm(ModelForm):
class Meta:
model = Release
exclude = []
# args: this model, fieldname on this model, lookup_channel_name
group = make_ajax_field(Release, 'group', 'group', show_help_text=True)
label = make_ajax_field(Release, 'label', 'label', help_text="Search for label by name")
# any extra kwargs are passed onto the field, so you may pass a custom help_text here
# songs = make_ajax_field(Release,'songs','song', help_text=u"Search for song by title")
# testing bug with no help text supplied
songs = make_ajax_field(Release, 'songs', 'song', help_text="", show_help_text=True)
# these are from a fixed array defined in lookups.py
title = make_ajax_field(Release, 'title', 'cliche', help_text="Autocomplete will suggest clichés about cats.")
class SongForm(ModelForm):
"""The Django form"""
class Meta:
model = Song
fields = ['title', 'group']
# args: this model, fieldname on this model, lookup_channel_name
group = make_ajax_field(Song, # this model
'group', # fieldname on this model
'group', # lookup_channel_name
help_text="Select the group")
class AuthorForm(ModelForm):
class Meta:
model = Author
fields = ('name',)
widgets = {
'name': autocomplete.Select(url='singers:author_autocomplete')
}
class BookForm(ModelForm):
class Meta:
model = Book
fields = ('title', 'author',)
widgets = {
'author': autocomplete.ModelSelect2(url='singers:author_autocomplete')
}
|
Le fichier singers/views.py¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.shortcuts import render_to_response
# https://docs.djangoproject.com/en/dev/ref/templates/api/
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.views.generic.edit import UpdateView
from ajax_select.fields import AutoCompleteField
# https://stackoverflow.com/questions/37915224/django-autocomplete-light-widgets-not-showing-up?rq=1
from dal import autocomplete
from .models import (Song,
Author,
Book)
from .forms import (SongForm,
AuthorForm,
BookForm)
class SearchForm(forms.Form):
q = AutoCompleteField('cliche',
required=True,
help_text="Autocomplete will suggest clichés about cats, but you can enter anything you like.",
label="Favorite Cliché",
attrs={'size': 100})
def search_form(request):
dd = {}
if 'q' in request.GET:
dd['entered'] = request.GET.get('q')
initial = {'q': "\"This is an initial value,\" said O'Leary."}
form = SearchForm(initial=initial)
dd['form'] = form
return render_to_response('search_form.html',
dd,
context=RequestContext(request))
class SongUpdate(UpdateView):
"""
url(r'^singers/song/(?P<pk>\d+)/update/$', SongUpdate.as_view(), name='song_update'),
Documentation:
- http://ccbv.co.uk/projects/Django/1.9/django.views.generic.edit/UpdateView/
"""
model = Song
form_class = SongForm
context_object_name = 'song'
template_name = 'singers/song/update.html'
def get_object(self, queryset=None):
"""Pour mémoriser self.demande_article"""
self.object = super(SongUpdate, self).get_object(queryset)
return self.object
def post(self, request, *args, **kwargs):
if "cancel" in request.POST:
url = self.get_success_url()
return HttpResponseRedirect(url)
else:
return super(SongUpdate, self).post(request, *args, **kwargs)
class AuthorAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
# Don't forget to filter out results depending on the visitor !
qs = Author.objects.all()
if self.q:
qs = qs.filter(name__istartswith=self.q)
return qs
class AuthorUpdate(UpdateView):
"""
url(r'^singers/song/(?P<pk>\d+)/update/$', SongUpdate.as_view(), name='song_update'),
Documentation:
- http://ccbv.co.uk/projects/Django/1.9/django.views.generic.edit/UpdateView/
"""
model = Author
form_class = AuthorForm
context_object_name = 'author'
template_name = 'singers/author/update.html'
def get_object(self, queryset=None):
"""Pour mémoriser self.demande_article"""
self.object = super(AuthorUpdate, self).get_object(queryset)
return self.object
def post(self, request, *args, **kwargs):
if "cancel" in request.POST:
url = self.get_success_url()
return HttpResponseRedirect(url)
else:
return super(AuthorUpdate, self).post(request, *args, **kwargs)
class BookUpdate(UpdateView):
"""
url(r'^singers/song/(?P<pk>\d+)/update/$', SongUpdate.as_view(), name='song_update'),
Documentation:
- http://ccbv.co.uk/projects/Django/1.9/django.views.generic.edit/UpdateView/
"""
model = Book
form_class = BookForm
context_object_name = 'author'
template_name = 'singers/author/update.html'
def get_object(self, queryset=None):
"""Pour mémoriser self.demande_article"""
self.object = super(BookUpdate, self).get_object(queryset)
return self.object
def post(self, request, *args, **kwargs):
if "cancel" in request.POST:
url = self.get_success_url()
return HttpResponseRedirect(url)
else:
return super(BookUpdate, self).post(request, *args, **kwargs)
|
Le fichier singers/urls.py¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #!/usr/bin/python
# -*- coding: utf8 -*-
from django.conf.urls import url
from .views import (SongUpdate,
BookUpdate,
AuthorAutocomplete)
urlpatterns = [
url(r'^song/(?P<pk>\d+)/update/$', SongUpdate.as_view(), name='song_update'),
url(r'^book/(?P<pk>\d+)/update/$', BookUpdate.as_view(), name='book_update'),
url(r'^author_autocomplete/$', AuthorAutocomplete.as_view(), name='author_autocomplete'),
]
|