当我尝试创建博客时 post 显示非空约束失败:blog_blog.id

when i try to create a blog post is shows not null constraint failed: blog_blog.id

当我尝试创建博客时 post 显示 not null constraint failed: blog_blog.id 我已尽一切可能解决此问题但它仍然无法正常工作 我不知道是否应该添加和我的 models.py 中的 id 字段 让我展示一下我的代码

models.py

# some field are commented out because i was trying them to see if it would work
class Blog(models.Model):
    id = models.UUIDField(primary_key=True, editable=False)
    title = models.CharField(max_length=10000, null=True, blank=True, verbose_name="Title")
    content = models.TextField(verbose_name="Post Content")
    # slug = models.SlugField(unique=True)
    image = models.ImageField(upload_to="blog-images/%Y/%m/%d/", verbose_name="Post Thumbnail")
    category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, verbose_name="Category", null=True)
    tags = models.ManyToManyField(Tag, related_name='tags', verbose_name="Tag")
    status = models.CharField(choices=STATUS_CHOICE, default="published", max_length=150, verbose_name='Status')
    creator = models.ForeignKey(User, on_delete=models.DO_NOTHING, verbose_name="Creator", null=True)
    created = models.DateTimeField(auto_now_add=True ,verbose_name="Created", null=True)

    def get_absolute_url(self):
        # return reverse('blog:blog-details', args=[self.slug])
        return reverse('blog:blog-details', kwargs={'pk': self.pk})
    
    class Meta:
        verbose_name = "Blog Post"
        verbose_name_plural = "Blog Posts"
    
    def __str__(self):
        return self.title

views.py

def blogpost(request):
    if request.method == "POST":
        form = BlogPostForm(request.POST, request.FILES)
        if form.is_valid():
            form = form.save(commit=False)
            form.creator = request.user
            form.save()
            messages.success(request, f'Hi, Your Post have been sent for review and would be live soon!')
            return redirect('blog:home')
    else:
        form = BlogPostForm()

    context = {
        "form": form
    }
    return render(request, 'blog/AddPost.html', context)

urls.py

path('', views.blog_list, name="home"),
    path('post/<int:pk>', views.blog_detail, name="blog-details"),
    path('post/categories/<slug:category_slug>', views.category, name="category"),
    path('post/tags/<slug:tag_slug>', views.tag, name="tags"),

    path('post/create/', views.blogpost, name="add-post"),


forms.py

class BlogPostForm(forms.ModelForm):
    image = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True}), required=True)
    # content = forms.CharField(widget=forms.Textarea(attrs={'class': 'input is-medium'}), required=True)
    tags = forms.CharField(widget=forms.TextInput(attrs={'class': 'input is-medium'}), required=True)

    class Meta:
        model = Blog
        fields = ('title', 'content', 'image', 'category', 'tags')

addpost.html

<form action="" method="POST" enctype="multipart/form-data">
                            {% csrf_token %}
                            {{form|crispy}}
                        <div class="form-group">
                            <button class="btn theme-bg rounded" type="submit">Send Message</button>
                        </div>
                        </form>

这是我的完整追溯,并且有一条关于我最近遇到的错误的评论 任何帮助将不胜感激


System check identified no issues (0 silenced).
November 18, 2021 - 22:48:00
Django version 3.2.9, using settings 'dexxapikprj.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[18/Nov/2021 22:48:02] "GET /blog/post/create/ HTTP/1.1" 200 23653
[18/Nov/2021 22:48:03] "GET /static/assets/fonts/themify.ttf?-fvbane HTTP/1.1" 404 1940
Internal Server Error: /blog/post/create/
Traceback (most recent call last):
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1823, in get_prep_value
    return int(value)
ValueError: invalid literal for int() with base 10: 'd'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Destiny\Desktop\DexxaPik\dexxapikprj\blog\views.py", line 44, in blogpost
    form.save()  # ← no commit=False
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\forms\models.py", line 469, in save
    self._save_m2m()
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\forms\models.py", line 451, in _save_m2m
    f.save_form_data(self.instance, cleaned_data[f.name])
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\db\models\fields\related.py", line 1668, in save_form_data
    getattr(instance, self.attname).set(data)
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 1007, in set
    else self.target_field.get_prep_value(obj)
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\db\models\fields\related.py", line 977, in get_prep_value
    return self.target_field.get_prep_value(value)
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1825, in get_prep_value
    raise e.__class__(
ValueError: Field 'id' expected a number but got 'd'.
[18/Nov/2021 22:48:12] "POST /blog/post/create/ HTTP/1.1" 500 97645
[18/Nov/2021 22:48:38] "GET /admin/blog/blog/ HTTP/1.1" 200 14076
[18/Nov/2021 22:48:38] "GET /admin/jsi18n/ HTTP/1.1" 200 3195
[18/Nov/2021 22:48:41] "GET /admin/blog/blog/c9f112b3-e108-4605-9c5b-edb952781045/change/ HTTP/1.1" 200 17761
[18/Nov/2021 22:48:41] "GET /admin/jsi18n/ HTTP/1.1" 200 3195
[18/Nov/2021 22:48:41] "GET /admin/jsi18n/ HTTP/1.1" 200 3195
[18/Nov/2021 22:48:50] "GET /admin/ HTTP/1.1" 200 14858
[18/Nov/2021 22:48:52] "GET /admin/blog/blog/ HTTP/1.1" 200 14076
[18/Nov/2021 22:48:52] "GET /admin/jsi18n/ HTTP/1.1" 200 3195
Internal Server Error: /blog/
Traceback (most recent call last):
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Destiny\Desktop\DexxaPik\dexxapikprj\blog\views.py", line 65, in blog_list
    return render(request, 'blog/bloghome.html', context)
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\shortcuts.py", line 19, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\template\loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\template\backends\django.py", line 61, in render
    return self.template.render(context)
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\template\base.py", line 170, in render
    return self._render(context)
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\template\base.py", line 162, in _render
    return self.nodelist.render(context)
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\template\base.py", line 938, in render
    bit = node.render_annotated(context)
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\template\loader_tags.py", line 150, in render
    return compiled_parent._render(context)
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\template\base.py", line 162, in _render
    return self.nodelist.render(context)
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\template\base.py", line 938, in render
    bit = node.render_annotated(context)
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\template\loader_tags.py", line 62, in render
    result = block.nodelist.render(context)
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\template\base.py", line 938, in render
    bit = node.render_annotated(context)
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\template\defaulttags.py", line 211, in render
    nodelist.append(node.render_annotated(context))
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\template\base.py", line 988, in render
    output = self.filter_expression.resolve(context)
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\template\base.py", line 671, in resolve
    obj = self.var.resolve(context)
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\template\base.py", line 796, in resolve
    value = self._resolve_lookup(context)
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\template\base.py", line 858, in _resolve_lookup
    current = current()
  File "C:\Users\Destiny\Desktop\DexxaPik\dexxapikprj\blog\models.py", line 58, in get_absolute_url
    return reverse('blog:blog-details', kwargs={'pk': self.pk})
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\urls\base.py", line 86, in reverse
    return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
  File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\urls\resolvers.py", line 694, in _reverse_with_prefix
    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'blog-details' with keyword arguments '{'pk': UUID('c9f112b3-e108-4605-9c5b-edb952781045')}' not found. 1 pattern(s) tried: ['blog/(?P<post_id>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$']
[18/Nov/2021 22:48:57] "GET /blog/ HTTP/1.1" 500 200505

任何帮助将不胜感激

由于主键不是 AutoFieldBigAutoField,因此不会自动分配值。

您应该指定一个可以生成随机 UUID 的函数。例如,您可以使用 uuid4() function [Python-doc]:

from uuid import <strong>uuid4</strong>

class Blog(models.Model):
    id = models.UUIDField(primary_key=True<strong>, default=uuid4</strong>, editable=False)
    # …

请注意,因为您没有使用表单保存对象,所以它不会像 tags 那样存储创建的对象的 ManyToManyFields。您可以将视图重写为:

def blogpost(request):
    if request.method == "POST":
        form = BlogPostForm(request.POST, request.FILES)
        if form.is_valid():
            form<strong>.instance.creator = request.user</strong>
            form.save()  # ← no commit=False
            messages.success(request, f'Hi, Your Post have been sent for review and would be live soon!')
            return redirect('blog:home')
    else:
        form = BlogPostForm()

    context = {
        'form': form
    }
    return render(request, 'blog/AddPost.html', context)