如何在Django中将图像url字段添加到html表单

2024-06-01 02:51:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个捐赠web应用程序。用户可以填写表单并将捐赠提交到数据库中,我想知道如何让用户提交图像的url并将其保存在数据库中,然后在另一个页面上呈现。例如(完整表单如下),如果用户填写表单并提交类似https://images.unsplash.com/photo-1481349518771-20055b2a7b24?ixid=MnwxMjA3fDB8MHxzZWFyY2h8M3x8cmFuZG9tfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&w=1000&q=80的url,我如何将其保存到数据库并在另一个页面上呈现?感谢所有的帮助。我的密码在下面

Html格式:

<label class="label-input100" for="image">Image</label>
                <div class="wrap-input100">
                    <input id="phone" class="input100" type="text" name="image" placeholder="Please enter the url of your image" required>
                    <span class="focus-input100"></span>
                </div>

视图:

if request.method == "POST":
        image= request.POST['image']
        return redirect('thankyou.html')

型号:

image = models.ImageField(null = True, blank = True)

我总是在我的电脑上,所以如果你有任何问题,请随时提问


Tags: 用户imagedivweb数据库trueurl表单
2条回答
def saveImage(request):
    if request.method == "POST":
        image = request.FILES.get('image')
        new_image = <Image_Model>.objects.create(
            image = image
        )

        return redirect('/somewhere/')
    return render(request, 'new_image.html',)
  1. 在项目的应用程序级别创建文件夹…将其命名为“静态”
  2. 在“静态”文件夹中,创建另一个文件夹,将其命名为“图像”
  3. 打开SETTINGS.PY文件并粘贴下面的代码

设置.PY

MEDIA_URL = '/images/'
MEDIA_ROOT = BASE_DIR / 'static/images'
  1. 在与SETTINGS.PY相同的文件夹中打开url.PY文件,并粘贴下面的代码

    from django.conf import settings

    from django.conf.urls.static import static

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

HTML表单

<form method="POST" enctype="multipart/form-data" action="{%destination url%}">

<input name="image" type="file">

</form>

相关问题 更多 >