How do I use a form to update a model?

18 views
Skip to first unread message

Zev

unread,
Sep 24, 2017, 3:01:45 PM9/24/17
to Django users

So what I'm trying to do is display a model on a page and then use a form to update said model on the page. I've managed to create a form and display it on the page, and I have managed to create to create a model--though I haven't gotten to display it on the page.

This is what I have so far for the form:


from django import forms

class IndexForm(forms.Form):
     post
= forms.CharField()


This is my models:

 

from django.db import models

class Post(models.Model):
    post
= models.CharField(max_length=141)


 

My views:

 

from django.shortcuts import render
from firstapp.forms import IndexForm
from django.views.generic import TemplateView
from firstapp.models import Post

class HomePage(TemplateView):
    template_name
= 'home/home.html'

   
def get(self, request):
        form
= IndexForm()
        posts
= Post.objects.all()
        args
= {'form': form, 'posts': posts}
       
return render(request, self.template_name, args)


 

This is my base.html:

 

{% load staticfiles %}

<!DOCTYPE html>
<html>
   
<head>
       
<meta charset="UTF-8">
       
<title>Home</title>
        <link rel='stylesheet' href='{% static "css/
base.css" %}'/>
    </head>
    <body>
        {% block body %}{% endblock %}
        <script src= '{% static "
js/base.js" %}'></script>
    </body>
</html>


 

And finally my home.html:

 

{% extends 'base.html' %}

{% block body %}

<div class="container">
   
<p>Home</p>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Submit</
button>
   
</form>
</
div>

{% endblock %}


 

So how would I go about changing this so the home page would display a form and a model with something like "Name: [Your Name]" and when you input your name in the form, the model would update itself to be "Name: ‘input’"?


I've been trying to figure this out for a week to no success, so I truly appreciate the help. Thank you!

C. Kirby

unread,
Sep 25, 2017, 9:53:11 AM9/25/17
to Django users
Sounds like you want a ModelForm. Docs are here: https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/
Reply all
Reply to author
Forward
0 new messages