2021年3月31日星期三

Django - Accessing Model Field in class based view

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)  

and this function based view that uses the model:

class PostListView(ListView):      model = Post      template_name = 'front/front.html'      context_object_name = 'listings'      ordering = ['-date_posted']            def get_context_data(self, **kwargs):          check_for_zipcode = #where I want to access the author for the current instance           context = super().get_context_data(**kwargs)          context['zipcodes'] = check_for_zipcode          return context  

All I want to know is how can I access the author field in the class-based view. I can access the author in my HTML like so"

  

With this, I'll get back the author field for every instance of that model.

How would I get the author for the instance in the variable check_for_zipcode? I tried self.author, self.listings.author, etc; but nothing works

https://stackoverflow.com/questions/66897058/django-accessing-model-field-in-class-based-view April 01, 2021 at 08:44AM

没有评论:

发表评论