20

我正在尝试在基于类的视图 CreateView 中访问 ForeignKey。我希望能够从 ForeignKeys 动态设置 CBV 中的初始值,并从 ForeignKeys 动态设置模板链接。

这两个问题(1.初始值,2.模板链接)可以用类似的方法解决,也可以用不同的方法解决……我还在学习中。也许第一个问题可以在里面解决views.py,第二个问题可以用模板语法解决ingredient_form.html

我已经看到关于 SO 设置初始值的问题来自用户(self.request.user),但不仅仅是来自models.py.

我正在浏览django-by-errors,并尝试添加额外的功能来扩展我的 django 知识。

我的问题特别集中在views.py:IngredientAddView(CreateView)、 on ingredient_form.html和 on urls.py:'recipe-detail'& 'ingredient-add'。

当我查看 时'recipe-detail',我可以单击指向 的链接'ingredient-add'。我想'ingredient-add'“知道”哪个配方点击了它,并且能够将此配方设置为初始值(我的尝试views.py:IngredientAddView:get_initials(self)不起作用),并且还能够链接回这个配方(我的尝试ingredient_form.html:{% comment %}不起作用)。

将不胜感激任何帮助。

模型.py

class Food(models.Model):
    name=models.CharField(max_length=20,unique=True)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('food-detail',kwargs={'pk':self.pk})

class Recipe(models.Model):
    title=models.CharField(max_length=80,unique=True)
    slug=models.SlugField(max_length=80,unique=True)
    description=models.TextField(blank=True)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('recipe-detail',kwargs={'slug':self.slug})

class Ingredient(models.Model):
    recipe=models.ForeignKey(Recipe)
    food=models.ForeignKey(Food)

    def __str__(self):
        return '%s (%s)' % (self.food, self.recipe)

视图.py

class FoodListView(ListView):
    model=Food

class FoodDetailView(DetailView):
    model=Food

class FoodCreateView(CreateView):
    model=Food

class RecipeListView(ListView):
    model=Recipe

class RecipeDetailView(DetailView):
    model=Recipe

class RecipeCreateView(CreateView):
    model=Recipe

class RecipeUpdateView(UpdateView):
    model=Recipe

class IngredientAddView(CreateView):
    model=Ingredient

#    def get_context_data(self,**kwargs):
#        context=super(IngredientAddView,self).get_context_data(**kwargs)
#        context['foreign']=self.request.session.get('slug')

    def get_initials(self):
        return {
            'recipe':self.request.session.get('recipe')
        }

网址.py

from .views import FoodListView, FoodDetailView, FoodCreateView, RecipeListView, RecipeDetailView, RecipeCreateView, RecipeUpdateView, IngredientAddView

urlpatterns=patterns('',
                     url(r'^$',RecipeListView.as_view(),name='recipe-list'),
                     url(r'^(?P<slug>[-\w]+)$',RecipeDetailView.as_view(),name='recipe-detail'),
                     url(r'^(?P<slug>[-\w]+)/edit$',RecipeUpdateView.as_view(),name='recipe-edit'),
                     url(r'^(?P<slug>[-\w]+)/add_ingredient/$',IngredientAddView.as_view(),name='ingredient-add'),
                     url(r'^new/$',RecipeCreateView.as_view(),name='recipe-create'),
                     url(r'^food/$',FoodListView.as_view(),name='food-list'),
                     url(r'^food/(?P<pk>[\d]+)$',FoodDetailView.as_view(),name='food-detail'),
                     url(r'^food/create/$',FoodCreateView.as_view(),name='food-create'),
                 )

recipe_detail.html

{% extends "base_food.html" %}

{% block title %}{{ recipe }} {% endblock %}

{% block content %}
  <h1>{{ recipe }}</h1>
  <p>{{ recipe.id }}</p>
  <p>{{ recipe.title }}</p>

  <br>
    <h2>Description</h2>
  <p>{{ recipe.description|default:'No description' }}</p>

  <h2>Ingredients</h2>
  <ul>
    {% for ingredient in recipe.ingredient_set.all %}
      <li>{{ ingredient }}</li>
  {% endfor %}
  </ul>
  <p><a href="{% url 'ingredient-add' recipe.slug %}">Add ingredient</a></p>
  <p><a href="{% url 'recipe-edit' recipe.slug %}">Edit recipe</a></p>
  <p><a href="{% url 'recipe-list' %}">Back to recipe list</a></p>
{% endblock %}

成分表.html

{% extends "base_food.html" %}

{% block title %}Add Ingredient{% endblock %}

{% block content %}
  <h1>Add Ingredient</h1>
  <form method="POST">{% csrf_token %}
    {{ form }}
    <button type="submit" class="btn btn-primary">Save</button>
  </form>

{%comment%}  <p><a href="{% url 'recipe-detail' recipe.slug %}">Back to detail</a></p> {%endcomment%}
  <p><a href="{% url 'recipe-list' %}">Back to recipe list</a></p>
{% endblock %}
4

1 回答 1

43

您需要实例化您的配方:

class IngredientAddView(CreateView):
    model=Ingredient

    def get_initial(self):
        recipe = get_object_or_404(Recipe, slug=self.kwargs.get('slug'))
        return {
            'recipe':recipe,
        }
于 2013-08-16T20:22:47.903 回答