Article From:https://www.cnblogs.com/Lujun1028/p/9737857.html

1、Verification Code

 1 import random
 2 from PIL import Image, ImageDraw, ImageFont, ImageFilter
 3 
 4 _letter_cases = "abcdefghjkmnpqrstuvwxy"  # Lower case letters to remove I, l, O, Z that may interfere.
 5 _upper_cases = _letter_cases.upper()  # Capital
 6 _numbers = ''.join(map(str, range(3, 10)))  # number
 7 init_chars = ''.join((_letter_cases, _upper_cases, _numbers))
 8 
 9 
10 def create_validate_code(size=(120, 30),
11                          chars=init_chars,
12                          img_type="GIF",
13                          mode="RGB",
14                          bg_color=(238, 99, 99),
15                          fg_color=(0, 0, 255),
16                          font_size=18,
17                          font_type="Monaco.ttf",
18                          length=4,
19                          draw_lines=True,
20                          n_line=(1, 2),
21                          draw_points=True,
22                          point_chance=2):
23     """
24     @todo: Generate verification code images25     @param size: The size, format (width, height) of the picture is (120, 30) by default.26     @param chars: Allowed character set, format string27     @param img_type: The format of the picture saved is GIF by default, and GIF, JPEG, TIFF, PNG are optional.28     @param mode: Picture mode, defaults to RGB29     @param bg_color: The background color is white by default.30     @param fg_color: The foreground color, the character of the verification code, and the default is blue #0000FF.31     @param font_size: Verifying code font size32     @param font_type: Verification code font, defaults to ae_AlArabiya.ttf33     @param length: Number of verification code characters34     @param draw_lines: Do you want to disturb the line?35     @param n_lines: The number of lines of interference line, the format tuple, by default (1, 2), only when draw_lines is True effective.36     @param draw_points: Do you draw interference points?37     @param point_chance: The probability of occurrence of interference points, size range [0, 100]38     @return: [0]: PIL ImageExample39     @return: [1]: The string in the verification code picture40     """
41     width, height = size  # Wide and high
42     # Create graphics
43     img = Image.new(mode, size, bg_color)
44     draw = ImageDraw.Draw(img)  # Create a brush
45 
46     def get_chars():
47         """Generates a string of given length and returns the list format."""
48         return random.sample(chars, length)
49 
50     def create_lines():
51         """Drawing interference lines"""
52         line_num = random.randint(*n_line)  # Number of interference lines
53         for i in range(line_num):
54             # starting point
55             begin = (random.randint(0, size[0]), random.randint(0, size[1]))
56             # End point
57             end = (random.randint(0, size[0]), random.randint(0, size[1]))
58             draw.line([begin, end], fill=(0, 0, 0))
59 
60     def create_points():
61         """Draw interference points"""
62         chance = min(100, max(0, int(point_chance)))  # The size is limited to [0, 100]
63         for w in range(width):
64             for h in range(height):
65                 tmp = random.randint(0, 100)
66                 if tmp > 100 - chance:
67                     draw.point((w, h), fill=(0, 0, 0))
68 
69     def create_strs():
70         """Drawing verification code characters"""
71         c_chars = get_chars()
72         strs = ' %s ' % ' '.join(c_chars)  # Each character is separated by spaces before and after.
73         font = ImageFont.truetype(font_type, font_size)
74         font_width, font_height = font.getsize(strs)
75 
76         draw.text(((width - font_width) / 3, (height - font_height) / 3),
77                   strs, font=font, fill=fg_color)
78 
79         return ''.join(c_chars)
80 
81     if draw_lines:
82         create_lines()
83     if draw_points:
84         create_points()
85     strs = create_strs()
86     # Graphic distortion parameter
87     params = [1 - float(random.randint(1, 2)) / 100,
88               0,
89               0,
90               0,
91               1 - float(random.randint(1, 10)) / 100,
92               float(random.randint(1, 2)) / 500,
93               0.001,
94               float(random.randint(1, 2)) / 500
95               ]
96     img = img.transform(size, Image.PERSPECTIVE, params)  # Create distortion
97     img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)  # Filter, boundary enhancement (greater threshold)
98     return img, strs

check_code.py

Need to match MONACO.TTF font usage

2、paging

 1 class Pagination(object):
 2     def __init__(self,totalCount,currentPage,CurentUrl,perPageItemNum=3,maxPageNum=3,):
 3         # Total number of data
 4         self.total_count = int(totalCount)
 5         # Current page
 6         try:
 7             v = int(currentPage)
 8             if v <= 0:
 9                 v = 1
10             self.current_page = v
11 
12         except Exception as e:
13             self.current_page = 1
14         # Number of rows per page
15         self.per_page_item_num = int(perPageItemNum)
16         # Maximum number of pages
17         self.max_page_num = int(maxPageNum)
18         self.current_url = CurentUrl
19 
20     def start(self):
21         return (self.current_page - 1)*self.per_page_item_num
22 
23     def end(self):
24         return self.current_page*self.per_page_item_num
25 
26     @property
27     def num_pages(self):
28         a,b = divmod(self.total_count,self.per_page_item_num)
29         if b == 0:
30             return a
31         return a+1
32 
33     @property
34     def pager_num_range(self):
35         # Current page
36         # self.current_page
37         # Maximum number of page numbers 7
38         # self.per_page_num
39         # PageCount
40         # self.num_pages
41         # Judgement of minimum extreme value
42         if self.max_page_num > self.num_pages:
43             # According to the current page dynamic generation, set the number of page display.
44             return range(1, self.num_pages + 1)
45         # The total number of pages is very long.
46         part = int(self.max_page_num/2)
47 
48         if part >= self.current_page:
49             return range(1, self.max_page_num + 1)
50 
51         # Maximum extreme value
52         if (self.current_page + part) >= self.num_pages:
53             return range(self.num_pages - self.max_page_num + 1, self.num_pages + 1)
54 
55         return range(self.current_page - part, self.current_page + part +1)
56 
57     def page_str(self):
58         page_list = []
59 
60         if self.current_page ==1:
61             prev = "<li><a href='#'>The last page is < /a> < /li>"
62         else:
63             prev = "<li><a href='%s?p=%s'>The last page is < /a> < /li>" %(self.current_url,self.current_page-1)
64         page_list.append(prev)
65 
66         first = "<li><a href='%s?p=1'>The home page is < /a> < /li>" % self.current_url
67         page_list.append(first)
68 
69         for i in self.pager_num_range:
70             if self.current_page == i:
71                 tem = "<li class='active'><a href='%s?p=%s'>%s</a></li>" % (self.current_url, i,i)
72             else:
73                 tem = "<li><a href='%s?p=%s'>%s</a></li>" % (self.current_url, i, i)
74             page_list.append(tem)
75 
76         last = "<li><a href='%s?p=%s'>The tail page is < /a> < /li>" % (self.current_url, self.num_pages)
77         page_list.append(last)
78 
79         if self.current_page == self.num_pages:
80             nex = "<li><a href='#'>The next page is < /a>"
81         else:
82             nex = "<li><a href='%s?p=%s'>The next page is < /a> < /li>" % (self.current_url, self.current_page + 1)
83         page_list.append(nex)
84 
85         return ''.join(page_list)

pager.py

When you use, you need to pass in three parameters.

  - Total number of information

  - Current page

  - Current URL

1 obj_list = Pagination(article_list.count(), current_page, current_url)
2     data_list = article_list[obj_list.start():obj_list.end()]

Code in view function

3、formVerification

  1 from django import forms
  2 from django.forms import fields,widgets
  3 from repository import models
  4 from django.core.exceptions import ValidationError
  5 
  6 class RegisterForm(forms.Form):
  7     username = fields.CharField(
  8         label='User name',
  9         required=True,
 10         max_length=32,
 11         initial='enter one user name',
 12         error_messages={
 13             'required': 'User name can not be empty.',
 14             'min_length': 'User name too short',
 15             'invalid': 'Formatting error',
 16         }
 17     )
 18     password = fields.CharField(
 19         label='Password',
 20         required=True,
 21         max_length=32,
 22         min_length=6,
 23         error_messages={
 24             'required': 'The password must not be empty.',
 25             'min_length': 'Password length is too short.',
 26             'invalid': 'Formatting error',
 27         }
 28     )
 29     # fields.RegexField()   Custom regularization
 30     confirm_pwd = fields.CharField(
 31         label='Confirm the password',
 32         required=True,
 33         max_length=32,
 34         min_length=6,
 35         error_messages={
 36             'required': 'The password must not be empty.',
 37             'min_length': 'Password length is too short.',
 38             'invalid': 'Formatting error',
 39         }
 40     )
 41     email = fields.EmailField(
 42         widget=widgets.EmailInput(attrs={"class":"form-control","placeholder": "Enter the mailbox"}),
 43         label='mailbox',
 44         required=True,
 45         error_messages={
 46             'required': 'Can't be empty',
 47         }
 48     )
 49     # Pay attention to using cleaned_data.get ('username') value.
 50     def clean_username(self):
 51         ret = models.User.objects.filter(username=self.cleaned_data.get('username'))
 52         if not ret:
 53             return self.cleaned_data.get('username')
 54         else:
 55             raise ValidationError('User name already exists.')
 56 
 57     def clean_password(self):
 58         pwd = self.cleaned_data.get('password')
 59         if not pwd.isdigit():
 60             return self.cleaned_data.get('password')
 61         else:
 62             raise ValidationError('Not all numbers.')
 63 
 64     # Whether the password is consistent before and after verification
 65     def clean(self):
 66         password = self.cleaned_data.get('password')
 67         confirm_pwd = self.cleaned_data.get('confirm_pwd')
 68         if confirm_pwd == password:
 69             return self.cleaned_data
 70         else:
 71             raise ValidationError('Password inconsistency')
 72 
 73 class LoginForm(forms.Form):
 74     username = fields.CharField(
 75         label='User name',
 76         required=True,
 77         max_length=32,
 78         initial='enter one user name',
 79         error_messages={
 80             'required': 'User name can not be empty.',
 81         }
 82     )
 83     password = fields.CharField(
 84         label='Password',
 85         required=True,
 86         max_length=32,
 87         min_length=6,
 88         error_messages={
 89             'required': 'The password must not be empty.',
 90         }
 91     )
 92     def clean(self):
 93         user_list = models.User.objects.all().values_list('username','password')
 94         user_list = list(user_list)
 95         login_list = (self.cleaned_data.get('username'),self.cleaned_data.get('password'))
 96         if login_list in user_list:
 97             return self.cleaned_data
 98         else:
 99             raise ValidationError('ERROR Incorrect username or password')
100 
101 class ArticleForm(forms.Form):
102     title = fields.CharField(
103         label='Title',
104         widget=widgets.TextInput(attrs={'class':'form-control', 'placeholder':'Heading 5-32 characters'}),
105         required=True,
106         min_length=5,
107         max_length=32,
108         error_messages={
109             'required':'Can't be empty',
110             'min_length':'The title is at least 5 bytes.',
111             'max_length':'The title is at least 32 bytes.',
112         }
113     )
114     summary = fields.CharField(
115         label='brief introduction',
116         required=True,
117         widget=widgets.Textarea(attrs={'class':'form-control', 'placeholder':'A brief introduction to 10-64 characters'}),
118         max_length=32,
119         min_length=10,
120         error_messages={
121             'required':'Can't be empty',
122             'min_length':'The introduction is at least 10 bytes.',
123             'max_length':'The maximum is 64 bytes.',
124         }
125     )
126     detail = fields.CharField(
127         label='content',
128         required=True,
129         widget=widgets.Textarea(attrs={'id':'detail','class': 'kind-content', 'placeholder': 'A brief introduction to 32-256 characters'}),
130         max_length=256,
131         min_length=32,
132         error_messages={
133             'required': 'Can't be empty',
134             'min_length': 'The introduction is at least 32 bytes.',
135             'max_length': 'The introduction is at least 256 bytes.',
136         }
137     )
138     user_choice = models.User.objects.all().values_list('id','username')
139     user = fields.IntegerField(
140         label='author',
141         widget=widgets.Select(choices=user_choice, attrs={'class':'form-control'})
142     )
143     blog_choice = models.Blog.objects.all().values_list('id','title')
144     blog = fields.IntegerField(
145         label='Blog',
146         widget=widgets.Select(choices=blog_choice, attrs={'class':'form-control'})
147     )
148     tags_choice = models.Tags.objects.all().values_list('id', 'caption')
149     tags = fields.IntegerField(
150         label='Label',
151         widget=widgets.Select(choices=tags_choice, attrs={'class':'form-control'})
152     )
153     category_choice = models.Category.objects.all().values_list('id','caption')
154     category = fields.IntegerField(
155         label='classification',
156         widget=widgets.Select(choices=category_choice, attrs={'class':'form-control'})
157     )
158 
159     def clean(self):
160         self.cleaned_data['user_id'] = self.cleaned_data.get('user')
161         self.cleaned_data['tags_id'] = self.cleaned_data.get('tags')
162         self.cleaned_data['blog_id'] = self.cleaned_data.get('blog')
163         self.cleaned_data['category_id'] = self.cleaned_data.get('category')
164         del self.cleaned_data['user']
165         del self.cleaned_data['tags']
166         del self.cleaned_data['blog']
167         del self.cleaned_data['category']
168         return self.cleaned_data
169 
170 class TroubleForm(forms.Form):
171     title = fields.CharField(
172         label='Title',
173         required=True,
174         widget=widgets.TextInput(attrs={'class':'form-control', 'placeholder':'Enter the heading 5-32 characters.'}),
175         max_length=32,
176         min_length=5,
177         error_messages={
178             'required':'The title should not be empty.',
179             'min_length':'The title is at least 5 bytes.',
180             'invalid':'Formatting error',
181         }
182     )
183     detail = fields.CharField(
184         label='content',
185         required=True,
186         widget=widgets.Textarea(attrs={'id':'detail','class':'kind-content', 'placeholder':'Input 5-256 characters'}),
187         max_length=256,
188         min_length=5,
189         error_messages={
190             'required': 'Content can not be empty.',
191             'min_length': 'The content is at least 5 bytes.',
192             'invalid': 'Formatting error',
193         }
194     )

Registration, login, edit, add

Details about form components: update later

 

Leave a Reply

Your email address will not be published. Required fields are marked *