1 基于forms组件设计注册页面
register.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="{% static 'blog/bootstrap/css/bootstrap.css' %}">
<style>
#avatar_img {
margin-left: 20px;
}
#avatar {
display: none
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 col-lg-offset-3">
<h3>注册页面</h3>
<form>
{% csrf_token %}
{% for filed in form %}
<div class="form-group">
<label for="{{ filed.auto_id }}">{{ filed.label }}</label>
{{ filed }}
</div>
{% endfor %}
<div class="form-group">
<label for="avatar">
头像
<img id="avatar_img" src="{% static 'blog/img/default.png' %}" width="50">
</label>
<input type="file" id="avatar">
</div>
<input type="button" class="btn btn-default login_btn pull-right" value="登录">
</form>
</div>
</div>
</div>
</body>
</html>
views.py
from django import forms
class UserForm(forms.Form):
user = forms.CharField(
max_length=32,
label='用户名',
widget=forms.widgets.TextInput(attrs={'class': 'form-control'})
)
pwd = forms.CharField(
max_length=32,
label='密码',
widget=forms.widgets.PasswordInput(attrs={'class': 'form-control'})
)
re_pwd = forms.CharField(
max_length=32,
label='确认密码',
widget=forms.widgets.PasswordInput(attrs={'class': 'form-control'})
)
email = forms.EmailField(
label='邮箱',
widget=forms.widgets.EmailInput(attrs={'class': 'form-control'})
)
def register(request):
form = UserForm()
return render(request, 'register.html', {'form': form})
2 实现点击预览头像
实现思路:
1.获取用户选中文件的对象
2.获取文件对象的路径
3.修改img的src路径,src=文件对象的路径
基于以上register.html,编写javascript代码
<script src="{% static 'blog/js/jquery-3.6.0.min.js' %}"></script>
<script>
// change状态改变后生效
$("#avatar").change(function () {
// 1.获取用户选中的文件对象
var file_obj = $(this)[0].files[0];
// 2.获取文件对象的路径
var reader = new FileReader();
reader.readAsDataURL(file_obj); // 异步的
reader.onload = function () {
// 3.修改img的src路径,src=文件对象的路径
$('#avatar_img').attr('src', reader.result)
} // onl oad同步,会等待异步代码执行完,在执行
})
</script>
标签:src,预览,form,label,forms,ajax,attrs,class
From: https://www.cnblogs.com/it-lkp/p/16580875.html