python - 用户在 Django 中的表单中上传后,图像未加载到 HTML 中
问题描述
我正在构建一个用户可以上传图像的表单。单击提交按钮后,他/她将被重定向到预览页面以查看所有提交的图像。但是该图像未显示在评论页面中,而该图像在管理站点中可见。点击inspect后,显示图片来源未知。这是我的代码:
模型.py
from django.db import models
from phonenumber_field.modelfields import PhoneNumberField
# Create your models here.
class Register(models.Model):
name = models.CharField(max_length=50)
idCard = models.ImageField(upload_to='idCard', null=True)
def __str__(self):
return self.name
表格.py
from django import forms
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import *
class RegisterForm(ModelForm):
name = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Your full name...'}))
class Meta:
model = Register
fields = '__all__'
视图.py
from django.shortcuts import render, redirect
from .models import *
from .forms import *
# Create your views here.
def index(request):
form = RegisterForm()
if request.method == 'POST':
form = RegisterForm(request.POST, request.FILES)
if form.is_valid():
instance = form.save()
return redirect('preview', pk=instance.id)
context = {'form':form}
return render(request, 'event/index.html', context)
def preview(request, pk):
reg = Register.objects.get(id=pk)
prev = RegisterForm(instance=reg)
if request.method == 'POST':
form = RegisterForm(request.POST, instance=reg)
if form.is_valid():
form.save()
return redirect('/')
context = {'reg':reg, 'prev':prev}
return render(request, 'event/preview.html', context)
网址.py
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
path('', views.index, name='home'),
path('preview/<str:pk>', views.preview, name="preview"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
设置.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
预览.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Preview</title>
</head>
<body>
Hey {{prev.name}},
your idCard photo is <img src="{{prev.idCard.url}}" alt="idcard">
</body>
</html>
索引.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event Registration</title>
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<script src="{% static 'js/script.js' %}"></script>
</head>
<body>
<div class="mobile-screen">
<div class="header">
</div>
<div class="logo"></div>
<form id="login-form" method="POST" action="" enctype="multipart/form-data">
{% csrf_token %}
{{form.name}}
<legend style="color: aliceblue;">Upload ID card: </legend>{{form.idCard}}
<input class="btn btn-sm btn-primary" type="submit" value="Register" name="Register">
</form>
</div>
</body>
</html>
帮我加载预览页面中的图片
解决方案
好像你还没有创建User
类。您需要related_name
通过引用Register
模型User
models.py
:
from django.db import models
from phonenumber_field.modelfields import PhoneNumberField
from django.contrib.auth.models import User
# Create your models here.
class Register(models.Model):
username = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile")
name = models.CharField(max_length=50)
idCard = models.ImageField(upload_to='idCard', null=True)
def __str__(self):
return self.name
forms.py
:
from django import forms
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import *
class UserForm(ModelForm):
class Meta():
model = User
fields = ('username')
class RegisterForm(ModelForm):
name = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Your full name...'}))
class Meta:
model = Register
fields = '__all__'
preview.html
:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Preview</title>
</head>
<body>
Hey {{prev.name}},
your idCard photo is <img src="{{prev.profile.idCard.url}}" alt="idcard">
</body>
</html>
推荐阅读
- java - 多个列表的最佳组合,每个列表只选择一个值
- file - 打开带有升序数字的文件
- javascript - 不使用 React 或 Angular 从 TypeScript 中的 HTML 获取用户输入
- sql-server - 如何获取 Perl/SQL Server 的列名和结果集
- javascript - 访问同一父级中另一个元素内的 div 元素
- c#-3.0 - 如何从具有多个部分的word文档中获取使用openxml的总页数?
- r - 在包代码中从其他包的命名空间中查找对象
- blazor - 在 Blazor 中使用 _host.cshtml 的预渲染时,如何停止渲染两次(对于非数据检索组件)?
- r - 如何在 table1 包中显示具有不相等组大小的 ANOVA 的 p 值?
- c++ - 编写自己的可执行格式GCC?