How to add an image to a form in django

I made a video showing the parts of code needed to add an image to a form in django and posted the code for each part below the video.

Here is the code needed:

views.py:

def userpostscreate(request):
    form = UserpostsForm(request.POST, request.FILES)
    if form.is_valid():
        form.save()

    context = {
        'form': form
    }
    return render(request, "users/userpostscreate.html", context)

settings.py

STATIC_URL = '/static/'
MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
    )

forms.py

from .models import Userposts

class UserpostsForm(forms.ModelForm):
    class Meta:
        model = Userposts
        fields = ['puser', 'ppost', 'image']
        widgets = {'puser': forms.HiddenInput()}

html

<form method='POST' enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.media }}
    {{ form.as_p }}

    <div style="display:none;"><input type="hidden" name=puser value={{ request.user.id }}></div>

    <input type='submit' value='Post' />
</form>

models.py

class Userposts(models.Model):
    puser = models.IntegerField()
    ppost = models.CharField(max_length=280)
    post_datetime = models.DateTimeField(auto_now=False, auto_now_add=True)
    image = models.ImageField(null=True, blank=True, upload_to="images/")

    def __str__(self):
        return f"{self.post_datetime} - {self.ppost}"

Leave a comment

Your email address will not be published. Required fields are marked *