从 ForeignKey (non-self.request.user) 在 CreateView 中设置初始值 [英] set initial value in CreateView from ForeignKey (non-self.request.user)

查看:14
本文介绍了从 ForeignKey (non-self.request.user) 在 CreateView 中设置初始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am attempting to access ForeignKeys in Class Based Views CreateView. I would like to be able to dynamically set initial values in CBV from ForeignKeys and also dynamically set template links from ForeignKeys.

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

These two questions (1. initial values, 2. template links) may be solved in similar methods, or perhaps by different methods... I'm still learning. Perhaps the first question can be solved within views.py and the second question can be solved with template syntax in ingredient_form.html?

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

I've seen questions on SO setting initial values from users (self.request.user), but not from just a normal foreign key in models.py.

我正在查看 django-by-errors,并尝试添加额外功能以扩展我的 Django 知识.

I'm going through django-by-errors, and attempting to add extra features to expand my django knowledge.

我的问题特别集中在 views.py:IngredientAddView(CreateView),在ingredient_form.htmlurls.py:'recipe-detail' &'ingredient-add'.

My question specifically centers on views.py:IngredientAddView(CreateView), on ingredient_form.html, and on urls.py:'recipe-detail' & 'ingredient-add'.

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

When I view a 'recipe-detail', I can click a link to 'ingredient-add'. I would like 'ingredient-add' to "know" which recipe clicked to it, and be able to set this recipe as the initial value (my attempt within views.py:IngredientAddView:get_initials(self) does not work), and also be able to link back to this recipe (my attempt within ingredient_form.html:{% comment %} does not work).

希望得到任何帮助.

models.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)

views.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')
        }

urls.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

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 %}

ingredient_form.html

ingredient_form.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 %}

推荐答案

您需要实例化您的配方:

You need to instantiate your recipe:

class IngredientAddView(CreateView):
    model=Ingredient

    def get_initial(self):
        recipe = get_object_or_404(Recipe, slug=self.kwargs.get('slug'))
        return {
            'recipe':recipe,
        }

这篇关于从 ForeignKey (non-self.request.user) 在 CreateView 中设置初始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆