怎么注册、登陆用户

怎么扩展用户信息

这篇讲解怎么更新用户信息


1、新建forms文件:accounts_forms.py

form包含两个类:一个是django自带的user信息表UserForm,另一个是扩展的用户信息的 UserProfileInfoForm

from django import forms
from django.contrib.auth.models import User
from .models import UserProfileInfo

class UserForm(forms.ModelForm):

    class Meta():
        model = User
        fields = ('password','email')

class UserProfileInfoForm(forms.ModelForm):
    class Meta():
        model = UserProfileInfo
        fields = ('profile_phone','profile_pic','profile_site','profile_descption')

2、在dashboard.html添加一个Modal,用来更新个人信息

<section class="support-author">
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#updateInfoModal"><i class="fa fa-cny" aria-hidden="true"></i> 更新个人信息</button>
</section>

目标是updateInfoModal,点击按钮后弹出更新框

 <!-- Inquiry Modal -->
  <div class="modal fade" id="updateInfoModal" role="dialog">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="inquiryModalLabel">修改个人信息</h5>
          <button type="button" class="close" data-dismiss="modal">
            <span>×</span>
          </button>
        </div>
        <div class="modal-body">

 <!-- 更新个人信息的输入框 -->
<form method="post" novalidate>
  {% csrf_token %}

{% if user.is_authenticated %}
 <div class="form-group">
  <label for="logonName">登录名:</label>
   <input type="text" class="form-control " readonly name="inputUsername" value='{{user.username}}'>

</div>
{% endif %}

  {% for hidden_field in form.hidden_fields %}
    {{ hidden_field }}
  {% endfor %}
 <!-- user_form是自定义的form类,包含密码和email -->
  {% for field in user_form.visible_fields %}
    <div class="form-group">
      {{ field.label_tag }}
      {% render_field field class="form-control" %}
      {% if field.help_text %}
        <small class="form-text text-muted">{{ field.help_text }}</small>
      {% endif %}
    </div>
  {% endfor %}

 <!-- 电话号码、照片等等不用form传递,对比一下哪种更方便 -->
  <div class="form-group">
    <label for="">电话号码</label>
    <input type="text" class="form-control" id="inputPhoneNumber" name="inputPhoneNumber" value={{phone_number}}>
  </div>

<div class="form-group">
<label for="" class="">照片</label>
 <div class="custom-file ">
    <input type="file" class="custom-file-input" id="inputProfilePic" name="inputProfilePic" >
    <label class="custom-file-label"   >{{selfie}}</label>
    <div class="invalid-feedback"></div>
  </div>
</div>


        
  <div class="form-group">
    <label for="">网址</label>
    <input type="url" class="form-control" id="inputPersonalWebsite" name="inputPersonalWebsite" value="{{website}}">
  </div>

  <div class="form-group">
    <label for="">个人介绍</label>
    <input type="textarea" class="form-control" id="inputDesciption" name="inputDesciption" value="{{description}}">
  </div>

  <button type="submit" value="Send" class="btn btn-block btn-secondary">提交</button>
  </form>


        </div>
      </div>
    </div>
  </div>

3、配置views.py,写dashboard函数,功能就是提交个人信息后更新用户信息。

导入accounts_forms和自定义的个人信息UserProfileInfo

from .account_forms import UserForm,UserProfileInfoForm
from  accounts.models import UserProfileInfo

dashboard函数:

当用户提交POST的时候,更新用户信息 updateInfo(request,my_forms)

没有提交POST的时候,展示用户个人信息。

没有提交信息的时候POST是空的。

注册john后,进行登陆,登陆后USER是john对象,如果没有登陆 USER 是 anonymous



def dashboard(request):
    my_forms = {"user_form":0,"profile_form":0}
    #if POST  then update info
    if request.method =='POST':
      isUpdate = updateInfo(request,my_forms)
      user_form = my_forms["user_form"]
      profile_form = my_forms["profile_form"]
      if isUpdate:
        return redirect('login')
      else:
        return redirect('dashboard')

    #not POST, then show personal info    
    else:

      if request.user.is_authenticated:
        id = request.user.id
        #通过django的user找到id,通过id获取附件用户信息的对象profile_form
        user_basic = User.objects.get(id=id)
        user_profile = UserProfileInfo.objects.get(user_id=id)
        #给user_form,profile_form赋值,传回前端,就可以在html上显示出来
        #initial={'password':''} 的意思是初始化为空,当用户更新信息时不显示数据库中存的用户密码
        user_form = UserForm(initial={'password':''},instance=user_basic)
        profile_form = UserProfileInfoForm(instance=user_profile)
        

        context = {"user_form":user_form,
              "profile_form":profile_form,
              "website":user_profile.profile_site,
              "phone_number":user_profile.profile_phone,
              "selfie":user_profile.profile_pic,
              "description":user_profile.profile_descption
              }

        return render(request,'accounts/dashboard.html',context)
      else:
        return redirect('login')



更新用户信息:

updateInfo函数



def updateInfo(request,my_form):

    if request.method == 'POST':
        name = request.POST.get('inputUsername')
        
        # 通过名字找到user_id,username是用户表的表头
        #user的id就是扩展个人信息的user_id
        user_basic = User.objects.get(username=name)
        user_id = getattr(user_basic, 'id')

        user_pofile = UserProfileInfo.objects.get(user_id=user_id)
        # Get info from "both" forms
        # It appears as one form to the user on the .html page
        #print(request.FILES['inputProfilePic'])

        #有instance的时候更新信息,没有instance的时候,新增信息
        user_form = UserForm(data=request.POST,instance=user_basic)
        profile_form = UserProfileInfoForm(data=request.POST,instance=user_pofile)

        # Check to see both forms are valid
        if user_form.is_valid() and profile_form.is_valid():

            # Save User Form to Database
            user = user_form.save()
            # Hash the password
            user.set_password(user.password)
            # Update with Hashed password
            user.save()
            # Now we deal with the extra info!
            # Can't commit yet because we still need to manipulate
            pf = profile_form.save(commit=False)
            # Set One to One relationship between
            # UserForm and UserProfileInfoForm
            pf.user = user
            # Check if they provided a profile picture
            if 'profile_pic' in request.FILES:
                print('found it')
                # If yes, then grab it from the POST form reply
                pf.profile_pic = request.FILES['inputProfilePic']

            pf.profile_phone = request.POST.get('inputPhoneNumber')
            pf.profile_site = request.POST.get('inputPersonalWebsite')
            pf.profile_descption= request.POST.get('inputDesciption')
            
            # Now save model
            pf.save()



        else:
            # One of the forms was invalid if this else gets called.
            print(user_form.errors,profile_form.errors)
            messages.error(request, user_form.errors,profile_form.errors)            
            return False

    else:
        # Was not an HTTP post so we just render the forms as the info we get from db.
        user_form = UserForm(instance = user_basic)
        profile_form = UserProfileInfoForm(instance = user_pofile)

    # give back user_form and profile_form
    my_form['user_form'] = user_form
    my_form['profile_form'] = profile_form

获取一个用户的所有信息:

 users = User.objects.all().select_related('UserProfileInfo') 


如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!



0 条评论

发表评论

电子邮件地址不会被公开。 必填项已用*标注