Django 版本 3.1.3 表单未保存到模型

Django version 3.1.3 form not saving to model

我正在关注这个tutorial

我已经回去写代码来完全匹配了。我有另一种名为 category_add 的表格,它与此表格完全相同。但是对于我的生活,我无法弄清楚为什么 bookmark_add 不使用表单条目更新数据库。

Models.py

from django.db import models
from django.contrib.auth.models import User


class Category(models.Model):
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True, null=True)

    created_by = models.ForeignKey(User, related_name='categories', on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = 'Categories'

    def __str__(self):
        return self.title


class Bookmark(models.Model):
    category = models.ForeignKey(Category, related_name='bookmarks', on_delete=models.CASCADE)
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True, null=True)
    url = models.CharField(max_length=255, blank=True)

    created_by = models.ForeignKey(User, related_name='bookmarks', on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

View.py

from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required

from .forms import BookmarkForm


@login_required
def bookmark_add(request, category_id):
    if request.method == 'POST':
        form = BookmarkForm(request.POST)
        if form.is_valid():
            bookmark = form.save(commit=False)
            bookmark.created_by = request.user
            bookmark.category_id = category_id
            bookmark.save()
            return redirect('category', category_id=category_id)

    else:
        form = BookmarkForm()

    context = {
        'form': form
    }

    return render(request, 'bookmark/bookmark_add.html', context)

Forms.py

from django.forms import ModelForm

from .models import Bookmark


class BookmarkForm(ModelForm):
    class Meta:
        model = Bookmark
        fields = ['title', 'description', 'url']

Urls.py

    path('', dashboard, name='dashboard'),
    path('categories/', categories, name='categories'),
    path('categories/add/', category_add, name='category_add'),
    path('categories/<int:category_id>/', category, name='category'),
    path('categories/<int:category_id>/add_bookmark', bookmark_add, name='bookmark_add')
]

bookmark_add.html

{% extends 'core/base.html' %}

{% block content %}
<div class="container">
    <h1 class="title">Add link</h1>

    <form method="post" action=".">
        {% csrf_token %}
        {{ form.as_p }}

        <button type="submit" class="button is-primary">Submit</button>
    </form>
</div>

{% endblock %}

解决了!

这是一个愚蠢的问题,也是我的疏忽。感谢 youtube 上的内容创建者。我只需要将“/”附加到 add_bookmark 的 url 路径。

问题: path('categories/<int:category_id>/add_bookmark', bookmark_add, name='bookmark_add')

修复: path('categories/<int:category_id>/add_bookmark/', bookmark_add, name='bookmark_add')