i am unable to pass data from view.py to html templates django - django

My name is arslan chaudhry, currently i am working with django. In my django project i have made some filters to filter the product category wise.i have successfully display the category of products. But when i click on the category image i recived an empity page no error is dispalyed.
I think data are not passing from view.py to html template.How i can fix this?
the code is given below.
views.py
def collectionsview(request, slug):
if(Category.objects.filter(slug=slug, status=0)):
products=Product.objects.filter(category__slug=slug)
category_name=Category.objects.filter(slug=slug).first()
contex={products:"products",category_name:"category_name"}
print(products)
return render(request, "store/product/index.html", contex)
else:
return HttpResponse('This is not a valid product')
html template
{% extends 'store/layouts/main.html' %}
{% block title %}Home{% endblock title %}
{% block body %}
<div class="container mt-3">
<div class="row">
<div class="col-md-12">
<h4>{{category_name}}</h4>
<div class="row">
{% for item in products %}
<div class="col-md-2">
<div class="card">
<a href="#">
<div class="card-body ">
<div class="card-image">
<img src="{{item.imge.url}}" alt="" width="100%" height="100%">
<h4 class="text-center mt-1" style="font-size: medium; font-weight: 600;">{{item.name}}</h4>
</div>
<span>{{item.original_price}}</span>
<span>{{item.selling_price}}</span>
</div>
</a>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
{% endblock body %}

Related

how to put my form in line orientation (horizontal). django forms

I want to put my form in horizontal.I tried to do this, but it got unformatted and disorganized
MY HTML:
<div class="tab-pane fade container-fluid p-2" id="profile" role="tabpanel"
aria-labelledby="profile-tab">
<h6 class="m-0 font-weight-bold text-primary">Horas Adicionais</h6>
<div class="row mt-4">
<div class="col">
{{ form_funcionarioadicional.management_form }}
{% for fa in form_funcionarioadicional %}
<div class="faform row">
<div class="col">
{{fa}}
</div>
</div>
{% endfor %}
</div>
</div>
</div>
currently it is like this, I wanted to leave it horizontal
How can I fix this in html, or in forms.py?
You can iterate form like this with col class of Bootstrap...
views.py
def Demoview(request):
form = DemoForm()
context = {'form':form}
return render(request,'index.html',context)
form.py
class DemoForm(forms.ModelForm):
class Meta:
model = DemoClass
fields = "__all__"
widgets = {
'field1':forms.TextInput(attrs={'class':'form-control','placeholder':'Field1'}),
'field2':forms.NumberInput(attrs={'class':'form-control','placeholder':'Field2'}),
'field3':forms.EmailInput(attrs={'class':'form-control','placeholder':'Field3'}),
'field4':forms.TextInput(attrs={'class':'form-control','placeholder':'Field4'}),
}
HTML Code
{% block body %}
<div class="container-fluid">
<div class="row">
{% for fm in form %}
<div class="col-6">
<label >{{fm.label}}</label>
{{fm}}
</div>
{% endfor %}
</div>
</div>
{% endblock body %}
Output

Turbo-flask turbo.push when button is submitted

I am using WTForms and turbo-flask
I have a template which I want to change
<div>
{% if data is defined %}
{% for item in data %}
<div id="load" class="col-12 col-sm-6 offset-md-0 col-md-6 col-lg-4 col-xl-3 p-1 p-md-2">
<div class="card rounded p-1 d-flex flex-column h-100">
<div class="card-body p-1">
<h5 class="card-title">{{item._source.judgment_name}}</h5>
<h6 class="card-subtitle mb-2 text-muted">{{item._source.justice_kind_name}}</h6>
<p class="card-text">{{item._source.court_name}}</p>
<p class="card-text">{{item._source.adjudication_date}}</p>
{{item._id}}
{{item._source.cause_num}}
</div>
</div>
</div>
{% endfor %}
{% endif %}
</div>
And where I include it
<div class="container">
<div class="row px-2 pt-0">
{% include "test.html" %}
</div>
</div>
#app.route('/', methods=['GET', 'POST'])
def main():
form = SearchForm()
if form.is_submitted():
resp = es.search(index="test", query={"match_all": {}})
data = resp['hits']['hits']
turbo.push(turbo.replace(render_template("test.html", data=data), 'load'))
else:
return render_template('home.html', form=form)
When I use this script it doesn't want to work. Do you have any idea how to fix it?
I solved this. Here working code
in app.route function
if turbo.can_stream():
return turbo.stream(
turbo.replace(render_template('doc_cards.html', data=data), target='load_cards'))
else:
return render_template('home.html', form=search_form, data=data)
On page where content will be updated
<div class="container">
{% with data=data %}
{% include "doc_cards.html"%}
{% endwith %}
</div>
and dynamic content
<div id="load_cards" class="container">
{% if data is defined %}
{% for item in data %}
.......
{% endfor %}
{% endif %}
</div>

How to work with nested if else in django templates?

Here, In this project I'm building a Ecommerce website and I'm using Django. So, here I want to show that if there is no product of category Electric, "Sorry, No Product is Available Right Now !!!" will be shown. where n is the number of product which is sent to this template from app views.
But I'm not getting "Sorry, No Product is Available Right Now !!!" as I've no product of Electric category in my database. How to fix this? where I'm doing wrong?
views.py
def electric(request):
product = Product.objects.all()
n = len(product)
params = {'product': product, 'range':range(1,n), 'n':n}
return render(request,'electric.html',params)
electric.html
{% if n is 0 %}
<div class="p-3 mb-1 bg-warning text-white text-center my-0">
<h1><b>Sorry, No Product is Available Right Now !!! </b></h1>
</div>
{% else %}
<div class="album py-2 bg-gradient">
<div class="container">
<div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3">
{% for i in product %}
{% if i.category == "Electric" %}
<div class="col">
<div class="card shadow-sm">
<img src="{{i.image}}" />
<div class="card-body">
<h4 class="card-title">{{ i.product_name}}</h4>
<h6 class="card-subtitle mb-2 text-muted">
Category: {{i.category}}
</h6>
<p class="card-text">{{i.description}}</p>
<div class="buy d-flex justify-content-between align-items-center">
<div class="price text-success">
<h5 class="mt-4">Price: {{i.price}} BDT</h5>
</div>
<i class="fas fa-shopping-cart"></i> Add to Cart
</div>
</div>
</div>
</div>
{% endif %}
{% endfor %}
</div>
</div>
</div>
{% endif %}
views.py
def electric(request):
product = Product.objects.all()
return render(request,'electric.html',{'product': product})
electric.html
{% if product.count > 0 %}
-- your code --
{% else %}
<div class="p-3 mb-1 bg-warning text-white text-center my-0">
<h1><b>Sorry, No Product is Available Right Now !!! </b></h1>
</div>
{% endif %}
Update your code as above. It will work.

Using Instagram API to make users populate images into my Django application directly from Instagram Pictures

My use case or what I want to do is:
Users click a Upload button,
it authenticates user,
its shows Instagram images,
users select, and
user click upload button to upload images or videos (media) from
Instagram directly into my django app.
What I have done is:
Instagram integration:
pip install python-instagram
views.py:
#login_required()
def instagram_pictures(request, template='dashboard/add-instagram-pictures.html'):
user = request.user
gallery = []
gallery = Gallery.objects.filter(service_provider=user.service_provider_profile)
context = {'gallery': gallery}
return render(request, template, context)
#login_required()
def add_instagram_pictures(request, template='dashboard/add-instagram-pictures.html'):
access_token = "YOUR_ACCESS_TOKEN" # Dont know how this gets factored in for any user
client_secret = settings.SECRET_ID
api = InstagramAPI(access_token=access_token, client_secret=client_secret)
recent_media, next_ = api.user_recent_media(user_id="userid", count=10)
for media in recent_media:
print(media.caption.text)
template/my-gallery.html:
{% extends 'base.html' %}
{% load static %}
{% block title %}My Dashboard{% endblock %}
{% block content %}
<div class="page-header" style="background: url({% static 'img/banner1.jpg' %});">
<div class="container">
<div class="row">
<div class="col-md-12">
<h1 class="page-title">My Gallery</h1>
</div>
</div>
</div>
</div>
<div id="content">
<div class="container">
<div class="row">
{% include '_side_menu.html' %}
<div class="col-md-8 page-content">
<div class="inner-box text-center">
<a href="{% url 'dashboard:add-instagram-pictures' %}" class="btn btn-md btn-success">
<span class="fa fa-plus-circle"> Upload from Instagram</span>
</a>
<ul>
<!-- I will re-write this loop to redefine how images are rendered for the project. Maybe in Carousels-->
{% for p in photos %}
<li>{{ p.name }}</li>
{% endfor %}
</ul>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
template/add-instagram-pictures.html:
{% extends 'base.html' %}
{% load static %}
{% block title %}Add Gallery{% endblock %}
{% block content %}
<div class="page-header" style="background: url({% static 'img/banner1.jpg' %});">
<div class="container">
<div class="row">
<div class="col-md-12">
<h1 class="page-title">Add Instagram Pictures</h1>
</div>
</div>
</div>
</div>
<div id="content">
<div class="container">
<div class="row">
{% include '_side_menu.html' %}
<div class="col-md-8 page-content">
<div class="inner-box text-center">
<a href="{% url 'dashboard:my-gallery' %}" class="btn btn-md btn-success">
<span class="fa fa-chevron-circle-left"> Back to Album List</span>
</a>
</div>
</div>
</div>
</div>
</div> {% endblock %}Add
url.py:
from django.conf.urls import url, include
from dashboard.views import dashboard, my_services, add_service, my_gallery, add_gallery, bank_profile, add_bank_profile, add_instagram_pictures
def ajax_photo_upload_view(args):
pass
urlpatterns = [
url(r'^$', dashboard, {}, name='home'),
url(r'^bank-profile/$', bank_profile, {}, name='bank-profile'),
url(r'^add-bank-profile/$', add_bank_profile, name='add-bank-profile'),
url(r'^my-services/$', my_services, name='my-services'),
url(r'^add-service/$', add_service, name='add-service'),
url(r'^add-gallery/$', add_gallery, name='add-gallery'),
url(r'^my-gallery/$', my_gallery, name='my-gallery'),
url(r'^add-gallery/$', add_instagram_pictures, name='add-instagram-pictures'),
]
settings.py:
# instagram settings
CLIENT_ID = "XXXXXXXXXXXXXXXXXXXX"
SECRET_ID = "XXXXXXXXXXXXXXXXXXXX"
How do I go about my use case as I have stated, my solution is in no way closer to what I want to do.

django class page view not rendering template code

I wanted to use class based views and went through the django documentation and I get noerror messages but wind up with an empty template. I had it working with the non-classed based views. How do I reformat the code so that it renders the template? The template consists of a title, some headings, a navigational menu, flags for selecting instructions in different languages,
followed by a form which shows a flag, policy name char field, and a check box control. I think the initial = {'key': 'value'} in the view forms incorrect but I don't know what to replace it with. Thanks in advance.
forms.py
from django import forms
from policytracker.models import Flag, Label_Links
class PolicyStartForm( forms.Form ):
flags = Flag.objects.all()
policy = Label_Links.objects.all().filter(iso_language='en')[0]
frm_policy1_name=[]
for flag in flags:
frm_policy1_name.append(forms.CharField(max_length=40))
policy_dict = { 'new_policy_link' :policy.nav_section_new_policy_link,
'new_policy_label' :policy.nav_section_new_policy_label,
'graphs_link':policy.nav_section_graphs_link,
'graphs_label' :policy.nav_section_graphs_label,
'account_link' :policy.nav_section_account_link,
'account_label' :policy.nav_section_account_label,
'policy_list_link':policy.nav_section_list_policies_link,
'policy_list_label':policy.nav_section_list_policies_label,
'login_link' :policy.nav_section_login_link,
'login_label' :policy.nav_section_login_label,
'new_policy1_heading' :policy.new_policy1_heading,
'new_policy1_title_label':policy.new_policy1_title_label,
'policy_needs_translation_label':policy.new_policy1_needs_trans_label,
'policy1_submit_label': policy.new_policy1_submit_button_label,
'policy1_tip_msg' :policy.new_policy1_tip_msg,
't_logged_in' :True,
'frm_policy_name' :frm_policy1_name,
't_flags' :flags }
</code>
<code>
views.py
# coding=utf-8
from django.shortcuts import render
from django.http import HttpResponseRedirect
from policytracker.forms import LoginForm, PolicyStartForm
from policytracker.models import Flag, Label_Links
from django.views import View
class PolicyStartView(View):
template_name = 'policystart.html'
initial = {'key': 'value'}
form_class = PolicyStartForm
def get(self, request, *args, **kwargs):
form = self.form_class(initial=self.initial)
return render(request, self.template_name, {'form': form})
</code>
<code>
policystart.html
{% extends "policy-base.html" %}
{% block navsection %}
<div class="container top">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<h1 class="text-center">{{ new_policy1_heading }}</h1>
</div>
</div>
{% if t_policy_details %}
<div class="row">
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
<h4 class="text-nowrap text-left" id="week_start">2017-02-11</h4></div>
<div class="col-md-4 col-xs-4">
<h4 class="text-center" id="week_number">Week 1</h4></div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
<h4 class="text-nowrap text-right" id="week_end">2016-09-18</h4></div>
</div>
{% endif %}
<div class="row">
<div class="col-md-12">
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header"><a class="navbar-brand hidden navbar-link" href="#"> Policies</a>
<button class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navcol-1"><span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button>
</div>
<div class="collapse navbar-collapse" id="navcol-1">
<ul class="nav navbar-nav navbar-right">
<li class="hidden" role="presentation">{{ new_policy_label }}</li>
<li {% if not t_logged_in %} class="hidden" {% endif %} role="presentation">{{ graphs_label }}</li>
<li {% if not t_logged_in %} class="hidden" {% endif %} role="presentation">{{ account_label }}</li>
<li role="presentation">{{ policy_list_label }}</li>
{% if not t_logged_in %} <li role="presentation">{{ login_label }}</li> {% endif %}
</ul>
</div>
</div>
</nav>
</div>
</div>
{% include "pol-new1-lang.html" %}
</div>
<div class="container middle-container">
<div class="row">
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-3">
<p> </p>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-8">
<h4>{{ new_policy1_title_label }}</h4>
</div>
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1">
<h4 class="text-center">{{ policy_needs_translation_label }}</h4>
</div>
</div>
<form method="POST">
{% csrf_token %}
{% load static %}
{% for f in t_flags %}
<div class="row flag">
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-2"><img src="{% static f.flag_image_filename %}"></div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-9">
<input class="form-control" type="text" name="policytitle">
</div>
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1">
<input class="form-control" type="checkbox" name="needstranslation">
</div>
</div>
{% endfor %}
<div class="row enter">
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-3">
<p> </p>
</div>
<div class="col-lg-9 col-md-9 col-sm-9 col-xs-8">
<button class="btn btn-default" type="submit">{{ policy1_submit_label }}</button>
</div>
</div>
</form>
<div class="row enter">
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-3">
<p> </p>
</div>
<div class="col-lg-9 col-md-9 col-sm-9 col-xs-8">
<p>{{ policy1_tip_msg }}</p>
</div>
</div>
</div>
{% endblock %}
</code>
You're using a load of variables in your template, but you aren't actually sending any of them to the context; the only thing your view passes is form. If you want to use things like new_policy1_heading, policy_needs_translation_label and t_flags you need to define them in your view and send them to the template from there.
Actually, it looks like you've completely misunderstood the jobs of forms and views. All the code you've currently put inside your form actually belongs in the view, and you should use policy_dict as the template context. It doesn't look like you need a form class at all.
Even there, though, you're doing much more work than you need to. There's no need to send all the specific fields of the policy object individually; just send policy and then in the template you can do {{ policy.policy_needs_translation_label }} etc.