MOUHAMED FARDOUSI
MOUHAMED FARDOUSI

Reputation: 37

Django form are not working in html template its just show button

I'm trying to create a form in Django template but it is just not showing the fields. my files: models.py where i created the desired table

from django.db import models
from django.contrib.auth.models import User
from django.db.models.deletion import CASCADE
STATUS = (
    (0,"Draft"),
    (1,"Publish")
)
class Post(models.Model):
    title = models.CharField(max_length=50)
    slug = models.SlugField(max_length=200)
    auther = models.ForeignKey(User,on_delete=CASCADE,related_name="blog_posts")
    updated_on = models.DateTimeField(auto_now=True)
    created_on = models.DateTimeField( auto_now_add=True)
    status = models.IntegerField(choices=STATUS,default=0)
    body = models.TextField()

    def __str__(self):
        return self.title

views.py where i created the view for the form

from post.models import Post
from django.shortcuts import redirect, render
from . forms import PostForm
def post_list(request):

    posts = Post.objects.all
    form = PostForm(request.POST)
    if request.method == "POST":
        if form.is_valid():
            form.save(commit=False)
            form.auther = request.user
            form.save()
            return redirect("/")
        else:
            form = PostForm()

    
    context = {
        "posts":posts,
        "form":form,
    }
    return render(request,'index.html',context)

forms.py where i created the form to edit only one field in the table

from django import forms
from django.db.models import fields
from django import forms
from . models import Post

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields='__all__'

index.html here is how i used the form in the html template

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Blog App</title>
</head>
<body>
    {% for post in posts %}
    <div>
        <h1>{{post.title}}</h1>
    </div>
    {{post.body}}
    {% endfor %}

<form method="post" action="/">
    {% csrf_token %}
    {{form}}
    <input type="submit" value="save">
</form>
</body>
</html>

Upvotes: 0

Views: 184

Answers (1)

Yilmaz
Yilmaz

Reputation: 49182

You did not add any field to the PostForm class:

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields='__all__'

Since u have no field, nothing will be displayed.

class PostForm(forms.ModelForm):
    user_name=forms.CharField()
    class Meta:
        model = Post
        fields='__all__'

Upvotes: 1

Related Questions