django语法小结
东西挺多,容易忘记,随时补充完善,便于查阅回忆。:)
URL
from django.urls import path,re_path
urlpatterns = [
path(r"category/<int:pk>", CategoryView.as_view(), name="category"),
path(r"category/<str:name>", CategoryView.as_view(), name="category"),
(r'^feeds/categories/(?P<category_id>\d+)/$', LatestEntriesByCategory()),
re_path(r'comments/(?:page-(?P<page_number>\d+)/)?$', comments), # Nested arguments good
]
Model
class Link(models.Model):
...
pass
class RecursiveComment(models.Model):
parent = models.ForeignKey("self", on_delete=models.CASCADE, null=True, related_name="children", blank=True)
links=models.ManyToManyField(Link,related_name=comments)
related_name 字段,为外键模型索引本模型时属性名。
link=Link.objects.all()[0]
comment=RecursiveComment.objects.get_or_create(...)
comment.links.add(link)
link.comments.all()[0] #通过related_name引用关联的另一个模型集合
Template
过滤器
时区
{% load tz%}
{# localtime on #}
{% timezone "Asia/Shanghai" %}
{% for comment in object %}
{{comment.pub_date|date:"Y-m-d H:i"}}
{% endfor %}
{% endtimezone %}
{# endlocaltime #}
localtime utc timezone:"Asia/Shanghai"
时间
{{comment.pub_date|date:"Y-m-d H:i"}}
{% now|date:"H:i" %} {% now "Y" as current_year %} {% blocktrans %}Copyright {{ current_year }}{% endblocktrans %}
Available format strings:
Format character Description Example output
a 'a.m.' or 'p.m.' (Note that this is slightly different than PHP's output, because this includes periods to match Associated Press style.) 'a.m.'
A 'AM' or 'PM'. 'AM'
b Month, textual, 3 letters, lowercase. 'jan'
B Not implemented.
c ISO 8601 format. (Note: unlike others formatters, such as "Z", "O" or "r", the "c" formatter will not add timezone offset if value is a naive datetime (see datetime.tzinfo). 2008-01-02T10:30:00.000123+02:00, or 2008-01-02T10:30:00.000123 if the datetime is naive
d Day of the month, 2 digits with leading zeros. '01' to '31'
D Day of the week, textual, 3 letters. 'Fri'
e Timezone name. Could be in any format, or might return an empty string, depending on the datetime. '', 'GMT', '-500', 'US/Eastern', etc.
E Month, locale specific alternative representation usually used for long date representation. 'listopada' (for Polish locale, as opposed to 'Listopad')
f Time, in 12-hour hours and minutes, with minutes left off if they're zero. Proprietary extension. '1', '1:30'
F Month, textual, long. 'January'
g Hour, 12-hour format without leading zeros. '1' to '12'
G Hour, 24-hour format without leading zeros. '0' to '23'
h Hour, 12-hour format. '01' to '12'
H Hour, 24-hour format. '00' to '23'
i Minutes. '00' to '59'
I Daylight Savings Time, whether it's in effect or not. '1' or '0'
j Day of the month without leading zeros. '1' to '31'
l Day of the week, textual, long. 'Friday'
L Boolean for whether it's a leap year. True or False
m Month, 2 digits with leading zeros. '01' to '12'
M Month, textual, 3 letters. 'Jan'
n Month without leading zeros. '1' to '12'
N Month abbreviation in Associated Press style. Proprietary extension. 'Jan.', 'Feb.', 'March', 'May'
o ISO-8601 week-numbering year, corresponding to the ISO-8601 week number (W) which uses leap weeks. See Y for the more common year format. '1999'
O Difference to Greenwich time in hours. '+0200'
P Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off if they're zero and the special-case strings 'midnight' and 'noon' if appropriate. Proprietary extension. '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.'
r RFC 5322 formatted date. 'Thu, 21 Dec 2000 16:01:07 +0200'
s Seconds, 2 digits with leading zeros. '00' to '59'
S English ordinal suffix for day of the month, 2 characters. 'st', 'nd', 'rd' or 'th'
t Number of days in the given month. 28 to 31
T Time zone of this machine. 'EST', 'MDT'
u Microseconds. 000000 to 999999
U Seconds since the Unix Epoch (January 1 1970 00:00:00 UTC).
w Day of the week, digits without leading zeros. '0' (Sunday) to '6' (Saturday)
W ISO-8601 week number of year, with weeks starting on Monday. 1, 53
y Year, 2 digits. '99'
Y Year, 4 digits. '1999'
z Day of the year. 0 to 365
Z Time zone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. -43200 to 43
官网说明链接 https://docs.djangoproject.com/zh-hans/2.0/ref/templates/builtins/#date
内建过滤器
Adds the argument to the value. {{ value|add:"2" }}
Adds slashes before quotes {{ value|addslashes }} If value is "I'm using Django", the output will be "I\'m using Django".
Capitalizes the first character of the value {{ value|capfirst }} If value is "django", the output will be "Django".
Centers the value in a field of a given width "{{ value|center:"15" }}"
Removes all values of arg from the given string. {{ value|cut:" " }} If value is "String with spaces", the output will be "Stringwithspaces".
Formats a date according to the given format. {{ value|date:"D d M Y" }}
If value evaluates to False, uses the given default. Otherwise, uses the value. {{ value|default:"nothing" }}
If (and only if) value is None, uses the given default. Otherwise, uses the value. {{ value|default_if_none:"nothing" }}
Takes a list of dictionaries and returns that list sorted by the key given in the argument. {{ value|dictsort:"name" }}
dictsortreversed divisibleby escape escapejs filesizeformat force_escape get_digit iriencode join last
length length_is
Returns the first item in a list. {{ value|first }}
floatformat 34.23234 {{ value|floatformat:"-3" }} 34.232
{{ value|length_is:"4" }} {{ value|linebreaks }} {{ value|linenumbers }} {{ value|make_list }}
{{ some_list|slice:":2" }} {{ value|time:"H:i" }} {{ blog_date|timesince:comment_date }}
{{ conference_date|timeuntil:from_date }}
等等,还有很多,可以通过前面的链接参考官方文档。
view
class PostDetailView(DetailView, FormView):
model = Post
template_name = "techblog/post_detail.html"
success_url = reverse_lazy("techblog:home") #不加lazy报错
form_class = MyModelForm
context_object_name = "new_stocks" #默认object_list
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['now'] = timezone.now()
context['comments'] = self.object.comments.all()
return context
def get_queryset(self):
return category.post_set.all().order_by("-name")
def post(self, request, *args, **kwargs):
return HttpResponseRedirect(request.get_full_path())