Home > Mobile >  How to link my HTML form to a view class in Django
How to link my HTML form to a view class in Django

Time:04-25

post_form.Html

This is an Html Page With Form to Update and Create As We Know that Create And Update View Class in Django used the same form

     <form method="post">
    {% csrf_token %}
    <div >
        <label for="PostInput">PostTitle</label>
        <input  type="text" name="post" placeholder="Name" value="{{ post.postname }}">
    </div>
    <div >
        <label for="descrInput">Description</label>
        <input  type="text" id="descrInput" placeholder="Description" value="{{ post.description }}">
    </div>
    <input type="submit" value="Save">
</form>

Views.py

class CreatePost(CreateView):
    model = post
    fields = ['title', 'content']

class UpdatePost(UpdateView):
    model = post
    fields = ['title', 'content']

Now, the question is how can i link this form with the above html page which already has form or input fields in the web page itself. I know how to do it using function views but i am not getting any materials, tutorials anything about this. Any Material regarding this will be helpful

CodePudding user response:

You can override CreateView().post() and UpdateView().post() methods like this

class CreatePost(CreateView):
    model = post
    fields = ['title', 'content']
    
    def post(self, request, *args, **kwargs):
        # Get your data from post request eg. request.POST['mykey']
        return redirect('success_page')

class UpdatePost(UpdateView):
    model = post
    fields = ['title', 'content']

    def post(self, request, *args, **kwargs):
        # Get your data from post request eg. request.POST['mykey']
        return redirect('success_page')

Note : You've created your post model class in lowercase which is not good practice always name a class in CapWords. Because you have written your class in lowercase python will treat your post class as a post or it may lead to logical error.

  • Related