返回到相关对象的按钮
Posted
技术标签:
【中文标题】返回到相关对象的按钮【英文标题】:Back button to a related object 【发布时间】:2021-03-30 19:01:47 【问题描述】:我正在构建一个应用程序,我可以在其中添加食谱并将配料添加到这些食谱中。在查看 recipe_details 时,我有一个 add_new_ingredient 按钮。当我使用 new_ingredient_form 时,我希望有 后退按钮 来返回食谱的详细信息。我正在尝试通过配方的 pk 但它不起作用。我怎样才能通过配方的 pk 才能回到以前的视图?
models.py
class Recipe(Timestamp):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True)
title = models.CharField(max_length=100, unique=True)
preparation = models.TextField()
def __str__(self):
return self.title
class Ingredient(Timestamp):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True)
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
amount = models.PositiveSmallIntegerField(blank=True, null=True)
unit = models.ForeignKey('Unit', on_delete=models.SET_NULL, blank=True, null=True)
def __str__(self):
return self.name
views.py
class RecipeView(generic.DetailView):
model = Recipe
context_object_name = 'recipe'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['ingredients_list'] = Ingredient.objects.filter(recipe=self.object.pk)
return context
class AddIngredientView(generic.edit.CreateView):
model = Ingredient
fields = [
'name',
'amount',
'unit'
]
success_url = '/'
template_name = 'recipes/add_ingredient.html'
def dispatch(self, request, *args, **kwargs):
self.recipe = get_object_or_404(Recipe, pk=self.kwargs['pk'])
return super().dispatch(request, *args, **kwargs)
def form_valid(self, form):
form.instance.recipe = self.recipe
return super().form_valid(form)
def get_success_url(self):
if 'add_another' in self.request.POST:
url = reverse_lazy('recipes:add_ingredient', kwargs='pk': self.object.recipe_id)
else:
url = reverse_lazy('recipes:recipe', kwargs='pk': self.object.recipe_id)
return url
add_ingredient.html
% extends "base.html" %
% load crispy_forms_tags %
% block content %
<form method="POST">
% csrf_token %
form|crispy
<button class="btn btn-success" type="submit">Save</button>
<button class="btn btn-success" type="submit" name="add_another">Save and add another</button>
<a href="% url 'recipes:recipe' recipe.pk %", class="btn btn-primary", role="button">Back</a>
</form>
% endblock %
【问题讨论】:
【参考方案1】:您可以通过将request.META.HTTP_REFERER
添加到按钮的 href 属性来转到上一页。
Django request to find previous referrer
【讨论】:
以上是关于返回到相关对象的按钮的主要内容,如果未能解决你的问题,请参考以下文章
UINavigationController的创建和相关设置---学习笔记四