通过django中的ModelForm上传图片

时间:2017-12-08 16:27:12

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

当我尝试提交表单时,它会显示“此字段是必填字段”。 对于图像,即使我提供图像和其他细节。

forms.py文件

from django.forms import ModelForm
from .models import Status

class CreatePost(ModelForm):

    class Meta:
        model=Status
        fields = ["username","text","privacy","image"]

models.py文件

class Status(models.Model):
    title=models.CharField(max_length=20,default="updated status")
    username = models.ForeignKey('User',on_delete=models.CASCADE)
    #username = models.CharField(max_length=20)
    text = models.TextField(blank=True, null=True)
    image = models.ImageField(upload_to="media/image",null=True)
    time = models.DateTimeField(auto_now=True)
    privacy = models.CharField(max_length=5, blank=True, null=True)
    gid = models.IntegerField(blank=True, null=True)
    dp = models.SmallIntegerField(blank=True, null=True)

    class Meta:
        #unique_together = (('username', 'dp'),)
        #managed = False
        db_table = 'status'

view.py

def create_post(request):
    form=CreatePost(request.POST or None)
    if request.method=="POST":
        if form.is_valid():
            instance=form.save(commit=False)
            instance.time=time.time()
            instance.save()
            return redirect('post',)

    return render(request,"uposts/createpost.html",{'form':form})

createpost.html

{% extends "friendsbook/structure.html" %}
{% block content %}
<form action="" method="post">
    {%csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Save">
</form>

{% endblock %}

点击保存按钮

后的内容

enter image description here

我只在表单中填写4个字段,因为所有其他字段都可以为null。对于时间字段,我在views.py中通过给出时间来处理它。

1 个答案:

答案 0 :(得分:0)

您必须像这样添加multipart / form-data修改模板:

SpriteRenderer

在views.py中,您可以使用const { JSDOM } = require('jsdom'); const jsdom = new JSDOM(); const { window } = jsdom; function copyProps(src, target) { const props = Object.getOwnPropertyNames(src) .filter(prop => typeof target[prop] === 'undefined') .map(prop => Object.getOwnPropertyDescriptor(src, prop)); Object.defineProperties(target, props); } global.window = window; global.document = window.document; global.navigator = { userAgent: 'node.js', }; copyProps(window, global); // Setup adapter to work with enzyme 3.2.0 const Enzyme = require('enzyme'); const Adapter = require('enzyme-adapter-react-16'); Enzyme.configure({ adapter: new Adapter() }); // Ignore React Web errors when using React Native console.error = (message) => { return message; }; require('react-native-mock-render/mock'); 访问上传的文件。