字段“ id”需要一个数字但得到了“ r”-Django形式

时间:2020-05-08 23:53:20

标签: python django python-3.x django-models django-forms

我有一个创建博客文章的Django表单,但是该表单在提交时会引发异常。奇怪的是,他们仍然创建了这些帖子,我可以在另一页上查看。这是我的models.py,views.py,form.py代码和堆栈跟踪。

Models.py


from django.db import models
from django.utils import timezone
from django.contrib.auth import get_user_model

User = get_user_model()


class Author(models.Model):
    """ Inherits the auth user model """
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.user.username


class Category(models.Model):
    """ Generic entries so posts can be filtered """
    title = models.CharField(max_length=20)

    def __str__(self):
        return self.title


class News_Post(models.Model):
    """ Inherits Category & Author Models """
    title = models.CharField(max_length=100)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    date_modified = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    categories = models.ManyToManyField(Category)
    featured = models.BooleanField()
    post_img = models.ImageField(default='default.jpg')

    def __str__(self):
        return self.title

Forms.py:

from .models import News_Post
from django import forms


class News_Post_Form(forms.ModelForm):
    """ Form responsible for creating new posts. """
    id = None
    content = forms.CharField()
    categories = forms.CharField()
    featured = forms.BooleanField()
    post_img = forms.ImageField()

    class Meta:
        model = News_Post
        fields = [
            'title',
            'content',
            'categories',
            'featured',
            'post_img',
        ]

Views.py


from django.shortcuts import render, redirect
from .models import News_Post, Author
from .forms import News_Post_Form
from django.contrib.auth.decorators import login_required

from django.views.generic import CreateView


def get_author(user):
    """Gets the author"""
    ath= Author.objects.filter(user=user)
    if ath.exists():
        return ath[0]
    return None


class PostCreateView(CreateView):
    """Generic post view """
    model = News_Post
    template_name = 'create_post.html'
    form_class = News_Post_Form

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = 'Create'
        return context

    def form_valid(self, form):
        form.instance.author = get_author(self.request.user)
        form.save()


@login_required
def news_post_create(request):
    """ Creates new posts """
    title = 'Create a new post.'
    author = get_author(request.user)
    form = News_Post_Form(request.POST or None, request.FILES or None)

    if request.method == 'POST':
        if form.is_valid():
            form.instance.author = author
            form.clean()
            form.save()
            return redirect('blog/posts.html')
    context = {
        'title': title,
        'form': form,

    }
    return render(request, 'blog/create_post.html', context)


@login_required
def news_post(request):
    """ Renders the 'News_Post' model. """
    query = News_Post.objects.filter(featured=True)
    context = {
        'obj_list': query
    }
    return render(request, 'blog/posts.html', context)

不想用大量文本来阻塞帖子,因此出于可读性目的,我使用了Django的堆栈跟踪共享功能:Stack trace

我不知道字符“ r”是从哪里来的,因为它仍然在更新数据库,有人可以提供原因的解释吗?另外,我还尝试了以下操作: ValueError: Field 'id' expected a number but got 'Processing'

1 个答案:

答案 0 :(得分:0)

问题已解决。

我正在使用Materialize CSS框架,它将覆盖默认复选框,并选择HTML标记属性,因此您需要使用Javascript对其进行初始化。 Select - Materialize

因此,我正试图将值插入外键值。