我使用两个类来抽象系统中的用户:Django 默认 User 和我的类 Documentador。 我在界面方面将它们视为一个,并且为了创建 User 和 Documentador 对,我使用传递给模板的表单并处理视图上的数据来创建和保存两个模型。 我的问题是:两个模型都保存得没有任何错误,但 Documentador 类中的图像却没有。
我尝试在 Django 管理中创建一个带有图像的 Documentador 模型,并且它有效。 我也这样测试了这些字段:
if not form.cleaned_data['foto']: return HttpResponseRedirect('/controle')
我被重定向到那条路径。
我想是某种形式或视图的东西,但找不到什么。
表格:
class DocumentadorForm(forms.Form):
foto = forms.ImageField(required=False)
username = forms.CharField(label="Nome de usuário", max_length="20")
first_name = forms.CharField(label="Primeiro nome", max_length="30")
last_name = forms.CharField(label="Sobrenome", max_length="30")
email = forms.EmailField()
matricula = forms.IntegerField()
password = forms.CharField(widget=forms.PasswordInput)
我的视图:
class UsuarioDocumentadorCreate(View):
def get(self, request, *args, **kwargs):
return render(request, 'mmrn/controle/crud_documentador/c_documentador.html', {'form':DocumentadorForm()} )
def post(self, request, *args, **kwargs):
form = DocumentadorForm(request.POST, request.FILES)
if form.is_valid():
f_foto = form.cleaned_data['foto']
f_username = form.cleaned_data['username']
f_first_name = form.cleaned_data['first_name']
f_last_name = form.cleaned_data['last_name']
f_email = form.cleaned_data['email']
f_matricula = form.cleaned_data['matricula']
f_password = form.cleaned_data['password']
new_user = User(username=f_username, first_name=f_first_name, last_name=f_last_name, email=f_email)
doc = Documentador(user=new_user, foto=form.cleaned_data['foto'], matricula=f_matricula)
new_user.save()
doc.save()
return HttpResponseRedirect('/controle/documentadores')
else: return render(request, 'mmrn/controle/crud_documentador/c_documentador.html',{'form':form})
纪录片模特:
class Documentador(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
foto = models.ImageField(blank=True, upload_to="documentadoresfotos/")
matricula = models.IntegerField(blank=True)
def __str__(self):
您发布的代码对于保存用户和 Documentador 实例以及图像似乎是合理的。由于 Documentador 模型已成功保存在管理员中,但不是通过您视图中的表单保存,因此表单处理文件上传的方式可能存在问题。
您可以检查以下几项:
HTML 表单属性:确保您的 HTML 表单标签包含 enctype="multipart/form-data" 属性。对于具有文件上传字段的表单,此属性是必需的。
<form method="post" enctype="multipart/form-data">
<!-- Your form fields go here -->
</form>
检查表单验证错误:在视图的post方法中,验证表单后,您可以将表单的错误打印到控制台,以查看是否存在与文件上传相关的问题。
if form.is_valid():
# Your existing code here
else:
print(form.errors)
return render(request, 'mmrn/controle/crud_documentador/c_documentador.html', {'form': form})
这将为您提供有关任何表单验证错误的更多信息。
检查文件是否正在发送:使用 request.FILES 检查文件是否正在发送 正在与请求一起发送。添加打印语句来检查是否 文件数据存在。
print(request.FILES)
更新用于文件上传的 HTML 表单:确保 HTML 中的表单 文件具有正确的 enctype 属性,并且 foto 输入字段是 文件类型。
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
<button type="submit">Submit</button>
</form>
检查文件权限:确保指定的目录 upload_to="documentadoresfotos/" 具有必要的写入权限 用于 Django 服务器。
通过完成这些步骤,您应该能够识别文件上传的问题。如果问题仍然存在,您可能需要考虑使用 Django 的 ModelForm 作为 Documentador 模型,这可以简化具有文件字段的模型实例的表单处理。