Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

django - TypeError: 'Post' object is not callable

I'm new to Django and I keep getting this error on my project. I have tried to fix it by examining similar problems, but I keep struggling to find the problem.

Here is the code for models.py file.

class Post(models.Model):
    publisher = models.ForeignKey(User, related_name='posts_published', on_delete=models.CASCADE)

    category = models.ForeignKey(Category, related_name='posts', on_delete=models.CASCADE)
    subject = models.CharField(max_length=200)
    slug = models.SlugField(max_length=200, unique=True)
    overview = models.TextField()
    published = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-published']

    def __str__(self):
        return self.subject


class Module(models.Model):
    post = models.ForeignKey(Post, related_name='modules', on_delete=models.CASCADE)
    subject = models.CharField(max_length=200)
    add_desc = models.TextField(blank=True)
    order = OrderField(blank=True, for_fields=['post'])

    class Meta:
        ordering = ['order']

    def __str__(self):
        return f'{self.order}. {self.subject}'

A snippet from views.py

class PostUpdateViewModel(TemplateResponseMixin, View):
    template_name = 'publications/manage/module/formset.html'
    post = None

    def get_formset(self, data=None):
        return PostsModuleFields(instance=self.post, data=data)

    def dispatch(self, request, pk):
        self.post = get_object_or_404(Post, id=pk, publisher=request.user)
        return super().dispatch(request, pk)

    def get(self, request, *args, **kwargs):
        formset = self.get_formset()
        return self.render_to_response({'post': self.post, 'formset': formset})

    def post(self, request, *args, **kwargs):
        formset = self.get_formset(data=request.POST)
        if formset.is_valid():
            formset.save()
            return redirect('posts_list_merge')
        return self.render_to_response({'post': self.post, 'formset': formset})

My formset.html

{% extends "home.html" %}
    {% block title %}
        Edit "{{ post.subject }}"
    {% endblock %}
{% block content %}
<h1>Edit "{{ post.subject }}"</h1>
<div class="module">
    <h2>Course modules</h2>
    <form method="post">
        {{ formset }}
        {{ formset.management_form }}
        {% csrf_token %}
    <input type="submit" value="Save modules">
    </form>
</div>
{% endblock %}

Full Traceback:

Traceback (most recent call last):
  File "E:FlaminhoeProjectsDIPLOMAckmsVirtualEnvlibsite-packagesdjangocorehandlersexception.py", line 47, in inner
    response = get_response(request)
  File "E:FlaminhoeProjectsDIPLOMAckmsVirtualEnvlibsite-packagesdjangocorehandlersase.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "E:FlaminhoeProjectsDIPLOMAckmsVirtualEnvlibsite-packagesdjangoviewsgenericase.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "E:FlaminhoeProjectsDIPLOMAckmsVirtualEnvckmsProjectpublicationsviews.py", line 61, in dispatch
    return super().dispatch(request, pk)
  File "E:FlaminhoeProjectsDIPLOMAckmsVirtualEnvlibsite-packagesdjangoviewsgenericase.py", line 98, in dispatch
    return handler(request, *args, **kwargs)

Exception Type: TypeError at /post/1/module/
Exception Value: 'Post' object is not callable

Has any one got any ideas why this error is happening?

question from:https://stackoverflow.com/questions/65927835/typeerror-post-object-is-not-callable

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is happening because your object is called post so the class instance has post as an instance of a Post object from your models.

However you're then trying to access the post function after doing a POST request to the view and post is a database object, not a function, so you can't call it.

The easiest fix is to change the object in the view to object, which is consistent with other django views, and feel free to call it post in the template context.

So your view would become something like this;


    class PostUpdateViewModel(TemplateResponseMixin, View):
        template_name = 'publications/manage/module/formset.html'
        object = None
    
        def get_formset(self, data=None):
            return PostsModuleFields(instance=self.object, data=data)
    
        def dispatch(self, request, pk):
            self.object = get_object_or_404(Post, id=pk, publisher=request.user)
            return super().dispatch(request, pk)
    
        def get(self, request, *args, **kwargs):
            formset = self.get_formset()
            return self.render_to_response({'post': self.object, 'formset': formset})
    
        def post(self, request, *args, **kwargs):
            formset = self.get_formset(data=request.POST)
            if formset.is_valid():
                formset.save()
                return redirect('posts_list_merge')
            return self.render_to_response({'post': self.object, 'formset': formset})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...