【问题标题】:Im trying using class modelForm in django我尝试在 django 中使用类 modelForm
【发布时间】:2022-08-21 12:20:14
【问题描述】:

我的模型.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,)

我的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\'}),

        }

和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)

我有错误 /blog/1/ 处的 ValueError ModelForm 没有指定模型类。 请求方法:GET 请求网址:http://localhost:8000/blog/1/ Django 版本:4.0.2 异常类型:ValueError 异常值:
ModelForm 没有指定模型类。

    标签: python django django-models django-views


    【解决方案1】:

    我想,你已经用小写写了meta,用Meta 写成Pascal case,然后用Comment 等PascalCase 写出你所有的模型。

    【讨论】:

    • 还要在 PascalCase 中编写所有模型,否则它们稍后会出错。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 2018-11-14
    • 1970-01-01
    • 1970-01-01
    • 2011-11-25
    相关资源
    最近更新 更多