zoukankan      html  css  js  c++  java
  • 动手实践记录(利用django创建一个博客系统)

    1.添加一个分类的标签,和主表的关系是 外键

    class Category(models.Model):
        """
        分类
        """
    
        name = models.CharField('名称', max_length=16)
        def __unicode__(self):# 在Python3中用 __str__ 代替 __unicode__
            return self.name
    class Blog(models.Model):
        """
        博客
        """
    
        title = models.CharField('标题', max_length=32)
        author = models.CharField('作者', max_length=16)
        content = models.TextField('正文')
        created = models.DateTimeField('发布时间', auto_now_add=True)
    
        category = models.ForeignKey(Category, verbose_name='分类')
        tags = models.ManyToManyField(Tag, verbose_name='标签')

    在Blog里models.ForeignKey表明是外键,在Category最后面写def __unicode() 函数返回本身,是为了在后天管理时能显示分类的详细信息,而不是全是显示category

    views的代码:

                form = CommentForm2(request.POST) ##获取html中post的所有数据,将CommentForm2涉及到的传给form
           cleaned_data = form.cleaned_data ##将这些参数传递给cleaned_data,,       cleaned_data中的值类型与字段定义的Field类型一致。
    
    
                a=request.POST.get('cate_name',1)  ##获取post中cate_name,获取不到的话就填写1
                cleaned_data['category'] = Category.objects.get(name=a) ##因为是外键,所以要将这一条category都查出来,然后添加到blog里
                Blog.objects.create(**cleaned_data)  ##插入到blog

    2.添加一个分类的标签,和主表的关系是 多对多

    前面与分类类似,但views不同

                check_box_list = request.POST.getlist('tags_name')  ##因为是多对多,所以在html用的是多选框,会有多个参数,要用getlist
                for b in check_box_list:     
                    a=Tag.objects.get(name=b)  ##先找到post的参数值
                    b1= Blog.objects.get(title=form.cleaned_data['title'])  ##获取前面锁添加的那条Blog记录
                    b1.tags.add(a)    ##插入刚获取的tag值(也就是上面的a),注意一定是用b1.tags(b1是指在Blog,tags是tags字段),这样才会自动实现多对对关系
             ##多对多的关系在数据库中是:例如 A,B是多对多,,在A,B都看不到对方的数据,会自动创建C表记录A和B的相连关系。

    后台admin:

    from django.contrib import admin
    
    from .models import Blog,Category,Tag
    
    class BlogAdmin(admin.ModelAdmin):
        fieldsets = [
            (None,               {'fields': ['title']}),
            ('Date information', {'fields': ['author', 'content',  'category', 'tags']}),  ##这两个是进入最底层页面时,添加blog显示的参数,并可以排顺序
        ]
    
        list_display = ('title', 'author', 'content') ##这是点进blog时,能预览到的详情
    
    
    class CategoryAdmin(admin.ModelAdmin):
        fieldsets = [
            (None,               {'fields': ['name']}),
        ]
        
        list_display = ('id','name')
    
    
    admin.site.register(Blog, BlogAdmin)
    admin.site.register(Category,CategoryAdmin)
    admin.site.register(Tag)

    2016/12/27

    实现新建博客后跳转回首页

    def get_create(request):
        if request.method == 'GET':
            form = CommentForm2()  ##我有创建一个from2.py里面放了CommentForm2函数,views.py有导入from2,所以这句是表单初始化
            ctx = {'form': form,
                   'category': Category.objects.all().order_by('-id'),
                   'tags': Tag.objects.all().order_by('-id')}  ##ctx 是为了实现下面的传参,因为我在templates(也就我的html咯)有category和tags两个选框,所以这里也要加上
            return render(request, 'blog-create.html',ctx)
        else:
            form = CommentForm2(request.POST)
            if form.is_valid():
                cleaned_data = form.cleaned_data
                a=request.POST.get('cate_name',1) 
                cleaned_data['category'] = Category.objects.get(name=a)
                Blog.objects.create(**cleaned_data)
                check_box_list = request.POST.getlist('tags_name')
                for b in check_box_list:
                    a=Tag.objects.get(name=b)
                    b1= Blog.objects.get(title=form.cleaned_data['title'])
                    b1.tags.add(a)       
            return HttpResponseRedirect(reverse('blog_get_blogs'))

    与网站的交互分get和post,一般进入一个网站就是get,而从网页里面传数据出来就是post(好像post也可以访问其他网站,有种说法是get是在网址上能看到参数,而post不能,因为是后台处理吧,这句话不重要,我瞎说的 = = )

    上面的代码是,如果我是进入这个网站 就会返回一个初始化的表单;但如果我是提交的话就会将所填数据传到数据空中,并返回到blog_get_blogs 这个url中。

    添加分页的功能:

    def get_blogs(request):
        blogs = Blog.objects.all().order_by('-created')
        paginator = Paginator(blogs, 3) # Show 25 contacts per page
    
        page = request.GET.get('page')
        try:
            blog_list = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            blog_list = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            blog_list = paginator.page(paginator.num_pages)
        ctx = {
            'blogs': blogs,
            'blog_list': blog_list
        }
        return render(request, 'blog-list.html', ctx)

    原本只有blogs = Blog.objects.all().order_by('-created') 和ctx以下的,只是简单实现在主页中看到所有的博客,添加中间这一块就可以完成后台的分页,当然也要配合html。

    {% for blog in blog_list %}    <!-- 注意是blog_list -->
        <div class="blog">
            <div class="title">
                <a href="{% url 'blog_get_detail' blog.id %}"><h2>{{ blog.title }}</h2></a>
            </div>
            <div class="info">
                <span class="category" style="color: #ff9900;">{{ blog.category.name }}</span>
                 {% for tags in blog.tags.all%}
                 <span class="tags" style="color: #ff9900;">{{tags.name}}</span>
                {%endfor%}
                <span class="author" style="color: #4a86e8">{{ blog.author }}</span>
                <span class="created" style="color: #6aa84f">{{ blog.created|date:"Y-m-d H:i" }}</span>
            </div>
            <div class="summary">
                {{ blog.content|truncatewords:100 }}
            </div>
        </div>
    {% endfor %}
    
    <div class="pagination">
        <span class="step-links">
            {% if blog_list.has_previous %}
                <a href="?page={{ blog_list.previous_page_number }}">上一页</a>
            {% endif %}
    
            <span class="current">
                第 {{ blog_list.number }} 页,共 {{ blog_list.paginator.num_pages }} 页
            </span>
    
            {% if blog_list.has_next %}
                <a href="?page={{ blog_list.next_page_number }}">下一页</a>
            {% endif %}
        </span>
    </div>

    2016/12/28

    复用templates模板:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>{{webname}}</title>
    <link href="/static/css/style.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
    <table width="954" border="0" align="center" cellpadding="0" cellspacing="0" class="container">
      <tr>
        <td align="left" valign="top" style="display:block;" id ="menu">
            <table width="100%">
                <tr>
                    <td width="150">
                    </td>
                    <td>
                        <ul id="menu">
                            <li><a href="/">首页</a></li>
                            <li><a href="/product">产品介绍</a></li>
                            <li><a href="/service">服务支持</a></li>
                            <li><a href="/download">资料下载</a></li>
                            <li><a href="/faq">常见问题</a></li>
                            <li><a href="/about">关于我们</a></li>
                        </ul>
                </td>
                <td align="right" style="padding-right:10px;">
                      <b> 业务专线  </b>&nbsp;: 13726206588
                </td>
             </tr> 
            </table>       
        </td>
      </tr>
      <tr>
        <td height="243" align="center" valign="top">
            {% block topAd %}
           
            {% endblock %}
        </td>
      </tr>
      <tr>
        <td>
         {% block main %}
         
         {% endblock %}
        </td>
      </tr>
      <tr style="height:30px;">
      
      </tr>  
    </table>
    
    <table width="954px" border="0" cellspacing="0" cellpadding="0" align="center" style="background-color: #272e31;">
      <tr>
        <td width="9"></td>
        <td>
          <div style="margin-top:10px;margin-bottom:10px;">
            <label class="mylink">收银软件系列:</label>
            <a href="#" class="mylink">免费pos系统</a>&nbsp;
            <a href="#" class="mylink">免费商场POS系统</a>&nbsp;
            <a href="#" class="mylink">免费超市POS系统</a>&nbsp;
            <a href="#" class="mylink">服装POS系统</a>&nbsp;
            <a href="#" class="mylink">专卖店POS系统</a>&nbsp;
            <a href="#" class="mylink">免费收银软件</a>&nbsp;
            <br />
            <label class="mylink"> Copyright 2012-2013 yihaomen Limited. All right reserved.</label>
           
          </div>
        </td>
        <td align="right">Powered by yihaomen.com</td>
        <td width="9"></td>
      </tr>
    </table>
    
    </body>
    </html>
    {% extends "base.html" %}
    {% block topAd %}
        <img src="/static/img/banner_index.jpg" width="930" height="235" />
    {% endblock %}
    {% load functionTag %}
    {% block main %}
      <table width="100%" border="0" cellspacing="0" cellpadding="0">
         <tr>
           <td width="239" align="left" valign="top" style="padding-left:12px;">
           <table width="203" border="0" cellspacing="0" cellpadding="0" style="margin-bottom:14px;">
               <tr>
                 <td><img src="/static/img/main/header_news.gif" width="203" height="45" /></td>
               </tr>
               {% display_index_announce_widget %}
               <tr>
                 <td><img src="/static/img/main/footer.gif" width="203" height="9" /></td>
               </tr>
           </table>
           {%display_index_recent_faqs%}
           </td>
           <td width="426" valign="top">
               {%display_index_news_widget%}
           </td>
           <td width="290" align="right" valign="top" class="ourproducts">
            {% display_products_widget %}
           </td>
         </tr>
     </table>
    {% endblock %}

    这只是个例子,不是自己写的。

    第一张图是我用使用的模板base.html,重点是里面会有{% block topAD}   {endblock} 这个里面是指可以修改里面的参数。

    使用bootstrap:

    官方文档:https://docs.djangoproject.com/en/1.9/howto/static-files/

    先下载想要的模板,(做个人博客的话,极力推荐:http://www.cssmoban.com/cssthemes/6287.shtml)

    修改urls.py文件 

    from django.conf import settings
    from django.conf.urls.static import static
    
    urlpatterns = [
        # ... the rest of your URLconf goes here ...
    ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

    重点是开头要from static 和 最后一句 + XXX 

    在模板中首行加上
    {% load staticfiles %}


    模板中设计到样式的格式要改成这样
    <img src="{% static "js/myexample.js" %}" alt="My image"/>

    2016/12/30

    发送邮件:

    setting最后加上

    EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
    EMAIL_HOST = 'smtp.126.com'
    EMAIL_PORT = 25                                
    EMAIL_HOST_USER = 'ewew2150@126.com'       
    EMAIL_HOST_PASSWORD = 'xxx'           
    EMAIL_SUBJECT_PREFIX = u'django'
    EMAIL_USE_TLS = True                      
    DEFAULT_FROM_EMAIL = EMAIL_HOST_USER  

    views加上

    from django.core.mail import send_mail  
    
    
    
    
    send_mail('title for blog', 'blog comment', 'ewew2150@126.com', ['815410098@qq.com'], fail_silently=False)
    ##第一个是主题,第二个是内容
  • 相关阅读:
    Reporting Service筛选器的作用
    asp.net很好用的编辑器
    Filter函数详析
    很好用的模态弹出窗口,可自定义弹出窗口外观
    asp.net 3.5异步调用方法小结
    C#面向对象的一个简单例子,继承、接口、重写都用上了,还用到了工厂模式
    漂亮的ajax图片切换
    asp.net大文件上传组件
    jQuery中文入门指南,翻译加实例,jQuery的起点教程(转)
    DirectoryEntry的使用
  • 原文地址:https://www.cnblogs.com/tangbinghaochi/p/6222054.html
Copyright © 2011-2022 走看看