{% if form.errors %} <ul> {% for field in form %} {% for error in field.errors %} <li>{{ field.label }}: {{ error }}</li> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <li>{{ error }}</li> {% endfor %} </ul> {% endif %}
classUserProfileForm(forms.ModelForm): classMeta: model = UserProfile fields = ['username', 'email', 'profile_picture']
更新视图
接下来,更新视图(views.py)以处理文件上传及其校验:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
from django.shortcuts import render, redirect from .forms import UserProfileForm
defupdate_profile(request): if request.method == 'POST': form = UserProfileForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('profile_success')
{% if form.errors %} <ul> {% for field in form %} {% for error in field.errors %} <li>{{ field.label }}: {{ error }}</li> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <li>{{ error }}</li> {% endfor %} </ul> {% endif %}
# myproject/urls.py from django.contrib import admin from django.urls import path from uploads.views import upload_file from django.conf import settings from django.conf.urls.static import static