简体   繁体   English

Django 编辑模型实例无法找到该实例

[英]Django editing a model instance fails to find the instance

I'm in the process of making a Recipe Book.我正在制作食谱书。 For some reason, whenever I try to pull up a recipe from the DB to edit it, I keep getting an error where it can't find the recipe I've specified.出于某种原因,每当我尝试从数据库中提取配方进行编辑时,我都会收到一个错误,提示它找不到我指定的配方。 I'm using slugs, and my logic is that I'm going from a detailView where I've already pulled up the db information, to an updateView.我正在使用 slugs,我的逻辑是我从一个已经提取了数据库信息的 detailView 到一个 updateView。 I'm attempting to pass the recipe object I already pulled from the detailView to the updateView, but when I do, it keeps telling me that it can't find the recipe specified.我试图将我已经从 detailView 中提取的配方对象传递给 updateView,但是当我这样做时,它一直告诉我它找不到指定的配方。

views.py: The base views I'm calling here are only providing a default post method for handling a search so that I don't have to put it in for every view I create so I have some code reusability views.py:我在此处调用的基本视图仅提供用于处理搜索的默认 post 方法,因此我不必为我创建的每个视图都放入它,因此我有一些代码可重用性

class RecipeDetailView(BaseDetailView):
    model = Recipe
    template_name = 'RecipeBook/recipe_detail.html'
    context_object_name = 'recipe_view'
    queryset = None
    slug_field = 'slug'
    slug_url_kwarg = 'slug'

    def get_context_data(self, *args, **kwargs):
        context = super(RecipeDetailView, self).get_context_data()
        recipe = self.object
        recipe.ingredients = recipe.ingredients_list.split('\n')

        context['recipe'] = recipe

        return context

class RecipeEditView(BaseUpdateView):
    model = Recipe
    template_name = 'RecipeBook/edit_recipe.html'
    context_object_name = 'recipe_edit'
    queryset = None
    slug_field = 'slug'
    slug_url_kwarg = 'slug'
    form_class = RecipeForm

    def get_context_data(self, *args, **kwargs):
        context = super(RecipeEditView, self).get_context_data()
        recipe = self.object
        print(recipe.name)
        recipe.ingredients = recipe.ingredients_list.split('\n')
        recipe.categories_list = ""
        categories = Category.objects.filter(recipe=recipe)
        for category in categories:
            if category != categories[-1]:
                recipe.categories_list += (category + ", ")
            else:
                recipe.categories_list += category

        recipe_edit_form = RecipeForm(initial={'name': recipe.name, 'ingredients_list': recipe.ingredients,
                                               'directions': recipe.directions, 'prep_time': recipe.prep_time,
                                               'cook_time': recipe.cook_time, 'servings': recipe.servings,
                                               'source': recipe.source, 'category_input': recipe.categories_list})
        context['recipe'] = recipe
        context['recipe_edit_form'] = recipe_edit_form

        return context

models.py:模型.py:

class Recipe(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100, default="")
    ingredients_list = models.TextField(default="")
    servings = models.IntegerField(default=0, null=True, blank=True)
    prep_time = models.IntegerField(default=0, null=True, blank=True)
    cook_time = models.IntegerField(default=0, null=True, blank=True)
    directions = models.TextField(default="")
    source = models.CharField(max_length=100, default="", null=True, blank=True)
    categories = models.ManyToManyField(Category, blank=True)
    slug = models.CharField(max_length=200, default="")

    def __str__(self):
        return self.name

urls.py网址.py

# ex: /Recipes/Grilled_Chicken/
    path('Recipes/<slug>/', views.RecipeDetailView.as_view(), name='view_recipe'),
    path('Recipes/<path:slug>/', views.RecipeDetailView.as_view(), name='view_recipe'),
    # ex: /Recipes/edit/Steak/
    path('Recipes/edit/<slug>/', views.RecipeEditView.as_view(), name='edit_recipe'),
    path('Recipes/edit/<path:slug>/', views.RecipeEditView.as_view(), name='edit_recipe'),

link in recipe_detail.html: recipe_detail.html 中的链接:

<a href="{% url 'RecipeBook:edit_recipe' recipe.slug %}" style="float: right">Edit Recipe</a>

I've been going nuts trying to figure it out.我一直在发疯想弄清楚。 By everything that I have in here, the recipe that I'm pulling up in the detailView should be able to be passed to the editView, but every time I try to open up the edit_recipe page, it keeps telling me that it can't find the recipe specified.根据我在这里的所有内容,我在 detailView 中提取的配方应该能够传递给 editView,但是每次我尝试打开 edit_recipe 页面时,它一直告诉我它不能找到指定的配方。 The URL that it generates shows the proper slug and link that it should though.它生成的 URL 显示了正确的 slug 和它应该的链接。 I don't know what I'm missing at this point...我不知道在这一点上我错过了什么......

试试这个方法:

<a href="{% url 'RecipeBook:edit_recipe' recipe_view.slug %}" style="float: right">Edit Recipe</a>

I ended up having to go back through and change the view to be a DetailView.我最终不得不返回并将视图更改为 DetailView。 That was the only way I could get the recipe instance to be pushed through.这是我可以让配方实例被推送的唯一方法。 There's something very specific about using an update view with models that isn't very clear...关于对模型使用更新视图的一些非常具体的东西不是很清楚......

Once I changed to a DetailView, the page would populate with the form initialized to the recipe values.一旦我更改为 DetailView,页面将填充初始化为配方值的表单。 I could then make tweaks to make sure everything worked from there.然后我可以进行调整以确保一切正常。

Thanks for those who responded, it at least got my brain working in a different direction to get this figured out.感谢那些回应的人,它至少让我的大脑朝着不同的方向工作以解决这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM