Sarthak  tiwari
Sarthak tiwari

Reputation: 59

insert image to data with help of form

i am insert data of Django of model with image but image not insert

model.py

class Product(models.Model):
       name = models.CharField(max_length=100,)
       image = models.ImageField(upload_to='images/',null=True)

form.py

class ProductForm(forms.ModelForm):
class Meta:
    model = Product
    fields = '__all__'

views.py

CreateProduct(request):
  context = {}


form = ProductForm(request.POST or None)
if form.is_valid():
    form.save()

context['form'] = form
return render(request, "create_pro.html", context)

html

<form method = "post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Upload</button>
</form>

{% endblock %}

settings.py

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

Upvotes: 1

Views: 281

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

You should pass request.FILES to the form as well:

from django.shortcuts import redirect

def create_product(request):
    if request.method == 'POST':
        form = ProductForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('name-of-view')
    else:
        form = ProductForm()
    return render(request, 'create_pro.html', {'form': form})

In the form, you should probably also fix the spacing:

<form method="post" action="{% url 'name-of-create-product' %}" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Upload</button>
</form>

Note: In case of a successful POST request, you should make a redirect [Django-doc] to implement the Post/Redirect/Get pattern [wiki]. This avoids that you make the same POST request when the user refreshes the browser.

Upvotes: 1

Related Questions