Preparation work
Create a new Django project
# 新建一个django项目 $ django-admin startproject mysite # 新建一个app $ django-admin startapp blog
Project structure
├── blog │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py ├── manage.py └── mysite ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py
# mysite/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'markdown2' ]
$ python3 manage.py runserver $ python manage.py collectstatic
Generally configure the url in urls.py, configure the model in models.py, and Configure View in views.py.
urls.py
Function views
1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
# blog/urls.py from django.conf.urls import url from blog import views urlpatterns = [ url(r'^blog/$', views.IndexView.as_view(), name='index'), url(r'^blog/article/(?P<article_id>\d+)$', views.ArticleDetailView.as_view(), name='detail'), url(r'^blog/category/(?P<cate_id>\d+)$', views.CategoryView.as_view(), name='category'), url(r'^blog/tag/(?P<tag_id>\d+)$', views.TagView.as_view(), name='tag'), ]</tag_id></cate_id></article_id>
Use the form of (?Pd+) to capture the value for the parameter in , such as (?P
# mysite/urls.py from django.conf.urls import url, include from django.contrib import admin from blog import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('blog.urls', namespace='blog', app_name='blog')) ]
The namespace parameter specifies the namespace for us, which means that the URL in this urls.py is under the blog app, so there will be no conflict even if there are the same URL under different apps.
Assuming that the user wants to access an article, it will automatically parse the URL corresponding to the blog:detail view function, and pass article.pk (the primary key of the article) to the detail view function, details
is the name
we specified in blog/urls.py
.
<a>{{ article.title }}</a>
If you want to access a directory
<a>{{ category.name }}</a>
models.py
django.db.models
is the basis of the orm framework, in Create three models
Article,
Category,
Tag in blog/models.py
.
class Article(models.Model): STATUS_CHOICES = ( ('d', 'Draft'), ('p', 'Published'), ) # 仍然使用默认的 objects 作为 manager 的名字 objects = ArticleManager() title = models.CharField('标题', max_length=70) body = models.TextField('正文') created_time = models.DateTimeField('创建时间', auto_now_add=True) last_modified_time = models.DateTimeField('修改时间', auto_now=True) status = models.CharField('文章状态', max_length=1, choices=STATUS_CHOICES) # blank和null要同时设置为null,详情参考官方文档 abstract = models.CharField('摘要', max_length=54, blank=True, null=True, help_text="可选,如若为空将摘取正文的前54个字符") views = models.PositiveIntegerField('浏览量', default=0) likes = models.PositiveIntegerField('点赞数', default=0) topped = models.BooleanField('置顶', default=False) category = models.ForeignKey('Category', verbose_name='分类', null=True, on_delete=models.SET_NULL) tags = models.ManyToManyField('Tag', verbose_name='标签集合', blank=True) def __str__(self): return self.title class Meta: ordering = ['-last_modified_time'] # 新增 get_absolute_url 方法 def get_absolute_url(self): # 这里 reverse 解析 blog:detail 视图函数对应的 url return reverse('blog:detail', kwargs={'article_id': self.pk})
Django provides us with many useful fields, such as the above-mentioned CharFiled
, TestField
, DateTimeFiled
, etc. For details, please Refer to official documentation.
One-to-many in Django is set in one, which corresponds to the classification of the article, and ForeignKey is the foreign key in the database. on_delete=models.SET_NULL means that after deleting a category (category), the foreign keys of all Articles under the category are set to null (empty), so we set null=True at the same time. Many-to-many is different, both sides need to be configured. Please refer to the official documentation for details.
class Category(models.Model): name = models.CharField('类名', max_length=20) created_time = models.DateTimeField('创建时间', auto_now_add=True) last_modified_time = models.DateTimeField('修改时间', auto_now=True) def __str__(self): return self.name
class Tag(models.Model): name = models.CharField('标签名', max_length=20) created_time = models.DateTimeField('创建时间', auto_now_add=True) last_modified_time = models.DateTimeField('修改时间', auto_now=True) def __str__(self): return self.name
Implementation of comment function
class BlogComment(models.Model): user_name = models.CharField('评论者名字', max_length=100) user_email = models.EmailField('评论者邮箱', max_length=255) body = models.TextField('评论内容') created_time = models.DateTimeField('评论发表时间', auto_now_add=True) article = models.ForeignKey('Article', verbose_name='评论所属文章', on_delete=models.CASCADE) def __str__(self): return self.body[:20]
class ArticleManage(models.Manager): """ 继承自默认的 Manager ,为其添加一个自定义的 archive 方法 """ def archive(self): date_list = Article.objects.datetimes('created_time', 'month', order='DESC') # 获取到降序排列的精确到月份且已去重的文章发表时间列表 # 并把列表转为一个字典,字典的键为年份,值为该年份下对应的月份列表 date_dict = defaultdict(list) for d in date_list: date_dict[d.year].append(d.month) # 模板不支持defaultdict,因此我们把它转换成一个二级列表,由于字典转换后无序,因此重新降序排序 return sorted(date_dict.items(), reverse=True)
We must first configure the corresponding configuration file in project_name/settings.py
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'DB_NAME', 'USER': 'DB_USER', 'PASSWORD': 'DB_PASSWORD', 'HOST': 'localhost', # Or an IP Address that your DB is hosted on 'PORT': '3306', } }
After the definition is completed, we execute the following command to generate the corresponding data table in the database:
$ python manage.py makemigrations $ python manage.py migrate
admins.py
Refer to Mozila's tutorials and official documents.
views.py
Markdown2 will be used below, so markdown2 must be added to INSTALLED_APP. However, this mardown parsing is very poor, and after finishing it, you have to download the corresponding markdown css file. , there is a dedicated website.
from blog.models import Article, Tag, Category from django.views.generic import ListView, DetailView import markdown2 class IndexView(ListView): # template_name属性用于指定使用哪个模板进行渲染 template_name = "blog/index.html" # context_object_name属性用于给上下文变量取名(在模板中使用该名字) context_object_name = "article_list" def get_queryset(self): article_list = Article.objects.filter(status='p') for article in article_list: article.body = markdown2.markdown(article.body, ) return article_list def get_context_data(self, **kwargs): kwargs['category_list'] = Category.objects.all().order_by('name') # 调用 archive 方法,把获取的时间列表插入到 context 上下文中以便在模板中渲染 kwargs['date_archive'] = Article.objects.archive() kwargs['tag_list'] = Tag.objects.all().order_by('name') return super(IndexView, self).get_context_data(**kwargs)
Because we need to perform markdown processing, we have redefined get_queryset
. If we do not want to perform corresponding processing, just formulate model
directly, get_context_data
can add some additional fields. For example, we will display catalogs and tags in the sidebar of the homepage in the future, so we need to add a category_list
and tag_list
here.
class ArticleDetailView(DetailView): model = Article template_name = "blog/detail.html" context_object_name = "article" # pk_url_kwarg会自动和model中相应的主键对应,aritlce_id就是下面配置的URLCONF pk_url_kwarg = 'article_id' # 为了让文章以markdown形式展现,我们重写get_object()方法 def get_object(self): obj = super(ArticleDetailView, self).get_object() obj.body = markdown2.markdown(obj.body) return obj # 新增 form 到 context def get_context_data(self, **kwargs): kwargs['comment_list'] = self.object.blogcomment_set.all() kwargs['form'] = BlogCommentForm() return super(ArticleDetailView, self).get_context_data(**kwargs)
class CategoryView(ListView): template_name = "blog/index.html" context_object_name = "article_list" def get_queryset(self): # url里的cate_id传递给CategoryView,传递的参数在kwargs属性中获取 article_list = Article.objects.filter(category=self.kwargs['cate_id'],status='p') for article in article_list: article.body = markdown2.markdown(article.body, ) return article_list def get_context_data(self, **kwargs): # 增加一个category_list,用于在页面显示所有分类,按照名字排序 kwargs['category_list'] = Category.objects.all().order_by('name') return super(CategoryView, self).get_context_data(**kwargs)
class TagView(ListView): template_name = "blog/index.html" context_object_name = "article_list" def get_queryset(self): """ 根据指定的标签获取该标签下的全部文章 """ article_list = Article.objects.filter(tags=self.kwargs['tag_id'], status='p') for article in article_list: article.body = markdown2.markdown(article.body, extras=['fenced-code-blocks'], ) return article_list def get_context_data(self, **kwargs): kwargs['tag_list'] = Tag.objects.all().order_by('name') return super(TagView, self).get_context_data(**kwargs)
from django.views.generic.edit import FormView class CommentPostView(FormView): form_class = BlogCommentForm template_name = 'blog/detail.html' def form_valid(self, form): target_article = get_object_or_404(Article, pk=self.kwargs['article_id']) # 调用ModelForm的save方法保存评论,设置commit=False则先不保存到数据库, # 而是返回生成的comment实例,直到真正调用save方法时才保存到数据库。 comment = form.save(commit=False) # 把评论和文章关联 comment.article = target_article comment.save() # 评论生成成功,重定向到被评论的文章页面,get_absolute_url 请看下面的讲解。 self.success_url = target_article.get_absolute_url() return HttpResponseRedirect(self.success_url) def form_invalid(self, form): target_article = get_object_or_404(Article, pk=self.kwargs['article_id']) # 不保存评论,回到原来提交评论的文章详情页面 return render(self.request, 'blog/detail.html', { 'form': form, 'article': target_article, 'comment_list': target_article.blogcomment_set.all(), })
template
##{% for %}Loop tag,
{% if %}Judge tag.
{{ variable }} are some very commonly used tags
context_object_name = "article_list" has been specified in views.py and has been set in
get_queryset () Markdown processing is performed in
{% for article in article_list %} {{article.title}}Usually a common parent template is set:
{% extends "base_generic.html" %} {% block content %} ... {% endblock %}It seems to be set like this:
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'blog/templates')] , 'APP_DIRS': True, ... ]Static fileDue to the loss of the source code, I don’t remember the specific situation clearly. The static file path must be set correctly. If the js file loads abnormally, it may be a problem with the loading order. base_generic.html is probably in the following format:
nbsp;html> {% load staticfiles %} <meta> <title>Myblog</title> <link> <link> <link> ...There seems to be a problem with the following settings:
# mysite/settings.py STATIC_URL = '/static/' STATICFILES = os.path.join(BASE_DIR, 'blog/static')Please refer to the official documentation for detailsDeploymentUse uwsgi+nginx/etc/nginx/sites-available/mysite.conf, blog is the app name, and the static file is placed below. It is recommended to place it directly under mysite. The same is true for template:
server { listen 80; location /static/ { alias /home/omrsf/mysite/blog/static/; } location / { uwsgi_pass 127.0.0.1:8001; include /etc/nginx/uwsgi_params; } }
uwsgi -i uwsgi.ini to start the uwsgi process, combined with
nohup &:
[uwsgi] socket = 127.0.0.1:8001 chdir=/home/ormsf/mysite/ wsgi-file = mysite/wsgi.py processes = 2 threads = 4 chmod-socket = 664improvementcurrent article The model is registered directly in admin.py, and then published in the admin background. It can be made into an API interface and an online editor. Add basic user authentication function. Fragmentary knowledge pointsThe difference between null and blank
- null is for the database. If null=True, it means that the field of the database can Is empty.
- blank is for forms. If blank=True, it means that you don’t need to fill in this field when filling in your form, such as when adding a model record in the admin interface. What you can intuitively see is that the field is not bold.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6
Visual web development tools