从 Django 视图上传图像

发布于 2024-11-15 11:05:50 字数 626 浏览 3 评论 0原文

模型:

from django.db import models
class Image(models.Model):
    advertisement = models.ForeignKey('Advertisement')
    image = ImageWithThumbsField(upload_to=store_path, blank=True)

class Advertisement(models.Model):
    #some code here

class AdvertOne(Advertisement):
    #some code again

class AdvertTwo(Advertisement):
    #and again

表单:

from models import Advertisement
from django.forms import *

class AdvertisementForm(ModelForm):
    message = CharField(max_length=400, widget=Textarea)
    image = ImageField(required=False)

问:我应该如何形成上传视图?

Models:

from django.db import models
class Image(models.Model):
    advertisement = models.ForeignKey('Advertisement')
    image = ImageWithThumbsField(upload_to=store_path, blank=True)

class Advertisement(models.Model):
    #some code here

class AdvertOne(Advertisement):
    #some code again

class AdvertTwo(Advertisement):
    #and again

Forms:

from models import Advertisement
from django.forms import *

class AdvertisementForm(ModelForm):
    message = CharField(max_length=400, widget=Textarea)
    image = ImageField(required=False)

Q: How should I form an upload view?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

荆棘i 2024-11-22 11:05:50

像这样的东西应该有效。确保在表单标记中包含 enctype="multipart/form-data" 以便上传文件。

def upload_advertisement(request):
    if request.method == "POST":
        form =  AdvertisementForm(request.POST,request.FILES, prefix='advertisement')
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/")
    else:    
        form =  AdvertisementForm(prefix='advertisement')

    return render_to_response('advertisementform.html', {
        'form':form,
    }, context_instance=RequestContext(request))

Something like this should work. Make sure you inlcude enctype="multipart/form-data" in your form tag so the files get uploaded.

def upload_advertisement(request):
    if request.method == "POST":
        form =  AdvertisementForm(request.POST,request.FILES, prefix='advertisement')
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/")
    else:    
        form =  AdvertisementForm(prefix='advertisement')

    return render_to_response('advertisementform.html', {
        'form':form,
    }, context_instance=RequestContext(request))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文