Django的主要开发流程(以扩充用户模型为例)

元气小坏坏 提交于 2020-01-31 00:39:10

需求描述

完成个人中心页面的用户信息更新
如图
在这里插入图片描述

开发流程(以users为例):

  1. startapp创建应用users
  2. 写users下的models
  3. 在settings下注册app
  4. makemigrations迁移数据库
  5. 设计路由
  6. 视图
  7. 渲染前端模板

1. startapp创建应用

cookiecutter创建项目时已经帮我们创建好了users
如果要创建自己的app,则使用

python manage.py startapp app_name

2. 写users下的models.py

class User(AbstractUser):
    # blank=True表示前端提交时可以为空, null=True表示数据库里该字段可以为空
    nickname = models.CharField(verbose_name='用户昵称', blank=True, null=True, max_length=255, default='')
    job = models.CharField(verbose_name='用户职业', blank=True, null=True, max_length=50, default='未知')
    introduction = models.TextField(verbose_name='简介', blank=True, null=True, default='该用户很懒,什么都没留下')
    avtar = models.ImageField(verbose_name='头像', upload_to='users/avatars/', blank=True, null=True, default='')
    address = models.CharField(verbose_name='住址', blank=True, null=True, max_length=50, default='')
    birthday = models.DateField(verbose_name='生日', blank=True, null=True, default=timezone.now)
    personal_url = models.URLField(max_length=255, null=True, blank=True, verbose_name='个人链接', default='')
    weibo = models.URLField(max_length=255, null=True, blank=True, verbose_name='微博链接', default='')
    zhihu = models.URLField(max_length=255, null=True, blank=True, verbose_name='知乎链接', default='')
    github = models.URLField(max_length=255, null=True, blank=True, verbose_name='GitHub链接', default='')
    linkedin = models.URLField(max_length=255, null=True, blank=True, verbose_name='LinkedIn链接', default='')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        verbose_name = '用户'
        verbose_name_plural = verbose_name
        
    def __str__(self):
        return self.username
        
    # 前端界面显示用户信息 有昵称则返回昵称,否则返回用户名
    def get_profile_name(self):
        if self.nickname:
            return self.nickname
        return self.username

    def get_absolute_url(self):
        return reverse("users:detail", kwargs={"username": self.username})

3. 在settings下注册app

创建项目时已经有了

LOCAL_APPS = [
    "mydjango.users.apps.UsersConfig",
    # Your stuff: custom apps go here
]
# https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS

4. makemigrations迁移数据库

python manage.py makemigrations
python manage.py migrate

5. 设计路由

users下的urls.py

app_name = "users"
urlpatterns = [
    path("~redirect/", view=user_redirect_view, name="redirect"),
    path("~update/", view=user_update_view, name="update"),
    path("<str:username>/", view=user_detail_view, name="detail"),
]

6. 视图

# 更新视图
class UserUpdateView(LoginRequiredMixin, UpdateView):

    model = User  # 模型
    fields = ["nickname", "job", "introduction", "avatar", "address", "birthday",
              "personal_url", "weibo", "zhihu", "github", "linkedin"]  # 可更新的字段
    template_name = 'users/user_form.html'

    def get_success_url(self):  # 更新成功后跳转
        return reverse("users:detail", kwargs={"username": self.request.user.username})

    def get_object(self):  # 获取当前登录的对象
        return User.objects.get(username=self.request.user.username)

    def form_valid(self, form):
        messages.add_message(
            self.request, messages.INFO, _("Infos successfully updated")
        )
        return super().form_valid(form)


user_update_view = UserUpdateView.as_view()

7. 渲染前端模板

{% extends "base.html" %}
{% load crispy_forms_tags %}

{% block title %}{{ user.username }}{% endblock %}

{% block content %}
  <h1>{{ user.username }}</h1>
  {#  增加enctype="multipart/form-data"接收多媒体文件以便上传头像 #}
  <form class="form-horizontal" method="post" enctype="multipart/form-data" action="{% url 'users:update' %}">
    {% csrf_token %}
    {{ form|crispy }}
    <div class="control-group">
      <div class="controls">
        <button type="submit" class="btn btn-primary">更新个人信息</button>
      </div>
    </div>
  </form>
{% endblock %}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!