模板中的Django表单

gupuwyp2  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(133)

我试图建立一个形式,使用户能够上传图片从网站到媒体\图像文件夹。
我试过这个,但它不起作用

models.py

from django.db import models

# Create your models here.

class imgUpscalling(models.Model):
    Image = models.ImageField(upload_to='images/')

forms.py

from django import forms
from .models import imgUpscalling

class ImageForm(forms.ModelForm):
    class Meta: 
        model = imgUpscalling
        fields = ('Image',)

views.py

def img_upscaler(request):
    context = {'from': ImageForm()}
    return render(request, "upsc_main.html",context)

template.html

<h1>Image Upscaler & Enhanced Resolution</h1>
    <h2>Select the Image</h2>
     <form method = "post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Upload</button>
    </form>

你能告诉我代码中的错误吗?因为该表单未显示在模板中。谢谢你提前

jmp7cifd

jmp7cifd1#

这里有几件事:
1.正确配置您的settings.py。当使用媒体时,您需要配置您的项目以处理媒体文件,如下所示:

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

1.您还需要在项目级别上配置urls.py,它看起来像下面这样:

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

if settings.DEBUG:
    static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
  1. Views.py
    您的视图应该如下所示:
def upload_image(request):
    if request.method == 'POST':
        form = ImageForm(request.POST, request.FILES) # ensure you include request.files
        if form.is_valid():
            form.save()
            return redirect('upsc_main.html')  # Redirect to a success page
    else:
        form = ImageUploadForm()
    return render(request, 'yoururl.html', {'form': form})

然后显然配置您的应用程序urls.py,html模板等。

相关问题