How to pass form into template and save it? Django

Viewed 132

Hello I have a question how can I pass a form into HTML template and save it in class based view? As you see in views.py I have made Item.objects.create after Post request but is it a good practice if Django provides forms?

Form:

class itemCreationForm(ModelForm):
    name = forms.CharField()
    class Meta:
        model = Item
        fields = ['name']

views.py:

class Home(ListView):
   model = Item
   template_name = 'home/todo.html'
   form_class = itemCreationForm
   def post(self, request):
      item = self.request.POST.get('item')
      Item.objects.create(name=item)
      
      return HttpResponse(f'Post! {item}')
1 Answers

I would advise to work with a CreateView instead, and add some extra logic to display a list.

We can implement this with:

from django.urls import reverse

class HomeView(CreateView):
    model = Item
    template_name = 'home/todo.html'
    form_class = itemCreationForm

    def get_context_data(self, *args, **kwargs):
        data = super().get_context_data(*args, **kwargs)
        data['object_list'] = Item.objects.all()
        return data

    def get_success_url(self):
        return reverse('name-of-home-view')

That way you can use {{ form }} to render the form, it will also handle a POST request and create the instance, and you can access the object_list in the template to render the list of items.

Related