首页 > 代码库 > 新闻网站项目笔记

新闻网站项目笔记

总结了一些知识点

1.api里面的对象有的要显示两层以上的嵌套怎么办?

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = (id,profile,username)
        depth = 1

class CommentSerializer(serializers.ModelSerializer):
    belong_user = UserSerializer()
    class Meta:
        model = Comment
        fields = __all__
        depth = 1

比如要取到comment.belong_user.profile.avatar。这里在序列化器里面做了一个嵌套 belong_user = UserSerializer()

2.如何做分页?

    pagerobot = Paginator(article_list,5)                         #创建分页器,每页限定五篇文章
    page_num = request.GET.get("page")                            #取到当前页数
    try:
        article_list = pagerobot.page(page_num)                   #一般情况下返回当前页码下的文章
    except EmptyPage:
        article_list = pagerobot.page(pagerobot.num_pages)        #如果不存在该业,返回最后一页
    except PageNotAnInteger:
        article_list = pagerobot.page(1)          

3.如何自定义表单验证?

def words_validator(comment):
    if len(comment)<5:
        raise ValidationError("您输入的评论字数太短,请重新输入至少5个字符")

class CommentForm(forms.Form):
    comment = forms.CharField(widget=forms.Textarea(),validators=[words_validator])

或者重写clean方法

class RegisterForm(forms.Form):
    username = forms.CharField(widget=forms.TextInput(attrs={placeholder:用户名}))
    email = forms.CharField(widget=forms.TextInput(attrs={placeholder:邮箱}))
    password = forms.CharField(widget=forms.PasswordInput(attrs={placeholder:密码}))
    password_confirm = forms.CharField(widget=forms.PasswordInput(attrs={placeholder:确认密码}))

    def clean(self):
        cleaned_data = super(RegisterForm,self).clean()
        username = cleaned_data.get("username")
        email = cleaned_data.get("email")
        password = cleaned_data.get("password")
        password_confirm = cleaned_data.get("password_confirm")

        if User.objects.filter(username=username):
           raise forms.ValidationError("用户已存在")
        if User.objects.filter(email=email):
           raise forms.ValidationError("该邮箱已被注册")

        try:
           validate_email(email)
        except ValidationError:
           raise forms.ValidationError("不正确的邮箱格式")

        if len(password) < 6:
           raise forms.ValidationError("密码长度至少6位")

        if password_confirm != password:
           raise forms.ValidationError("两次输入的密码不一致")

4.如何对于留言板功能用cookie验证表单

首先在用户的cookies里存进token:

def detail(request,article_id):
    if not isinstance(request.user, User):
        return render(request, detail.html)
    token, created = Token.objects.get_or_create(user=request.user)    #创建登录用户的token并存到cookie中
    response = render(request, detail.html)
    response.set_cookie(key=token,value=http://www.mamicode.com/token.key)
    return response

在提交留言的方法中记得在请求头加入token:

sendcomment:function(){
              var self = this;
              var id = location.href.split("/")[4];
              var datenow = new Date();
              reqwest({
                url:/api/detail/+ id +/,
                type:json,
                method:post,
                headers:Cookies.get(token)? {Authorization: Token  + Cookies.get(token)}:{}, #这里这里!
                data:{
                  article_id:id,
                  created:datenow.toISOString(),
                  words:self.words
                },
                success:function(resp){
                  location.reload();
                }
              })
            }

记得在urls.py中配置token的api地址:

from rest_framework.authtoken import views

url(r^api/token-auth/$, views.obtain_auth_token)

 

新闻网站项目笔记