0

index.html

 <div class="container add_dog_form">
            <form method="POST">
                {% csrf_token %}
                <div class="row" id="namefield">
                    {{ form.as_table }}
                </div>
                <div class="row">
                    <button type="Submit" id="form_submit">Submit</button>
                </div>
            </form>
        </div>

forms.py

class DogForm(forms.ModelForm):

    class Meta:
        model = Dog
        fields = ['name', 'dog_pic']

views.py

class IndexView(generic.ListView):
    template_name = "takyi1/index.html"
    context_object_name = "dogs_context"
    dog_form = DogForm

    def get_context_data(self, **kwargs):
        self.dogs_context = super().get_context_data(**kwargs)
        self.dogs_context['dogs'] = self.dog
        self.dogs_context['form'] = self.dog_form
        return self.dogs_context

    def post(self, request, *args, **kwargs):
        form = self.dog_form(request.POST)

        if form.is_valid():
            form.save()
            return HttpResponse('Valid Form')
        else:
            return HttpResponse('inValid Form')
Shreeyansh Jain
  • 1,407
  • 15
  • 25
  • Why are you using `ListView`? You should use` CreateView` instead. –  Oct 26 '21 at 02:39
  • You forgot to include `action` in form tag –  Oct 26 '21 at 16:11
  • @bichanna ive changed to CreateView. It didnt work though. Ive realised the problem is with the Image. when i use only the name field in the form, it saves successfully. BUt when i add the imagefield, thats when it keeps returning invalid form. Any help with that please? – Yaw Otuo Oct 27 '21 at 15:51

1 Answers1

0

easiest method is to building a html form and saving data into Model by post method.

Using of ModelForm just makes it difficult.

If you use below code, It works perfectly

class IndexView(generic.ListView):
    template_name = "takyi1/index.html"
    model = Dog
  
    def post(self, request):
        self.model(name=request.POST['name'],
                   dog_pic=request.POST['dog_pic']).save( )
        return HttpResponse('Valid Form')