PolarBear10
PolarBear10

Reputation: 2305

Django 'NoneType' object has no attribute 'filter'

The task: To assign a single user to the model at a time.

The Error:

Django 'NoneType' object has no attribute 'filter'

The models.py is

class Post(models.Model):
    post_tag = models.ForeignKey(ProjectUser, related_name="user_tag", blank=True, null=True,on_delete=models.CASCADE)

Where ProjectUser is:

from django.contrib.auth.models import AbstractUser

class ProjectUser(AbstractUser):

    def __str__(self):
        return self.username

The .html code is :

% for post_user in objects %}
<form method='POST' action="{% url 'a_tag' post_user.id %}">
    {% csrf_token %}
    <input type='hidden'>
    {% if post_user.id in assigned_user %}
        <button type='submit'>Cancel</button>
    {% else %}
        <button type='submit'>Start</button>
    {% endif %}
</form>

The urls.py is

path('<int:tag>', views.tag_analyst, name='a_tag'),

The views.py function is <- Filter, add and remove attributes here are causing the errors

def tag_analyst(request, tag):
    post = get_object_or_404(Post, id=tag)

    if request.method == 'POST':
        if post.post_tag.filter(id=request.user.id).exists():
            post.post_tag.remove(request.user)

        else:
            post.post_tag.add(request.user)

    return HttpResponseRedirect(reverse('homepage'))

The views.py class

class View(LoginRequiredMixin, ListView):
    context_object_name = "objects"
    model = Post
    template_name = "page.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['assigned_user'] = self.request.user.user_tag.values_list('id', flat=True)
        return context

Upvotes: 0

Views: 6901

Answers (2)

vijay singh
vijay singh

Reputation: 1

class Question(models.Model):
webregister = models.ForeignKey(Webregister, on_delete=models.CASCADE)
que = models.CharField(max_length=255,null=True, blank=True)

    def __str__(self):
        return str(self.pk)


orgs = Question.objects.filter(webregister=module,que__isnull=True)
orgs.delete()

Upvotes: 0

dirkgroten
dirkgroten

Reputation: 20672

post_tag is a ForeignKey field for Post, so post.post_tag is an object (or None in this case), but not a Manager. So you can't filter().

You can just check if post.post_tag. This will be True if a user is associated, and False (None) if not.

Upvotes: 2

Related Questions