I have created a model.py as below
class overallAccountDetail(models.Model):
accountId = models.IntegerField(primary_key=True, unique=False, blank=False,
auto_created=True, null=False,
editable=False)
accountName = models.CharField(max_length=100)
countryName = models.CharField(max_length=100)
marketName = models.CharField(max_length=100)
Alarm_Count = models.CharField(max_length=255,default='',blank=True)
TT_Count = models.CharField ( max_length=255 , default='' , blank=True )
Views.py
def displayAlarmCount(request):
totalAlarmCount=overallAccountDetail.objects.filter(marketName='Market1', accountName= 'Account1').aggregate(Sum('Alarm_Count')).values()
ctx = {
'totalAlarmCount': totalAlarmCount
}
return render_to_response('overallaccountdetail_filter.html', ctx, context_instance=RequestContext(request))
In HTML template
{% block content %}
<form method="get">
{{ filter.form.as_p }}
<button type="submit">Search</button>
</form>
filter.qs.totalAlarmCount<br>
totalAlarmCount
<p><strong>Total Alarm_Count:</strong>{{totalAlarmCount}}</p>
<ul>
{% for overallAccountDetail in filter.qs %}
<li>{{ overallAccountDetail.Alarm_Count }}</li>
{% endfor %}
</ul>
Now the issue is when i am executing the below query in shell, i am getting the sum of all alarm count of Account1 corresponding to Market 1. But when i am displaying same on html .. it is showing nothing. Please advise what's the problem in my code. The below query shows the exact value in shell that i want to present on the webpage
totalAlarmCount=overallAccountDetail.objects.filter(marketName='Market1',
accountName= 'Account1').aggregate(Sum('Alarm_Count')).values()
HI your query returns dict value of decimal like dict_values([Decimal('308617')])
totalAlarmCount=overallAccountDetail.objects.filter(marketName='Market1',
accountName= 'Account1').aggregate(Sum('Alarm_Count')).values()
So you can change your below like that,
sum_count=overallAccountDetail.objects.filter(marketName='Market1',
accountName= 'Account1').aggregate(Sum('Alarm_Count'))
totalAlarmCount = sum_count['Alarm_Count__sum']
return render(request, 'overallaccountdetail_filter', {'totalAlarmCount': totalAlarmCount})
Django promotes the separation of concerns means filtering data should be performed in py file (in your case, same method written above) or in model class. It's still not clear what's filter object in your template from where qs is being fetched? If you can provide that detail then I would be able to help.
Related
In my Django project, I am trying to create a website that streams TV shows. Each show belongs in many categories, hence the use of many to many relations in my model. What I want to do with a certain page on my website is dynamically load a page of shows belonging to a specific category. However, all of my attempts have ended in failure as I am unable to figure out a way on how to access the actual category data from each show.
In views.py
def shows_in_category(request, category_slug):
category = get_object_or_404(Category, slug=category_slug)
showsall = theShow.objects.all()
shows = []
for show in showsall:
print(show.category.name, category.name)
if show.category.name == category.name:
shows.append(show)
print(shows)
return render(request, 'show/show_list_view.html', {'category':category, 'shows': shows})
In models.py
class Category(models.Model):
name = models.CharField(max_length=255, db_index=True)
slug = models.SlugField(max_length=255, unique=True)
class Meta:
verbose_name_plural = 'Categories'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("theshowapp:shows_in_category", args=[self.slug])
class theShow(models.Model):
english_name = models.CharField(max_length=400)
show_type = models.CharField(max_length=200, blank=True)
is_active = models.BooleanField(default=False)
category = models.ManyToManyField(Category)
slug = models.SlugField(max_length=400,unique=True)
class Meta:
verbose_name_plural = 'Shows Series'
def __str__(self):
return self.english_name
In the template (show_list_view.html)
{% for show in shows %}
<script> console.log("I'm trying to get in")</script>
<script> console.log("{{ show.name }} {{show.category.name}}")</script>
<script> console.log("I'm in")</script>
<div class="row">
<div class="col-lg-4 col-md-6 col-sm-6">
<div class="product__item">
<div class="product__item__text">
<ul>
{% for genre in show.category %}
<li>{{ show.category }}</li>
{% endfor %}
</ul>
<h5>{{ show.english_name }}</h5>
</div>
</div>
</div>
</div>
{% endfor %}
Any insight on this matter would be much appreciated.
What you're doing here violates some of the best practices of Django and also isn't using the Django ORM to its full potential. Please replace the lines
showsall = animeShow.objects.all()
shows = []
for show in showsall:
print(show.category.name, category.name)
if show.category.name == category.name:
shows.append(show)
print(shows)
with
shows = animeShow.objects.filter(category__name=category.name)
Also in the template change <li>{{ show.category }}</li> to <li>{{ genre }}</li> since that's the iterating variable.
I read up a bit more on the many to many fields examples in Django's documentation and figured out that I should use this:
shows = animeShow.objects.all().filter(category__name=category)
I have a Django web app which I want to do some basic filtering on. Basically, I have a social media like site where Users register their hobbies. What I want to do is have a filter where Users can choose to see only Male or Female users for now. Whilst I can do this in the Python Shell with the following code:
from mainapp.models import Profile
Users = Profile.objects.all().filter(gender = "Male")
I am having trouble with implementing this in Django. Here is my models.py file:
class Hobby(models.Model):
name = models.CharField(max_length=50, default='')
def __str__(self):
return self.name
class Profile(models.Model):
user = models.OneToOneField(
to=User,
blank=True,
null=True,
on_delete=models.CASCADE
)
gender = models.CharField(max_length=6, default='')
age = models.CharField(max_length=3, default='')
dob = models.CharField(max_length=10, default='')
image = models.ImageField(upload_to='profile_images')
hobbies = models.ManyToManyField(Hobby)
The filter function which is in the Views.py file:
def filter(user):
other_users = Profile.objects.all()
filter_results = other_users.filter(gender = "Male")
context = {
'appname': appname,
'usersresults': filter_results
}
return render(request, 'mainapp/members.html', context)
The Urls part:
path('filter/', views.filter, name='filter'),
And the HTML code:
<ul>
{% for user in usersresults %}
<li>
<a> {{user}}</a>
</li>
{% endfor %}
</ul>
However, this does not work as expected and does not return anything to the display. I am not sure why this is going wrong - any help/advice will be much appreciated.
For my function views I pass a request, and then any kwargs I need after that. I haven't tried the way you have it so just putting that out there in case it's part of the problem. In this case I don't think you need to pass user since it's not a variable in your urls and you aren't using it to filter the query. You also might consider renaming the variables to make it clearer for you in case you also decide to filter for female users:
def filter(request):
template = 'mainapp/members.html'
male_users = Profile.objects.filter(gender="Male")
context = {
'male_users': male_users
}
return render(request, template, context)
And then in the template:
<ul>
{% for male in male_users %}
<li>
<a> {{ male.user }}</a>
</li>
{% endfor %}
</ul>
I'm learning Django after having built some basic apps in Flask. One thing I want to do is show users a list of all posts and whether or not they follow that given post. However, Jinja or Django is throwing some error that I don't quite know how to debug.
Models.py
class User(models.Model):
id = models.AutoField(primary_key=True)
username = models.CharField(unique=True, max_length=120,blank=False)
password = models.CharField(max_length=120, blank=True, null=False)
class Record(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=120, unique=True, blank=True)
followers = models.ManyToManyField(User, through='Follow')
class Follow(models.Model):
id = models.AutoField(primary_key=True)
record = models.ForeignKey(Record)
user = models.ForeignKey(User)
date_followed = models.DateField(null=True, blank=True)
records.html
{% for i in records %}
{% if i.follow.filter(id='1').first() %}
DO SOMETHING
{% endif %}
{% endfor %}
error
TemplateSyntaxError at /records/
Could not parse the remainder: '(id='1').first()' from 'i.follow.filter(id='1').first()'
To test this out when I run the python manage.py shell and execute the following I have no issues:
>>> x = Record.objects.first()
>>> x.followers.filter(id='1').first()
<User: User object>
I had initially prototyped this app using Flask and had the following jinja template and never had an issue:
{% for i in accounts %}
{% if i.follow.filter_by(user_id='1').first() %}
DO SOMETHING
{% endif %}
{% endfor %}
You cannot do that logic in template. You can create a method in Record model that does it for you and you can call it in template
class Record(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=120, unique=True, blank=True)
followers = models.ManyToManyField(User, through='Follow')
def first_follower(self):
if self.follow_set.filter(user_id=1).exists():
return True
return False
and in template:
{% for i in records %}
{% if i.first_follower %}
DO SOMETHING
{% endif %}
{% endfor %}
This is by design https://code.djangoproject.com/ticket/1199
The idea is that a django template should focus on design, for designers, and let the more complex code run in Python, not when the template renders.
So if this is a single instance when you use this check, add it to the view:
def get_context_data(self,*arg,**kwargs):
context = super(MyRecordView,self).get_context_data(*args,**kwargs)
context[has_follow] = self.object.follow.filter_by(user_id='1').exists()
return context
In the template:
{% if has_follow %}
...
{% endif %}
However, if you use this check a lot, you can add it to your model:
def has_follow(self):
return self.follow.filter_by(user_id='1').exists()
And then you can access it in a template, w/o any changes to the view context, since it's a model attribute:
{% if i.has_follow %}
...
{% endif %}
First, I have to say that is this my first application in Django. So my knowledge is still limited.
I have this home page where it shows all the data in my model. The model name is "Asset".
I am trying to have a search field inside the home page.
models.py
class Asset(models.Model):
asset_desc = models.CharField(max_length=120, null=False)
BEIRUT = 'Beirut'
SAIDA = 'Saida'
HALBA = "Halba"
base_choice = ((SAIDA, "Saida"), (BEIRUT, "Beirut"), (HALBA, "Halba"))
asset_base = models.CharField(max_length=120, null=False, choices=base_choice)
created_date = models.DateField(auto_now_add=True)
update_date = models.DateTimeField(auto_now=True)
asset_user = models.CharField(max_length=120, blank=True)
slug = models.SlugField()
def save(self, *args, **kwargs):
self.slug = slugify(self.asset_desc)
super(Asset, self).save(*args, **kwargs)
def __str__(self):
return self.asset_desc
views.py
def search_asset(request):
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
assets = Asset.objects.filter(asset_desc__icontains=q)
context = {'desc': assets}
return render(request, 'home.html', context)
html for the search field:
<form method="GET" class="navbar-form navbar-right">
<input type="text" class="form-control" placeholder="Search..."id="search_box" name="q">
urls.py
url(r'^search/$', "asset.views.search_asset", name="home")
Please any help on why it is not showing the result. I am using Django 1.9.
some corrections:
you dont need null=False for TextField() and CharField(), since they never save Null to database but empty string. so you can remove null=False
the search url name is home which logically not really approriate. it should be changed to search or search_view and then you can refer to it via url tag:
action="{% url 'search' %}"
this is useful if someone should look over your code. "Readability counts" ;)
and finally, put this to your home.html (actually you must already have it)
{% for asset in desc %}
<div>
{{ asset.asset_desc }} <br>
{{ asset.base_choice }} <br>
{{ asset.asset_user }}
</div>
{% endfor %}
I hope, this helps
You have not provided the template or the HTML portion where you list the results. You should consider the name of you context variable, but by following your name, you should list the results like this:
{% for asset in desc %}
<div>
{{ asset }}
</div>
{% endfor %}
Anything else looks correct.
Hope it helps
i know you will say that this question is asked before many times but i havent solved it yet...
models.py
class Doc(UploadModel):
doc_no = models.CharField(max_length=100, verbose_name = "No", blank=True)
date_added = models.DateTimeField(verbose_name="Date", default=datetime.now,
editable=False)
class DocImage(models.Model):
property = models.ForeignKey(Doc, related_name='images')
image = FileBrowseField("Docs", max_length=200,
directory="doc_img/%Y/%m/%d/%H/%M/%S/",
extensions=[".jpg",".tif"], blank=True, null=True)
views.py
def doc_detail(request, dosc_no):
res = Doc.objects.filter(doc_no = dosc_no)
return render_to_response("doc/doc_detail.html", {"result": res})
templates:
{% for i in docimage.property_set.all %}
{{ i.image.url }}
{% endfor %}
i have tried above template but i didnt get any result. so i want to get imageurl adress in DocImage class...
all helps
If you review the foreign key documentation, if you have a relationship like
Doc -> has many DocImages
you need to define your foreign key on the DocImages class like so:
class DocImage(models.Model):
property = models.ForeignKey(Doc, related_name='images')
If you don't set related names, you can access the DocImages from the Doc like:
Doc.docimage_set.all()
Docs on Related Objects
But setting related_name in the property field lets you do
Doc.images.all()
Just make sure whatever you pass to the template in the view context matches what is used in the template, e.g.
# in the view
return render_to_response('mytemplate.html', { 'mydoc' : doc, 'mydocimage' : img }
This can then be used in the template as follows:
# and in your template to get the images attached to the document
{% for i in mydoc.images.all %}
...
{% endfor %}
# or to get the document the image belongs to
{{ mydocimage.property.date_added }}
first you iterate over the result
the images related to a Doc are retrieved by the images property of doc which is generated from the related_name attribute in the ForeignKey
code:
{% for doc in result %}
{% for docimage in doc.images.all %}
{{ docimage.image.url }}
{% endfor %}
{% endfor %}