Home > Enterprise >  Im trying using class modelForm in django
Im trying using class modelForm in django

Time:02-27

My models.py

from django.db import models

# Create your models here.
class modelBlog(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField()
    body = models.TextField()
    pub_date = models.DateTimeField(auto_now_add=True,)
    
    def __str__(self):
        return ('{}.{}').format(self.id, self.title)
class comment(models.Model):
    blog = models.ForeignKey(modelBlog, on_delete=models.CASCADE)
    name = models.CharField(max_length=200)
    komentar = models.TextField()
    pub_date = models.DateTimeField(auto_now_add=True,)

My forms.py from .models import modelContact, comment from django import forms

class CommentForm(forms.ModelForm):
    class meta:
        model = comment
        fields = [
            'name',
            'komentar',
        ]
        widgets = {
            'name': forms.TextInput(attrs={'class':'form-control'}),
            'komentar': forms.Textarea(attrs={'class':'form-control'}),

        }

AND views.py

def detail(request, id):
    blog = modelBlog.objects.get(id=id)
    form = CommentForm()
    if request.method == 'POST':
        nama = request.POST['nama']
        comment = request.POST['komentar']
        new_comment = blog.comment_set.create(name=nama,komentar=comment)
        new_comment.save()
        messages.success(request, 'Komentar berhasil ditambahkan')
        return redirect('blog:detail', id)
    judul = blog.title
    context = {
        'title':judul,
        'blog':blog,
        'form':form
    }
    return render(request, 'blog/detail.html', context)

i got error ValueError at /blog/1/ ModelForm has no model class specified. Request Method: GET Request URL: http://localhost:8000/blog/1/ Django Version: 4.0.2 Exception Type: ValueError Exception Value:
ModelForm has no model class specified.

CodePudding user response:

I think, you have wrote meta in smallcase, write it in Pascal case that is Meta and write all your models in PascalCase such as Comment and other models.

  • Related