【问题标题】:Images not loading in HTMLs after user uploads in forms in Django用户在 Django 中的表单中上传后图像未加载到 HTML 中
【发布时间】:2020-05-25 17:48:41
【问题描述】:

我正在构建一个用户可以上传图片的表单。单击提交按钮后,他/她将被重定向到预览页面以查看所有提交的图像。但是该图像未显示在评论页面中,而该图像在管理站点中可见。点击inspect后,显示图片来源未知。这是我的代码:

models.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

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 RegisterForm(ModelForm):
    name = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Your full name...'}))

    class Meta:
        model = Register
        fields = '__all__'

views.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)

urls.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)

settings.py

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

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.idCard.url}}" alt="idcard">

</body>
</html>

index.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>

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

【问题讨论】:

  • 尝试将 models.py 中的 upload_to 属性更改为:idCard = models.ImageField(upload_to='img', null=True)
  • 没用。

标签: python html django django-models django-forms


【解决方案1】:

您似乎还没有创建User 类。您需要related_name 通过User 引用Register 模型

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>

【讨论】:

    猜你喜欢
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 2019-03-24
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    相关资源
    最近更新 更多