Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Django学习记录(十六):Django by example -- Blog(十二) #52

Open
PyxYuYu opened this issue Nov 17, 2016 · 0 comments
Open

Django学习记录(十六):Django by example -- Blog(十二) #52

PyxYuYu opened this issue Nov 17, 2016 · 0 comments
Labels

Comments

@PyxYuYu
Copy link
Owner

PyxYuYu commented Nov 17, 2016

Success is finding satisfaction in giving a little more than you take.

0x01 Django

  • Build a Blog Application

    • Creating a comment system
      • 创建一个评论系统
      • 创建一个保存评论的模型
      • 创建一个表单用于提交和验证输入内容
      • 增加一个视图用于处理表单和保存评论到数据库
      • 编辑 post detail 模板,显示评论列表和增加评论的表单
    • 编辑 models.py 增加一个模型用于保存评论
       class Comment(models.Model):
           post = models.ForeignKey(Post, related_name='comments')
           name = models.CharField(max_length=80)
           email = models.EmailField()
           body = models.TextField()
           created = models.DateTimeField(auto_now_add=True)
           update = models.DateTimeField(auto_now=True)
           active = models.BooleanField(default=True)
    
           class Meta:
               ordering = ('created', )
    
           def __str__(self):
               return 'Comment by {} on {}'.format(self.name, self.post)
    • 这个评论模型,包含了一个外键用于关联单独的 post 对应评论(可以多个评论), related_name 属性定义了这个关联的名字,一个评论的话可以用 comment.post 来表示,一个 post 中所有评论可以用 post.comment.all() 表示,这是一个 many-to-one 关联关系
    • created 字段用于按照时间前后顺序来分类保存评论
    • active 字段用于手动去除不想要的评论
    • Comment 模型不会同步到数据库中,所以需要创建一个新的数据迁移
       python manage.py makemigrations blog
       pythom manage.py migrate
    • 为了管理评论,需要在管理页面增加一个类 CommentAdmin
    • 编辑 admin.py 增加
       from .models import Post, Comment
       
       class CommentAdmin(admin.ModelAdmin):
           list_display = ('name', 'email', 'post', 'created', 'active')
     	  list_filter = ('active', 'created', 'updated')
     	  search_fields = ('name', 'email', 'body')
     	  
       admin.site.register(Comment, CommentAdmin)
    • Creating forms from models
      • Django 有两种类来创建表单 FormModelForm
      • 评论这里需要动态的创建表单,所以需要用 ModelForm 这个类
      • 编辑 forms.py 增加
        from .models import Comment
        
        class CommentForm(forms.ModelForm):
            class Meat:
      	      model = Comment
      		  fields = ('name', 'email', 'body')
    • Handling ModelForms in views
      • post detail 视图来实例化表单,修改 post_detail
        from .models import Post, Comment
        from .forms import EmailPostForm, CommentForm
        
        def post_detail(request, year, month, day, post):
            post = get_object_or_404(Post, slug=post, status='published', publish__year=year,
      	                           publish__month=month, publish__day=day)
      	  # 这个post的活动评论
      	  comments = post.comments.filter(active=True)
      	  
      	  if request.method == 'POST':
      	      # 评论被提交
      		  comment_form = CommentForm(data=request.POST)
      		  if comment_form.is_valid():
      		      # 创建评论对象但是不保存到数据库
      			  new_comment = comment_form.save(commit=False)
      			  # 指定当前的post为评论
      			  new_comment.post = post
      			  # 保存评论到数据库
      			  new_comment.save()
      	  elsecomment_form = CommentForm()
      	  return render(request, 'blog/post/detail.html', {'post': post, 
      		            'comments': comments, 'comment_form': comment_form})
    • Adding comments to the post deatail template
      • post detail 模板中增加评论的功能
        • 显示评论的数量
        • 显示评论
        • 显示一个新的表单用于提交评论
      • 首先增加评论数量的显示,编辑 blog/detail.html 模板,在 content 中增加
        {% with comments.count as total_comments %}
            <p>
      	      {{ total_comments }} comment{{ total_comments|pluralize }}
      	  </p>
        {% endwith %}
      • 在这里使用了 ORM 来执行查询集 comments.count(),注意在 Django 模板中,不用圆括号来调用方法,所以上面只写了 comments.count
      • {% with %} 这个标签允许我们分配一个值给指定的新变量直到 {% endwith %}标签
      • total_comments|pluralize 这里根据 total_comments 评论的数量,用了 pluralize 来显示是否需要在 comment 后面加上 s 来代表复数
      • 接下来显示评论列表,紧跟上面继续添加
        {% for comment in comments %}
            <div class="comment">
      	      <p class="info">
      		      Comment {{ forloop.counter }} by {{ comment.name }}
      			  {{ comment.created }}
      		  </p>
      		  {{ comment.body|linebreaks }}
      	  </div>
        {% empty %}
            <p>There are no comments yet.</p>
        {% endfor %}
      • 上面用 {% for %} 标签来循环,如果评论为空,那么返回默认的输出,通过 forloop.counter 来枚举这些评论
      • 最后如果评论被成功提交的话,需要显示成功的返回,在后面继续添加
        {% if new_comment %}
            <p>Your comment has been added.</p>
        {% else %}
            <p>Add a new comment</p>
      	  <form action="." method="post">
      	      {{ comment_form.as_p }}
      		  {% csrf_token %}
      		  <p><input type="submit" value="Add comment"></p>
      	  </form>
        {% endif %}
      • 上面渲染了表单,其中也包含了 POST 请求的 CSRF token
  • Django 忘记了用户密码解决方法

    • Django 保存的密码是经过加密的,所以用 SQL 重写的话比较麻烦,所以可以使用以下三种方法:
      • createsuperuser 来创建一个新的帐号
        python manage.py createsuperuser
      • 调用 shell ,用 Userset_password 方法来重置密码
        python manage.py shell
        from django.contrib.auth.models import User
        
        user = User.objects.get(username='admin')
        user.set_password('new_password')
        user.save()
      • Django 1.2 后新版,可以直接调用 shell 修改
        python manage.py changepassword username
@PyxYuYu PyxYuYu added the Django label Nov 17, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant