首页 > 解决方案 > 用户在 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>

帮我加载预览页面中的图片

标签: pythonhtmldjangodjango-modelsdjango-forms

解决方案


好像你还没有创建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>

推荐阅读