Модель class Book models Model book_code models IntegerField primary_k

 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
# Модель
class Book(models.Model):
book_code = models.IntegerField(primary_key=True)
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()
def __unicode__(self):
return self.title
class Meta:
verbose_name = "Книга"
verbose_name_plural = "Книги"
def get_fields(self):
fields = [ field for field in self._meta.fields ]
for field in fields:
yield field.name, getattr( self, field.name )
#Форма
from django.forms.util import flatatt
from models import Book
from django import forms
from django.forms import ModelForm
from django.forms import widgets
class ReadOnlyWidget(forms.Widget):
def render(self, name, value, attrs):
final_attrs = self.build_attrs(attrs, name=name)
if hasattr(self, 'initial'):
value = self.initial
return "%s" % (flatatt(final_attrs), value or '')
def _has_changed(self, initial, data):
return False
class ReadOnlyField(forms.Field):
widget = ReadOnlyWidget
def __init__(self, widget=None, label=None, initial=None, help_text=None):
forms.Field.__init__(self, label=label, initial=initial,
help_text=help_text, widget=widget)
def clean(self, value, initial):
self.widget.initial = initial
return initial
class BooksForm(ModelForm):
book_code = ReadOnlyField()
class Meta:
model = Book
def __init__(self, *args, **kwargs):
super(BooksForm, self).__init__(*args, **kwargs)
#self.fields['book_code'].widget = ReadOnlyWidget()
self.fields['title'].widget = widgets.Textarea(attrs={'cols': '80', 'rows': '2'})
#Представление
from django.shortcuts import render_to_response
from django.http import Http404
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from forms import BooksForm
from models import Book
def view_book(request, bcode):
try:
bk = Book.objects.get(pk = bcode)
except:
raise Http404()
return render_to_response('view_book.html', {'book':bk})
def edit_book(request, bcode):
try:
bk = Book.objects.get(pk = bcode)
except:
raise Http404()
if request.method == 'POST':
form = BooksForm(request.POST, instance = bk)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('www.books.views.view_book', args=(bcode,)))
else:
return render_to_response('edit_book.html', {'form':form})
else:
form = BooksForm(instance = bk)
return render_to_response('edit_book.html', {'form':form})