[英]Displaying get_context_data in template Django
I am trying to display the get_context_data on the template.我正在尝试在模板上显示 get_context_data。 I have a method on the model class that I need to call from ProfileView which has two different models.我在 model class 上有一个方法,我需要从具有两种不同模型的 ProfileView 调用该方法。 For the Profile View I have Profile Model and for the shippingaddress view I have ShippingAddress Model.对于 Profile View,我有 Profile Model,对于 shippingaddress 视图,我有 ShippingAddress Model。 And these models are from two different app.这些模型来自两个不同的应用程序。 I tried the function below and it does not show any error, but when I tried to call it in the Template, It does not show the method.我尝试了下面的 function 并没有显示任何错误,但是当我尝试在模板中调用它时,它没有显示方法。
Views.py视图.py
class ProfileView(LoginRequiredMixin, DetailView):
model = Profile
template_name = "account/profile.html"
success_url = "/"
def get_context_data(self, *args, **kwargs):
context = super(ProfileView, self).get_context_data(**kwargs)
context['shipping'] = ShippingAddress.objects.filter(user=self.request.user)
return context
Template code模板代码
{{object.get_full_address}}
Models.py模型.py
class ShippingAddress(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
phone_number = PhoneNumberField(null=True, blank=True)
street_address = models.CharField(max_length=300)
province = models.CharField(max_length=300)
city = models.CharField(max_length=50)
country = models.CharField(max_length=50)
zip_code = models.CharField(max_length=10)
def __str__(self):
return str(self.user)
def get_phone_number(self):
return self.phone_number
@property
def get_full_address(self):
return f"{self.street_address}, {self.province}, {self.city}, {self.country}, {self.zip_code}"
object
is the context variable that DetailView
will add to the context. object
是DetailView
将添加到上下文中的上下文变量。 For your view this would be an instance of Profile
.对于您的观点,这将是Profile
的一个实例。 You pass a queryset into the context with the name shipping
so you can loop over that:您将查询集传递到名称为shipping
的上下文中,以便您可以遍历它:
{% for shipping_address in shipping %}
{{ shipping_address.get_full_address }}
{% endfor %}
Note : You need to loop because one user has multiple Shipping Addresses according to your models.注意:您需要循环,因为根据您的模型,一个用户有多个送货地址。
Note : Also you didn't need to override
get_context_data
you could simply have written:注意:您也不需要覆盖get_context_data
您可以简单地编写:{% for shipping_address in request.user.shippingaddress_set %} {{ shipping_address.get_full_address }} {% endfor %}
Where
shippingaddress_set
is the related model name with_set
appended.其中shippingaddress_set
是附加了_set
的相关 model 名称。 You can change that by settingrelated_name
on your foreign key.您可以通过在外键上设置related_name
来更改它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.