跟大妈学Django Part - 10 (Django入门续集10)
今天想先做个profile,这样用户就能拥有自己的小盒子。
做之前,先把登录Django Admin 把之前设定的user给删了,不然后面会出现ERROR。
总之,之前已经建立过好几次App了,今天要飞快的闪过。
通道内建APP, 上次用错了指令
如果用django-admin建app的话,会在下面一级建档,很是麻烦。
最好是用以下指令建新的app
python3 manage.py startapp profiles
view里先简单的render出页面,现在的设定是主要先确保url能用
/workspace/how-do-you-do/profiles/views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from .models import UserProfile
# Create your views here.
@login_required
def profile(request):
""" Display the user's profile. """
template = 'profiles/profile.html'
context = {}
return render(request, template, context)
profile的model只需要显示用户,名字,邮件,如果没有用户资料的话,就生成一个
/workspace/how-do-you-do/profiles/models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
# Create your models here.
class UserProfile(models.Model):
"""a user profile to main personal feelings"""
user = models.OneToOneField(User, on_delete=models.CASCADE)
full_name = models.CharField(max_length=50, null=True, blank=False)
email = models.EmailField(max_length=254, null=True, blank=False)
def __str__(self):
return self.user.username
@receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
"""
Create or update the user profile
"""
if created:
UserProfile.objects.create(user=instance)
# Existing users: just save the profile
instance.userprofile.save()
# /workspace/how-do-you-do/profiles/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.profile, name='profile'),
]
# /workspace/how-do-you-do/hdyd/urls.py
path('profile/', include('profiles.urls')),
前端模板
/workspace/how-do-you-do/profiles/templates/profiles/profile.html
{% extends "base.html" %}
{% load static %}
{% block content %}
<!--Main Navigation-->
<header>
{% include 'mood/nav.html' %}
<!-- Background image -->
<div id="intro" class="p-5 text-center bg-image shadow-1-strong ">
<div class="mask bg-color ">
<div class="d-flex justify-content-center align-items-center h-100">
<div class="px-4 bg-light bg-gradient text-black-50">
<div class="my-4"></div>
<h4 class="border border-light my-4 p-4">
{{ user }} Profile
</h4>
<button
type="button"
class="btn btn-outline-muted btn-lg m-2 text-black-50"
href="#"
role="button"
>
Stuffing
</button>
<div class="my-4"></div>
</div>
</div>
</div>
</div>
<!-- Background image -->
</header>
<hr class="m-0" />
{% include 'mood/footer.html' %}
{% endblock %}
链接成功