Django在模板中使用queryset

时间:2018-03-12 19:53:05

标签: django templates

我想检查表(= UserProfileInfo)的字段(= is_seller),如果它有一些值(= 0),则禁用模板的某些部分

这些是我的代码:

models.py:

class UserProfileInfo(models.Model):
  user=models.OneToOneField(User,related_name='profile')
  companyname=models.CharField(blank=True,null=True,max_length=128,verbose_name=_('companyname'))
  phone_regex = RegexValidator(regex=r'^\d{11,11}$', message=_(u"Phone number must be 11 digit."))
  cellphone = models.CharField(validators=[phone_regex], max_length=17,verbose_name=_('cellphone'))
  tel = models.CharField(blank=True,null=True, max_length=17,verbose_name=_('tel'))
  state=models.CharField(,max_length=128,verbose_name=_('state'))
  city=models.CharField(,max_length=128,verbose_name=_('city'))
  address=models.CharField(blank=True,null=True,max_length=264,verbose_name=_('address'))
  is_seller=models.CharField(blank=True,null=True, max_length=2,verbose_name=_('seller'))
  def __str__ (self):
     return self.user.username

  class Meta:
    verbose_name=_('UserProfileInfo')
    verbose_name_plural=_('UserProfileInfos')

view.py:

 def stock(request):
  st_form=StocksForm(None)
  is_seller="0"
  if request.method == "POST":
    st_form =StocksForm(data=request.POST)
    is_seller=UserProfileInfo.objects.filter(user=request.user).values("is_seller")
    print("<<<<<<<<<<<"+str(is_seller))
    if st_form.is_valid():
        instance=st_form.save()
        id_name=(st_form.cleaned_data.get("name"))
        instance.name=StocksName.objects.filter(id=id_name).values("name")[0]['name'] #becouse of autocomplete it was saving the value by its id and i converted to name
        instance.user=request.user
        instance.save()
        messages.success(request,"SUCCESSFUL" ,extra_tags="savestock")

    else:
        messages.error(request, "ERROR!")

else:
    st_form=StocksForm()

return render(request,'BallbearingSite/stock.html',{'stocks_form':st_form,'seller':is_seller})

template.html: 它不起作用,我不知道如何纠正它:

  {% for item in seller %}
   {% if item.is_seller=="0" %}
     <p>show some message</p>
   {% endif %}
  {% endfor %}

1 个答案:

答案 0 :(得分:0)

我认为您尝试将布尔值(item.is_seller)与字符串("0")进行比较。

你应该这样做:

{% if item.is_seller %}

或者:

{% if not item.is_seller %}