任务:一次将一个用户分配给模型。
错误:
Django'NoneType'对象没有属性'filter'
models.py 是
class Post(models.Model):
post_tag = models.ForeignKey(ProjectUser, related_name="user_tag", blank=True, null=True,on_delete=models.CASCADE)
ProjectUser 所在的位置:
from django.contrib.auth.models import AbstractUser
class ProjectUser(AbstractUser):
def __str__(self):
return self.username
.html 代码是:
% 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>
urls.py 是
path('<int:tag>', views.tag_analyst, name='a_tag'),
views.py 函数的 <- Filter
,add
和remove
属性是导致错误
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'))
views.py类
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
答案 0 :(得分:2)
post_tag
是ForeignKey
的{{1}}字段,因此Post
是对象(在这种情况下为post.post_tag
),但不是{{1 }}。因此,您无法None
。
您只需检查Manager
。如果已关联用户,则为filter()
,否则为if post.post_tag
(True
)。
答案 1 :(得分:0)
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()