User0511
User0511

Reputation: 725

Can't add file in django 1.7

I cannot add a file in Django. When I click the "save" button, it does not save the database.

This is my view.py:

def add_product(request):
    if request.method == "POST":
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            post.userprofile = request.user
            post.save()
            return redirect('kerajinan.views.add_product', pk=post.pk)
    else:
        form = PostForm()
        return render(request, 'kerajinan/add_product.html', {'form': form})

add_product.html:

    {% block content %}
    <h1>New Product</h1>
    <from method="POST" class="post-form" enctype="multiple/form-data">{% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="save btn btn-default">Save</button>
    </from>
{% endblock %}

forms.py:

class PostForm(forms.ModelForm):
    class Meta:
        model   = Product
        fields  = ('category','title', 'price','image', 'description')

and urls.py:

url(r'^add_product/$', views.add_product, name='add_product'),

Can you help me solve my problem?

Upvotes: 2

Views: 64

Answers (1)

rnevius
rnevius

Reputation: 27102

You need to change your enctype to: enctype="multipart/form-data"

Your current value (multiple/form-data), is not a valid method of encoding.

From the docs:

Note that request.FILES will only contain data if...the <form> that posted the request has the attribute enctype="multipart/form-data". Otherwise, request.FILES will be empty.

Upvotes: 1

Related Questions