Search code examples
djangodjango-modelsdjango-viewsdjango-formsdjango-templates

model form not rendering in django template


My models.py and this is my model for photos.

       # home photo page
    class Photos(models.Model):
        photo_title = models.CharField(max_length=50, blank=False)
        photo_description = models.CharField(max_length=50, blank=False)
        photo_date = models.DateField(blank=False)
        photo_location = models.CharField(max_length=50, blank=False)
        photo_file = models.FileField(upload_to='photos', blank=False)
    
        def __str__(self):
            return self.photo_title

My forms.py this is the model form I made to render it as a form.

    class UploadPhotosForm(forms.Form):
    
        class Meta:
            model = Photos
            fields = '__all__'
    

my views.py these are my relavent imports and section I coded in view file.

from .forms import CampForm, ProjectForm, HikeForm, UploadPostsForm, UploadPhotosForm

    posts = UploadPostsForm()
    photo = UploadPhotosForm()

    print(photo.as_p())

here this code should print the form as text into console isn't it? But I don't have any console output. It seems like the nothing has been initialized to the photo variable isn't it? I do not have any clue what happened.

    context = {
        'title': 'manage_wall',
        'posts': posts,
        'photo': photo,
    }
    return render(request, 'manager/manage_wall.html', context)

My template

{% block content %}
<div class="container">
    <div class="row">
        <div class="col">
            <form action="" method="post">
                {% csrf_token %}
                {{photo.as_p}}
                <input type="submit" value="Add">
            </form>
        </div>
        <div class="col">
            <form action="" method="post">
                {% csrf_token %}
                {{posts.as_p}}
                <input type="submit" value=" Add">
            </form>
        </div>
    </div>
</div>
{%endblock %}

enter image description here

As you can see here my photoForm is not rendering in the frontend can someone point out the mistake I have made not to render that form only while other forms are successfully rendering in the frontend. My Question is all other model forms rendered successfully why this is not displaying properly.


Solution

  • Your UploadPhotosForm is inherited from forms.Form(...) class which does not contain model in Meta class so instead of inheriting from forms.Form class inherit from form.ModelForm(...)

    here is final version of your code

     class UploadPhotosForm(forms.ModelForm):
         class Meta:
             model = Photos
             fields = '__all__'