简体   繁体   中英

Django - How access the value of an instance in views.py

I have this 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:

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

My question is how can I access the content field in my view function and change it. 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. 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..

If you want to edit the value of the CONTENT to the city name... then,

The best way would be to override the save method and set the value there,

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

instance_update = Post.objects.filter(id = <pk of Post>).update(content = NEWLY FOUND CITY NAME)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM