[英]Django - How access the value of an instance in views.py
I have this model我有这个 model
class Post(models.Model):
title = models.CharField(max_length=100)
title2 = models.CharField( max_length=100)
content = models.TextField(default=timezone.now)
content2 = models.TextField(default=timezone.now)
post_image = models.ImageField(upload_to='post_pics')
post_image2 = models.ImageField(upload_to='post2_pics')
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
Then I have this simple view function that allows me to access each of its field in my HTML:然后我有这个简单的视图 function,它允许我访问 HTML 中的每个字段:
def home(request):
postings = {
'listings' : Post.objects.all(),
}
return render(request, 'front/front.html', postings)
{% for listings in listings%}
<h1>{{listings.content}}</h1>
{% endfor %}
With this, I'm able to access the content
field for every instance of that model and display it有了这个,我可以访问该 model 的每个实例的content
字段并显示它
My question is how can I access the content
field in my view function and change it.我的问题是如何访问我的视图 function 中的content
字段并进行更改。 The content
field holds a zipcode and I want to use an API to display the city of that zipcode(which I already know how to do) and pass it back to the h1
tag. content
字段包含一个邮政编码,我想使用 API 来显示该邮政编码的城市(我已经知道该怎么做)并将其传递回h1
标签。 Each instance holds a unique zipcode so I need it to apply for each instance.每个实例都有一个唯一的邮政编码,所以我需要它来申请每个实例。 How would I approach this?我将如何处理这个?
the simplest way would be to create another variable(from views) which finds the city for a corresponding zipcode and send it through the context dictionary to the template.最简单的方法是创建另一个变量(来自视图),它为相应的邮政编码找到城市,并将其通过上下文字典发送到模板。 OR Add a model city setting default and Null and later based on the entered pincode you can set value to the city attribute of the model..或添加 model 城市设置默认值和 Null 及更高版本基于输入的密码,您可以将值设置为 model 的城市属性。
If you want to edit the value of the CONTENT to the city name... then,如果您想将 CONTENT 的值编辑为城市名称...那么,
The best way would be to override the save method and set the value there,最好的方法是覆盖保存方法并在那里设置值,
models.py:模型.py:
class Post(models.Model):
...
def save(self, *args, **kwargs):
self.content = API_VALUE_OF_city_name
super(Post, self).save(*args, **kwargs)
if you want to update it from views,如果你想从视图中更新它,
in views.py:在views.py中:
instance_update = Post.objects.filter(id = <pk of Post>).update(content = NEWLY FOUND CITY NAME)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.