以下学习 朔宁夫 开发课(Python)。
文件上传&表单类
一 Django文件上传
表单上传。
前端:表单设置
enctype = "multipart/form-data"
后端:获取上传文件对象
upload_dile = request.FILES.get("文件域名称")
后端:分块写入服务器
for chunk in upload_file.chunks():
目标文件.write(chunk)
演示:
python manage.py startapp upload_app
setting // installed_apps
total urls // path('upload_app/', include('upload_app.urls', namespace='upload')),
sub urls //
app_name = "upload" urlpatterns = [ path("upload/", upload_view, name="up"), ]
template //
<form action="{% url 'upload:up' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} Upload file: <br> <input type="file" name="a_file"><br> <input type="submit" value="UPLOAD"> </form>
views //
def upload_view(request): #BASE_DIR = 'D:/webDevelopment/exercises/djangoProject' if request.method == "GET": return render(request, "upload.html") if request.method == "POST": upload_obj = request.FILES.get("a_file") file_name = str(int(time.time()) * 1000) + upload_obj.name #path = os.path.join(BASE_DIR, "/upload_files", upload_obj.name) # , file_name path = os.path.join('D:/webDevelopment/exercises/djangoProject/upload_files', file_name) print(path) with open(path, 'wb') as f: for chunk in upload_obj.chunks(): f.write(chunk) print('flag_up_w') data = { "msg": "Data Uploaded." } return JsonResponse(data)
# 上传同名文件会覆盖。加入时间戳可。
admin 上传:
class Anime(models.Model): name = models.CharField(max_length=32, verbose_name='figure name') impress = models.FloatField(verbose_name="index") # img = models.FilePathField() img = models.ImageField(verbose_name="img") class Meta: verbose_name = "figure" verbose_name_plural = verbose_name def __str__(self): return self.name
#注册
models = [ Anime, ] admin.site.register(models) setting // MEDIA_ROOT = os.path.join(BASE_DIR, "upload_files") MEDIA_URL = '/media/'
二 表单类
简化编码。使用步骤:继承→自定义类属性→调用→模板渲染。
app下form.py //
from django import forms
class RegisterForm(forms.Form):
reg_name = forms.CharField(max_length=10, label="user_name")
reg_pwd = forms.CharField(max_length=20, label="pwd", widget=forms.PasswordInput()) # 组件
reg_home = forms.ChoiceField(label="area", choices=((1, 'alive'), (2, 'dead'), (3, 'walk_dead')))
gender = forms.ChoiceField(label='gender', choices=((1, 'Female'), (2, 'Male')), widget=forms.RadioSelect())
views //
def form_view(request):
if request.method == "GET":
form = RegisterForm()
return render(request, "form.html", locals())
if request.method == "POST":
form = RegisterForm(request.POST)
if form.is_valid():
name = form.cleaned_data["reg_name"]
home = form.cleaned_data["reg_home"]
gender = form.cleaned_data["gender"]
data = {
"name": name,
"home": home,
"gender": gender,
}
return JsonResponse(data)
else:
return JsonResponse({"msg": "Fail"})
template //
<form action="{% url 'upload:reg' %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="register">
</form>