python - Django:收到错误消息 "needs to have a value for field "id“在可以使用此多对多关系之前”

标签 python django

我是 Django 的初学者。现在,我正在通过构建一个名为 PhoneReview 的应用程序来学习该框架。它将存储与最新手机相关的评论。它还将显示手机品牌、相关手机型号及其评论。

当我访问http://127.0.0.1:8000/index时,我看到这个页面: enter image description here

当我点击三星时,我看到此页面:

enter image description here

到此为止就可以了。 但是,当我单击任何手机型号(例如 Galaxy S10)时,我收到 404 错误。它看起来像这样:

Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/details/galaxy-s10
Raised by:  PhoneReview.views.ReviewView
No review found matching the query

You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

当我点击 Samsung 时,我应该会看到 details.html 页面,其中包含手机的评论以及新闻链接。相反,我收到了 404 错误。

我认为通过 Django admin 执行迁移并添加有关任何手机型号(例如 Galaxy S10)的新评论可以解决该问题。但是当我尝试通过 Django admin 添加 Galaxy S10 的评论时,出现此错误:

"<Review: The Galaxy S10 is a fitting 10th anniversary phone for Samsung and its storied S series. It delivers on change with a novel-looking Infinity-O screen so large it displaces the front camera, and a triple-lens rear camera that takes ultra-wide photos. Its in-screen fingerprint sensor tech should serve you well, while its Wireless PowerShare could serve your friends well. That’s a lot of change – just know that it comes at a high price and the Galaxy S10e and S10 Plus flank it from both sides of the coin as better options.>" needs to have a value for field "id" before this many-to-many relationship can be used.

这是我位于 PhoneReview 文件夹中的 models.py 代码:

from django.db import models
from django.template.defaultfilters import slugify

# Create your models here.
class Brand(models.Model):
    brand_name = models.CharField(max_length=100)
    origin = models.CharField(max_length=100)
    manufacturing_since = models.CharField(max_length=100, null=True, blank=True)
    slug = models.SlugField(max_length=150, null=True, blank=True)

    def __str__(self):
        return self.brand_name

    def save(self, *args, **kwargs):
        self.slug = slugify(self.brand_name)
        super().save(*args, **kwargs)

class PhoneModel(models.Model):
    brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
    model_name = models.CharField(max_length=100)
    launch_date = models.CharField(max_length=100)
    platform = models.CharField(max_length=100)
    slug = models.SlugField(max_length=150, null=True, blank=True)

    def __str__(self):
        return self.model_name

    def save(self, *args, **kwargs):
        self.slug = slugify(self.model_name)
        super().save(*args, **kwargs)

class Review(models.Model):
    phone_model = models.ManyToManyField(PhoneModel, related_name='reviews')
    review_article = models.TextField()
    date_published = models.DateField(auto_now=True)
    slug = models.SlugField(max_length=150, null=True, blank=True)
    link = models.TextField(max_length=150, null=True, blank=True)

    def __str__(self):
        return self.review_article

    def save(self, *args, **kwargs):
        self.slug = slugify(self.phone_model)
        super().save(*args, **kwargs)

这是我位于 PhoneReview 文件夹中的 urls.py 代码:

from . import views
from django.urls import path

app_name = 'PhoneReview'

urlpatterns = [
    path('index', views.BrandListView.as_view(), name='brandlist'),
    path('phonemodel/<slug:slug>', views.ModelView.as_view(), name='modellist'),
    path('details/<slug:slug>', views.ReviewView.as_view(), name='details'),
]

这是我位于 PhoneReview 文件夹中的 views.py 代码:

from django.shortcuts import render, get_object_or_404
from django.views import generic
from .models import Brand, PhoneModel, Review


class BrandListView(generic.ListView):
    template_name = 'PhoneReview/index.html'
    context_object_name = 'all_brands'

    def get_queryset(self):
        return Brand.objects.all()


class ModelView(generic.ListView):
    template_name = 'PhoneReview/phonemodel.html'
    context_object_name = 'all_model_name'

    def get_queryset(self):
        self.brand = get_object_or_404(Brand, slug=self.kwargs['slug'])
        return PhoneModel.objects.filter(brand=self.brand)

class ReviewView(generic.DetailView):
    model = Review
    template_name = 'PhoneReview/details.html'

这是我位于 PhoneReview 文件夹中的 apps.py 代码:

from django.apps import AppConfig


class PhonereviewConfig(AppConfig):
    name = 'PhoneReview'

这是我位于 templates 文件夹内的 index.html 代码:

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

{% load static %}

{% block title%}
Brand List
{% endblock %}

{% block content %}
<!--Page content-->
<h1>This is Brand List Page</h1>
<h2>Here is the list of the brands</h2>
    <ul>
        {% for brand in all_brands %}
<!--            <li>{{ brand.brand_name }}</li>-->
            <li><a href = "{% url 'PhoneReview:modellist' brand.slug %}">{{ brand.brand_name }}</a></li>
        {% endfor %}
    </ul>
<img src="{% static "images/brandlist.jpg" %}" alt="Super Mario Odyssey" /> <!-- New line -->
{% endblock %}

这是我位于 templates 文件夹内的 phonemodel.html 代码:

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

{% load static %}

{% block title%}
Phone Model Page
{% endblock %}

{% block content %}
<!--Page content-->
<h1>This is Phone Model Page</h1>
<h2>Here is the phone model</h2>
    <ul>
        {% for phonemodel in all_model_name %}
            <li><a href = "{% url 'PhoneReview:details' phonemodel.slug %}">{{ phonemodel.model_name }}</a></li>
        {% endfor %}
    </ul>
<img src="{% static "images/brandlist.jpg" %}" alt="Super Mario Odyssey" /> <!-- New line -->
{% endblock %}

这是我位于 templates 文件夹内的 details.html 代码:

{% extends 'PhoneReview/base.html' %}
{% load static %}

<html>

<link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}">


<html lang="en">

{% block title%}Details{% endblock %}

{% block content %}

<h1>This is the Details Page</h1>

<h2>Review:</h2>
<p>{{ review.review_article }}</p>

<h2>News Link:</h2>
<a href={{ review.link }}>{{ review.link }}</a>
{% endblock %}
</html>

details.html有什么问题吗?

最佳答案

您的审核模型保存方法有问题。因为 slugify(self.phone_model) 是在多对多字段添加值之前执行的。

尝试

通过注释掉 Review 模型的保存方法

关于python - Django:收到错误消息 "needs to have a value for field "id“在可以使用此多对多关系之前”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58880898/

相关文章:

python - 在 CentOS 8 上使用 crontab 时是否有用于 HTTP 请求的页面缓存?

python,正则表达式拆分和特殊字符

python 2.7 : log displayed twice when `logging` module is used in two python scripts

django - 在一个用于CI(Bamboo)的容器中运行postgres 9.5和django

python - 如何在django中将文件保存到数据库

python - Bokeh 条形图未正确显示宽度

python - 如何使我的测试装置仅在 Django 中测试时加载?

django - __init __()获得了意外的关键字参数 'attrs'

python - 如何访问FormView中的request对象

python - 如何在 Django 中创建集成多个应用程序的网站主页?