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:

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

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

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

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

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

from .models import Userposts

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


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

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

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

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 *