In the template:
<h4>
{% if data.wine_one %}
{{ data.wine_one.title }}
{% elif data.news_one %}
{{ data.news_one.title }}
{% endif %}
</h4>
I promise the data.wine_one is exists, because in the views.py I have print out it.
But in the templates it do not shows up the data.wine_one.title, and I use the data.wine_one != None can not judge it too.
EDIT
In the views.py:
def getData():
banner = models.Banner.objects.filter(fk_info=1)
info = models.Info.objects.all().first()
aboutus = models.AboutUs.objects.all().first()
winery = models.Winery.objects.all()[:3]
winery_consult = models.WineryConsult.objects.all()[:4]
data = {
'banner': banner,
'info': info,
'aboutus': aboutus,
'winery': winery,
'winery_consult': winery_consult,
}
return data
def productdetails(request, nid):
data = getData()
wine_one = models.Winery.objects.filter(id=nid).first()
data['wine_one'] = wine_one
print (data['wine_one'].title) # there ouput the "gaoliangjiu"
return render(request, 'article_list_content.html', data)
You've misunderstood how the template context works.
There's no element called data in the template; that's just the local variable you're using in the view to build up the context. In the template, you just reference the keys of that object directly. So it should be:
{% if wine_one %}
{{ wine_one.title }}
{% elif news_one %}
{{ news_one.title }}
{% endif %}
Related
I have a questionnaire, containing many questions with their answers. My main objective is to create a webpage where I can show the details of a questionnaire with the list of rules (question/answer) and in the bottom of the page I want to call the create rule page:
def create_rule_view(request, id, sc_id):
if request.method == "POST":
input = InputForm(request.POST)
answer = AnswerForm(request.POST)
rule = RuleForm(request.POST)
if rule.is_valid() and input.is_valid() and answer.is_valid():
r = rule.save()
i = input.save(commit=False)
a = answer.save(commit=False)
i.rule_id = r
i.save()
a.rule_id = r
a.save()
question = input.cleaned_data["patterns"]
else:
input = InputForm()
answer = AnswerForm()
rule = RuleForm()
return render(request, "rule/create_rule.html", {
'rule': rule,
'input': input,
'answer': answer
})
def detail_scenario(request, id, sc_id):
object = get_object_or_404(Scenario, id=sc_id)
# TODO : add rule in the same view
create_rule_div = create_rule_view(request, id, sc_id)
print("content", create_rule_div)
context = {
'scenario': object,
'create_rule_div': create_rule_div
}
return render(request, "scenario/detail_scenario.html", context)
This is rule_create.html:
{% block content %}
<form method="POST"> {% csrf_token %}
<h2>Create Rule</h2>
{{ rule.name}}
{{ input.patterns }}
{{ answer.text }}
<input type="submit" value="Save Rule"/>
</form>
{% endblock %}
This is detail_senario.html:
{% block content %}
<h2>Scenario {{ scenario.id }}</h2>
<p>Scenario for : {{ scenario.chatbot_id }}</p>
<p>Name: {{ scenario.name }}</p>
<p>Description: {{ scenario.description }}</p>
<p>State: {{ scenario.state }}</p>
{% for rule in scenario.rule_ids.all %}
<li>{{ rule }}</li>
{% endfor %}
<div>{% block rule %}
{{ create_rule_div.content }}{% endblock %}
</div>
{% endblock %}
when I call url of detail_scenario I got an html code in navigator like this:
How can I fix this?
Thanks.
I'm trying to detect if the button is clicked and store the value of a retrieved info in session from def detail.
views.py:
def job_display(request):
job_list = Job.objects.filter(Publication_Status="A").order_by('- Job_Position')
context = {'job_list': job_list}
return render(request, 'frontend/jobs.html', context)
def detail(request, job_id):
jreq = get_object_or_404(Job, pk=job_id)
if request.POST.get(jreq.Job_Position):
request.session['jpos'] = jreq.Job_Position
return HttpResponseRedirect('apply')
return render(request, 'frontend/details.html', {'jreq': jreq})
template:
<h1>{{ jreq.Job_Position }}</h1>
<h2>{{ jreq.Job_Description }}</h2>
{{ jreq.Available_Slots }}
<ul>
{% for req in jreq.job_requirement_set.all %}
<li>{{ req.Job_Requirements }}</li>
{% endfor %}
<p> BLA BLA BLA <p/>
{% for req in jreq.skill_requirement_set.all %}
<li>{{ req.Skill_Requirements }}</li>
{% endfor %}
<input name="form-type " name = {{ jreq.Job_Position }} value={{ jreq.Job_Position }} type="submit"/>
In short, you need to put your <input> into a <form>. Without a form you cannot POST any data.
Sounds like you need to learn how a form works in web development. While it's hard to give you a concrete example, django original document is always your friend: https://docs.djangoproject.com/en/1.8/topics/forms/
I have a condition within a loop in my template like this:
{% for message in message_trash %}
<td><a href="#">
{% if request.session.user_email == message.message_user_reciever.user_email %}
{{ message.message_user_reciever.user_firstName }} {{ message.message_user_reciever.user_lastName }}
{% elif request.session.user_email == message.message_user_sender.user_email %}
{{ message.message_user_sender.user_firstName }} {{ message.message_user_sender.user_lastName }}
{% endif %}
</a><small>Friends</small></td>
{% endfor %}
but i don't know why i get this error when applying the url?
TemplateSyntaxError: Could not parse the remainder: '==message.message_user_reciever.user_email' from 'request.session.user_email==message.message_user_reciever.user_email'
Update:
this is the view and variables that i render to the template:
def trashMessages(request, userId):
if isMessageOwner(request, userId):
user = Users.objects.get(user_id=userId)
message_trash = Messages.objects.filter(Q(message_user_reciever= user, message_sender_type='TRASH') | Q(message_user_sender=user, message_reciever_type='TRASH'))
return render(request, 'navigation_messages.html', {'user': user, 'message_trash': message_trash, 'type': 'trash'})
On testing your code out, I can only replicate your issue is by swapping:
{% if request.session.user_email == message.message_user_reciever.user_email %}
for
{% if request.session.user_email ==message.message_user_reciever.user_email %}
Note the missing space. Is the snippet in your question exactly as it is in your template?
def broadcast_display_and_form(request):
if request.method == 'POST' :
form = PostForm(request.POST)
if form.is_valid():
post = form.cleaned_data['post']
obj = form.save(commit=False)
obj.person = request.user
obj.post = post
obj.save()
readers = User.objects.all()
for x in readers:
read_obj = BroadcastReader(person = x)
read_obj.post = obj
read_obj.save()
return HttpResponseRedirect('/broadcast')
else :
form = PostForm()
posts = BroadcastReader.objects.filter(person = request.user)
return render_to_response('broadcast/index.html', { 'form' : form , 'posts' : posts ,} )
My template
{% extends "base.html" %}
{% load comments %}
{% block content %}
<form action='.' method='POST'>
{{ form.as_p }}
<p>
<input type="submit" value ="send it" /></input>
</p>
</form>
{% get_comment_count for posts.post as comment_count %}
{% render_comment_list for posts.post %}
{% for x in posts %}
<p>
{{ x.post.person }} - {{ x.post.post }}
</p>
{% endfor %}
{% endblock %}
What is posts.post supposed to be? posts is a BroadcastReader QuerySet, and probably doesn't have such an attribute? I'm guessing the comment rendering tags are causing your error? Try removing them, or using posts.0 or similar to debug.
Which "post" do you actually want to display comments for? Your view logic is unclear.
I'm having some trouble using get_absolute_url in a template. It seems to work fine if I just pass in one of my store objects and say {{ store.get_absolute_url }}, but if I have to iterate through a dictionary of stores and then use the get_absolute_url function, it returns nothing. Exactly what I'm doing is below:
class Store(EthicalObject):
type = "Store"
name = models.CharField(max_length=50)
company = models.ForeignKey(Company, verbose_name="Company", null=True, blank=True)
location = models.OneToOneField(Location, verbose_name="Location", null=True, blank=True)
products = models.ManyToManyField('Product', related_name="%(class)s_related", db_table=u'ethicsdb_products_to_stores', blank=True)
companies = models.ManyToManyField('Company', related_name="%(class)s_related", db_table=u'ethicsdb_companies_to_stores', blank=True)
def get_absolute_url(self):
return ('store_details', [str(self.id)])
get_absolute_url = models.permalink(get_absolute_url)
This works:
views.py:
def fetch_sidebar_data(shop_object):
sidebar_modules = {}
if shop_object.content_type.name == 'company':
sidebar_modules['related_stores'] = shop_object.stores.all()
sidebar_modules['related_products'] = shop_object.products.all()
if shop_object.content_type.name == 'store':
sidebar_modules['related_companies'] = shop_object.companies.all()
sidebar_modules['related_products'] = shop_object.products.all()
if shop_object.content_type.name == 'product':
sidebar_modules['related_stores'] = shop_object.stores.all()
sidebar_modules['related_companies'] = shop_object.companies.all()
sidebar_modules['tags'] = shop_object.tags
return sidebar_modules['related_stores'][1]
def company_details(request, company_id):
company = get_object_or_404(Company, id=company_id)
sidebar_modules = fetch_sidebar_data(company)
return render_to_response('company/details.html', {'company': company, 'sidebar_modules': sidebar_modules}, context_instance=RequestContext(request))
template:
{% extends "base-onecol.html" %}
{% block page_div_extra_attr %}class="twocol"{% endblock %}
{% block sidebar_content %}
<div id="sidebar-right">
<h1>{{ sidebar_modules.name }}{{sidebar_modules.get_absolute_url }}</h1>
</div>
{% endblock %}
This doesn't work:
views.py:
def fetch_sidebar_data(shop_object):
sidebar_modules = {}
if shop_object.content_type.name == 'company':
sidebar_modules['related_stores'] = shop_object.stores.all()
sidebar_modules['related_products'] = shop_object.products.all()
if shop_object.content_type.name == 'store':
sidebar_modules['related_companies'] = shop_object.companies.all()
sidebar_modules['related_products'] = shop_object.products.all()
if shop_object.content_type.name == 'product':
sidebar_modules['related_stores'] = shop_object.stores.all()
sidebar_modules['related_companies'] = shop_object.companies.all()
sidebar_modules['tags'] = shop_object.tags
return sidebar_modules
template:
{% extends "base-onecol.html" %}
{% block page_div_extra_attr %}class="twocol"{% endblock %}
{% block sidebar_content %}
<div id="sidebar-right">
{% for module_name,module in sidebar_modules.items %}
{% ifequal module_name "related_stores" %}
<h3>Sold Here</h3>
{% for related_store in module.values %}
{{ related_store.name }}<br/>
{% endfor %}
{% endifequal %}
{% ifequal module_name "related_products" %}
<h3>Buy Local</h3>
{{ module }}<br/>
{% endifequal %}
{% ifequal module_name "related_companies" %}
<h3>
{{ module }}<br/>
{% endifequal %}
{% ifequal module_name "tags" %}
{{ module }}<br/>
{% endifequal %}
{% endfor %}
</div>
{% endblock %}
In the second one, I just get no return from get_absolute_url. I know it's working in other places when I print it out. Is this a Django bug, the inability to use get_absolute_url in a dictionary of dictionaries?
Wow, that was a rather convoluted question.
Your problem is here: {% for related_store in module.values %}
module is a QuerySet. .values is calling the QuerySet method which returns a dictionary containing the field values for each row. A dictionary has no get_absolute_url attribute, and get_absolute_url isn't a field in the model.
Just use {% for related_store in module %} and you'll be dealing with actual model instances rather than dictionaries, which means {{ related_store.get_absolute_url }} will work fine.