0

Hello I followed steps here;Need a minimal Django file upload example I'm not sure what I did wrong. I'm trying to add a feature that user to be able to post pictures as well. Here's my try

settings.py

MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_in_env", "media_root")
MEDIA_URL = '/media/'

    models.py

class Category(models.Model): 
    image = models.ImageField(upload_to='images',blank=True, null=True)

forms.py

class CategoryForm(forms.ModelForm):
    name = forms.CharField(max_length=128)
    description = forms.CharField(max_length=300)
    image = forms.ImageField()

    class Meta:
        model = Category



my views.py

@login_required
def add_category(request):
    if not request.user.is_superuser and Category.objects.filter(author=request.user).exists():
        return render(request,'main/category_already_exists.html')
    if request.method == 'POST':
        category = Category(author=request.user)
        form = CategoryForm(request.POST, instance=category)
        if form.is_valid():
            form.save(commit=True)
            return redirect('index')

    else:
        form = CategoryForm()

    return render(request, 'main/add_category.html', {'form':form})


category.html

{% load staticfiles %}

{{category.image}} 
Community
  • 1
  • 1
mike braa
  • 647
  • 1
  • 12
  • 33
  • Are you receiving an exception? If so, please add the stack trace. Also, can you please add the template where you have the form for uploading the image. – Rod Xavier Jan 18 '16 at 00:14
  • Questions seeking debugging help (**"why isn't this code working?"**) must include the desired behavior, *a specific problem or error* and *the shortest code necessary* to reproduce it **in the question itself**. Questions without **a clear problem statement** are not useful to other readers. See: [How to create a Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve). – MattDMo Jan 18 '16 at 00:17

1 Answers1

0

I am assuming you are missing enctype form attribute in your template.

<form method="POST" enctype="multipart/form-data">
  {{ form.as_p }}
  <input type="submit" value="Submit" />
</form>

Also, in your views, instantiating your form should be

form = CategoryForm(request.POST, request.FILES, instance=category)
Rod Xavier
  • 3,983
  • 1
  • 29
  • 41