我尝试实现一个允许用户查找特定广告的查询表单,我在shell中花了一些时间,所以我可以在views.py中编写该函数但是有些错误,因为我没有得到任何结果我的模板。
models.py
from django.db import models
from user.models import User
class Ads(models.Model):
name = models.CharField(max_length=30, unique=True, blank=False) #I added an object called 'apple'
def __str__(self):
return self.name
class Offer(models.Model):
publisher = models.ForeignKey(User)
content = models.TextField()
ads = models.ManyToManyField(Ads)
def __str__(self):
return self.content
forms.py
class SendOfferForm(forms.ModelForm):
courses = forms.ModelChoiceField(queryset=Course.objects.all())
class Meta:
model = Offer
fields = ('ads', 'content')
labels = {
'content': _("write your ads here"),
'ads': _("ads-number"), # TODO the label does'nt show up in the template
}
class QueryForm(forms.ModelForm):
ads = forms.ModelChoiceField(queryset=Course.objects.all(), required=False)
def __init__(self, *args, **kwargs):
super(QueryForm, self).__init__(*args, **kwargs)
self.fields['content'].required = False
class Meta:
model = Offer
fields = ('ads', 'content')
views.py
def search(request):
try:
logged_user = get_logged_user_from_request(request)
except:
pass
if request.method=='GET':
form = QueryForm(request.GET)
results = None
if form.is_valid():
query_content = request.GET.get('id_content')
if query_content:
results = Offer.objects.filter(content__contains=query_content)
else:
form = QueryForm()
return render(request, 'offers/search.html', locals())
模板
<form id="login_form" method='GET' action="{% url "search" %}">
{% csrf_token %}
{{ form.as_p }}
<p>
<input type="submit" value="chercher" />
</p>
</form>
search.html
{% if results %}
{% for result in results %}
<div class="result">
<p>{{ result.content }}</p>
<p>{{ result.cours.name }}</p>
</div>
{% empty %}
<p>No ads, sorry</p> <!--TODO this is always showing up -->
{% endfor %}
{% elif results == None %}
<p>No ads, sorry</p>
{% endif %}
最后,这是我在shell中编写的查询
Offer.objects.filter(content__contains='apple')
[<Offer: a>, <Offer: a>]
那是在这里工作但是
results = Offer.objects.filter(content__contains='apple')
result = result[0]
result
<Offer: a> # the user is called 'a', I was a bit lazy to create a real exemple of user ^^
res.content
'I'm an ads called apple'
res.ads
<django.db.models.fields.related.create_many_related_manager.<locals>.ManyRelatedManager object at 0x7fdf5231deb8>
res.ads.name
print(res.ads.name)
None
通常情况下,当我搜索&#39; apple&#39;时,我可以看到内容。但我的模板中没有任何内容。另外,我可以看到我甚至无法获得广告的名称。根据管理员的说法,它不是无,它是苹果。我负责编写以下代码以保存m2m关系的对象:
if offerform.is_valid():
sent = True
offer = offerform.save(commit=False)
offer.publisher = User.objects.get(id=logged_user.id)
offer.save()
offerform.save_m2m()
答案 0 :(得分:2)
您不应该使用locals()
将上下文返回给模板。在您的情况下,form.is_valid()
可能是False
,results
仍为None
。此外,如果其他人试图阅读您的代码,除非他们通过整个查看方法,否则他们无法弄清楚您的上下文中的内容。