Django: How to render non-Boolean database rows as checkboxes? - django

My model:
class LineItems(models.Model):
descr = models.CharField(max_length=100)
cost = models.DecimalField(max_digits=5, decimal_places=2)
My form:
class LineItemsForm(forms.ModelForm):
class Meta:
model = LineItems
fields = ['descr', 'cost']
Can someone please tell me either 1) how to render all of the product rows as checkboxes or 2) the proper way to do this if I'm coming at it incorrectly?

Ok, then you should design your model this way:
class Product(models.Model):
description = models.TextField()
cost = models.CharField(max_length=100)
# 'cost' should be a CharField because you would want to save currency name also e.g. €
users dont need a checkbox to buy it, I think, more appropriate way would be just an html button called "put into cart", where users can put items into cart .. and then in cart page, you give users the chance to delete the selected items again. now you think further about next steps..

in the model form you can specify in the meta class
class Meta:
widgets = {
'descr': CheckboxInput()
}
something like that anyway.
CheckboxInput is in django.forms.widgets I believe

Found what I was looking for. In my form:
LINEITEM_CHOICES = [[x.id, x.descr] for x in LineItems.objects.all()]
class LineItemsForm(forms.Form):
food = forms.MultipleChoiceField(choices=LINEITEM_CHOICES,
widget=forms.CheckboxSelectMultiple(), required=False)
In my view:
{% for radio in lineItems.food %}
<div class="food_radios">
{{ radio }}
</div>
{% endfor %}
My code is based off of this post.
Thank you for your answers.

Related

DJANGO Supplement to the data list via an intermediate table

I have an intermediate models connection
Simplified:
class Person(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
etc...
class Company(models.Model):
name = models.CharField(max_length=60)
etc...
class CompanyEnrollment(models.Model):
person = models.ForeignKey(Person, on_delete=models.CASCADE)
company = models.ForeignKey(Company, on_delete=models.CASCADE)
company_position =
models.ForeignKey(CompanyPosition,on_delete=models.CASCADE)
etc...
class Meta:
unique_together = [['person', 'company']]
class CompanyPosition(models.Model):
name = models.CharField(max_length=60)
I want to create the following array:
datas = Person.objects.All(...{All elements of Person model supplemented with CompanyPosition_name}...)
There is a case where a person does not have a company_name association
Is it possible to solve this with a query?
If you have an explicit through model for your many-to-many relationship, you could use this to only get or exclude based on the entries of this table, using an Exists clause:
enrollments = CompanyEnrollment.objects.filter(person_id=OuterRef('pk'))
enrolled_persons = Person.objects.filter(Exists(enrollments))
unenrolled_persons = Person.objects.filter(~Exists(enrollments))
If you don't have an explicit intermediate table, then it's has been generated by Django directly. You should be able to use it by referring to it with Person.enrollments.through instead of CompanyEnrollment.
Since you did not detailed much the CompanyEnrollment table, I assumed you're in the second case.
This is not the best solution in my opinion, but it works for now, with little data. I think this is a slow solution for a lot of data.
views.py I will compile the two necessary dictionaries
datas = Person.objects.all().order_by('last_name', 'first_name')
companys = CompanyEnrollment.objects.all()
Use Paginator
p = Paginator(Person.objects.all(), 20)
page = request.GET.get('page')
pig = p.get_page(page)
pages = "p" * pig.paginator.num_pages
Render HTML:
context = {
"datas": datas,
"pig": pig,
"pages": pages,
"companys": companys,
}
return render(request, "XY.html", context)
HTML template:
{% for datas in pig %}
{{datas.first_name}} {{datas.last_name}}
{% for company in companys %}
{% if datas == company.person %}
{{company.company.name}} <br>
{% endif %}
{% endfor %}
{% endfor %}
not the most beautiful, but it works ... I would still accept a more elegant solution.

Django filter form appears by default as dropdown; change to checkbox

I have a model defined like below in models.py
class ImageGrab(models.Model):
title = models.CharField(max_length=50)
slug=models.CharField(max_length=200)
age=models.ForeignKey(Age, on_delete=models.CASCADE)
gender=models.ForeignKey(Gender, on_delete=models.CASCADE)
masked=models.ForeignKey(Mask, on_delete=models.CASCADE)
withBackpack=models.ForeignKey(Backpack, on_delete=models.CASCADE)
Filters for which are defined as below in filters.py:
class ImageFilterAge(django_filters.FilterSet):
class Meta:
model = ImageGrab
fields = ['age']
###others similar to this
class ImageFilter(django_filters.FilterSet):
class Meta:
model = ImageGrab
fields = ['age', 'gender', 'masked', 'withBackpack']
The view is like below defined in views.py
def images(request):
imagelist = ImageGrab.objects.all()
imagefilter = ImageFilter(request.GET, queryset=imagelist)
agefilter = ImageFilterAge(request.GET, queryset=imagelist)
genderfilter=ImageFilterGender(request.GET, queryset=imagelist)
maskedfilter= ImageFilterMask(request.GET, queryset=imagelist)
backpackfilter = ImageFilterBackpack(request.GET, queryset=imagelist)
return render(request, 'imglist.html', {'filter': imagefilter,'agefilter': agefilter.form, 'genderfilter':genderfilter.form, 'maskfilter':maskedfilter.form, 'backpackfilter':backpackfilter.form})
My template is like this, in imglist.html
<form method="get" name="search" id="search">
{{ agefilter }} <br>
{{ genderfilter }} <br>
{{ maskfilter }} <br>
{{ backpackfilter }} <br>
</form>
This is rendered by default as dropdown select form as given in image link below. I want to change this to say checkbox multiple select and/ or radio button for the filters.
Filtering Using Dropdown
How to go about doing this?
Thanks in advance.
I combined the two solutions given by both users above, and got the solution thus:
Filters.py:
age = ModelMultipleChoiceFilter(queryset=Age.objects.all(),widget=forms.CheckboxSelectMultiple())
Models.py
class Age(models.Model):
ageChoices=(
('Child', 'Child'),
('Adult', 'Adult'),
('Old', 'Old'),
)
age = models.CharField(max_length=5, choices=ageChoices)
What is good is that the filters seem to wok neatly on the data set as well.
Thanks to users Abdul Aziz Barkat & Vosem
Seeing how your models are set up you might want to create a django custom form on which you specify the fields and the input method for each field.
Although you also might want to rethink using Foreign Keys for something as simple as age, gender or withBackpack. You probably want to use other kinds of fields for those, like IntegerField or BooleanField
You can customize the filter generation by specifying filter_overrides in the filter sets Meta. So for your use you can do something like below to set CheckboxInput as the widget to be used:
from django import forms
from django.db import models
class ImageFilterAge(django_filters.FilterSet):
class Meta:
model = ImageGrab
fields = ['age']
filter_overrides = {
models.ForeignKey: {
'filter_class': django_filters.ModelChoiceFilter,
'extra': lambda f: {
'widget': forms.CheckboxInput,
},
},
}
You can also explicitly define the filter field to be able to specify it's widget:
from django import forms
class ImageFilterAge(django_filters.FilterSet):
age = django_filters.ModelChoiceFilter(queryset=Age.objects.all(), widget=forms.CheckboxInput)
class Meta:
model = ImageGrab
fields = ['age']

Can I have data from different fields of a model returned as separate HTML elements? (Django 2.1)

I am compiling a database of articles and have my model set up like this:
class articles(models.Model):
ArticleID = models.IntegerField(primary_key=True)
Title = models.CharField(max_length=500)
Author = models.CharField(max_length=200, null=True)
Journal = models.CharField(max_length=500, null=True)
Date = models.IntegerField(null=True)
Issue = models.IntegerField(null=True)
Link = models.URLField(max_length=800, null=True)
Content = models.TextField()
class Meta:
db_table = 'TEST'
def __str__(self):
return f'{self.Title}, {self.Author}, {self.Journal},{self.Date}, {self.Issue}, {self.Content}'
def get_absolute_url(self):
return reverse('article-detail', args=[str(self.ArticleID)])
The idea is pretty simple. Each meta data type (i.e. title, author) is it's own field, and the actual content of the article is in the field Content.
My view for this model:
def article_detail(request, ArticleID):
ArticleID = get_object_or_404(articles, ArticleID=ArticleID)
context = {'ArticleID': ArticleID}
return render(request, 'article_detail.html', context)
The HTML template for the view:
{% extends 'base.html' %}
{% block content %}
<div class="container">
{{ ArticleID }}
</div>
{% endblock %}
The data displayed in on the HTML page is one big block of text in one single HTML element. How can I make it so that I can use CSS to target each individual field from the model? Must I make separate models for each field (and bound them with foreign keys)?
No of course not. You can access fields with normal dot notation: ArticleID.Title, ArticleID.Author, etc.
(But you shouldn't call your context variable ArticleID; it's the whole article, not the ID. Also, Python style is to use lower_case_with_underscore for variables and attribute names.)
There is already a primary key in for every model which is called id, you don't have to explicitly declare that.
Secondly you are getting an article object with get_object_or_404 so if you use . (dot) notation you will get your desired value in your template.
Something like-
<h2>{{article.Title}}</h2>
<p>{{article.Content}}</p>
though you have to send article names instead of ArticleID in context variable.
In addition to Mr. Daniel Roseman's comment you should use class name Article instead of articles which is not pythonic.

Getting values correctly while using Many to Many relation

I have standart User model and Categories model like this;
class Categories(models.Model):
name=models.CharField(max_length=100)
def __str__(self):
return self.name
And here is another class for relation which associates some users with some categories;
class Interested(models.Model):
user = models.ManyToManyField(User)
category = models.ManyToManyField(Categories)
For example if I have Users such as Bob, Eric, Oliver, Michael
and categories such as Basketball, Football
and relations like that
Bob -> Basketball,Football
Eric-> Basketball
Oliver -> Football
(michael not interested in anything)
I want to get list of who interested in what? How can I handle this? Thank you for your help.
You can get the instance of Interested for a user with:
interested = Interested.objects.get(user="your user")
and list the linked categorys by:
interested.category.all()
But I would, if not nescessary for any other reason, just link the category directly to the user....
class Category(models.Model):
name = models.Charfield()
user = models.ManyToManyField(user)
This way you can get the categorys for a user:
categorys = Category.objects.filter(user="youruser")
and if you pass this to your template just do:
{% for category in categorys %} {{ category.name }}{% endfor %}
To get the users interested in a category, just get the Category instance with:
category = Category.objects.get(name="categoryname")
and the the related user models with:
usersincategory = category.user.all()
if you want this for all categorys just use a normal for loop:
categorys = Category.objects.all()
for category in categorys:
category.user.all()

Display objects from different models at the same page according to their published date

I have three different models for my app. All are working as I expected.
class Tender(models.Model):
title = models.CharField(max_length=256)
description = models.TextField()
department = models.CharField(max_length=50)
address = models.CharField(max_length=50)
nature_of_work = models.CharField(choices=WORK_NATURE, max_length=1)
period_of_completion = models.DateField()
pubdat = models.DateTimeField(default=timezone.now)
class Job(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
title = models.CharField(max_length=256)
qualification = models.CharField(max_length=256)
interview_type = models.CharField(max_length=2, choices=INTERVIEW_TYPE)
type_of_job = models.CharField(max_length=1, choices=JOB_TYPE)
number_of_vacancies = models.IntegerField()
employer = models.CharField(max_length=50)
salary = models.IntegerField()
pubdat = models.DateTimeField(default=timezone.now)
class News(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
title = models.CharField(max_length=150)
body = models.TextField()
pubdat = models.DateTimeField(default=timezone.now)
Now I am displaying each of them at separate page for each of the model (e.g. in the jobs page, I am displaying only the jobs.). But now at the home page, I want to display these according to their published date at the same page. How can I display different objects from different models at the same page? Do I make a separate model e.g. class Post and then use signal to create a new post whenever a new object is created from Tender, or Job, or News? I really hope there is a better way to achieve this. Or do I use multi-table inheritance? Please help me. Thank you.
Update:
I don't want to show each of the model objects separately at the same page. But like feeds of facebook or any other social media. Suppose in fb, any post (be it an image, status, share) are all displayed together within the home page. Likewise in my case, suppose a new Job object was created, and after that a new News object is created. Then, I want to show the News object first, and then the Job object, and so on.
A working solution
There are two working solutions two other answers. Both those involve three queries. And you are querying the entire table with .all(). The results of these queries combined together into a single list. If each of your tables has about 10k records, this is going to put enormous strain on both your wsgi server and your database. Even if each table has only 100 records each, you are needlessly looping 300 times in your view. In short slow response.
An efficient working solution.
Multi table inheritance is definitely the right way to go if you want a solution that is efficient. Your models might look like this:
class Post(models.Model):
title = models.CharField(max_length=256)
description = models.TextField()
pubdat = models.DateTimeField(default=timezone.now, db_index = True)
class Tender(Post):
department = models.CharField(max_length=50)
address = models.CharField(max_length=50)
nature_of_work = models.CharField(choices=WORK_NATURE, max_length=1)
period_of_completion = models.DateField()
class Job(Post):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
qualification = models.CharField(max_length=256)
interview_type = models.CharField(max_length=2, choices=INTERVIEW_TYPE)
type_of_job = models.CharField(max_length=1, choices=JOB_TYPE)
number_of_vacancies = models.IntegerField()
employer = models.CharField(max_length=50)
salary = models.IntegerField()
class News(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
def _get_body(self):
return self.description
body = property(_get_body)
now your query is simply
Post.objects.select_related(
'job','tender','news').all().order_by('-pubdat') # you really should slice
The pubdat field is now indexed (refer the new Post model I posted). That makes the query really fast. There is no iteration through all the records in python.
How do you find out which is which in the template? With something like this.
{% if post.tender %}
{% else %}
{% if post.news %}
{% else %}
{% else %}
Further Optimization
There is some room in your design to normalize the database. For example it's likely that the same company may post multiple jobs or tenders. As such a company model might come in usefull.
An even more efficient solution.
How about one without multi table inheritance or multiple database queries? How about a solution where you could even eliminate the overhead of rendering each individual item?
That comes with the courtesy of redis sorted sets. Each time you save a Post, Job or News, object you add it to a redis sorted set.
from django.db.models.signals import pre_delete, post_save
from django.forms.models import model_to_dict
#receiver(post_save, sender=News)
#receiver(post_save, sender=Post)
#receiver(post_save, sender=Job)
def add_to_redis(sender, instance, **kwargs):
rdb = redis.Redis()
#instead of adding the instance, you can consider adding the
#rendered HTML, that ought to save you a few more CPU cycles.
rdb.zadd(key, instance.pubdat, model_to_dict(instance)
if (rdb.zcard > 100) : # choose a suitable number
rdb.zremrangebyrank(key, 0, 100)
Similarly, you need to add a pre_delete to remove them from redis
The clear advantage of this method is that you don't need any database queries at all and your models continue to be really simple + you get catching thrown in the mix. If you are on twitter your timeline is probably generated through a mechanism similar to this.
The following should do want you need. But to improve performance you can create an extra type field in each of your models so the annotation can be avoided.
Your view will look something like:
from django.db.models import CharField
def home(request):
# annotate a type for each model to be used in the template
tenders = Tender.object.all().annotate(type=Value('tender', CharField()))
jobs = Job.object.all().annotate(type=Value('job', CharField()))
news = News.object.all().annotate(type=Value('news', CharField()))
all_items = list(tenders) + list(jobs) + list(news)
# all items sorted by publication date. Most recent first
all_items_feed = sorted(all_items, key=lambda obj: obj.pubdat)
return render(request, 'home.html', {'all_items_feed': all_items_feed})
In your template, items come in the order they were sorted (by recency), and you can apply the appropriate html and styling for each item by distinguishing with the item type:
# home.html
{% for item in all_items_feed %}
{% if item.type == 'tender' %}
{% comment "html block for tender items" %}{% endcomment %}
{% elif item.type == 'news' %}
{% comment "html block for news items" %}{% endcomment %}
{% else %}
{% comment "html block for job items" %}{% endcomment %}
{% endif %}
{% endfor %}
You may avoid the annotation altogether by using the __class__ attribute of the model objects to distinguish and put them in the appropriate html block.
For a Tender object, item.__class__ will be app_name.models.Tender where app_name is the name of the Django application containing the model.
So without using annotations in your home view, your template will look:
{% for item in all_items_feed %}
{% if item.__class__ == 'app_name.models.Tender' %}
{% elif item.__class__ == 'app_name.models.News' %}
...
{% endif %}
{% endfor %}
With this, you save extra overhead on the annotations or having to modify your models.
A straight forward way is to use chain in combination with sorted:
View
# your_app/views.py
from django.shortcuts import render
from itertools import chain
from models import Tender, Job, News
def feed(request):
object_list = sorted(chain(
Tender.objects.all(),
Job.objects.all(),
News.objects.all()
), key=lambda obj: obj.pubdat)
return render(request, 'feed.html', {'feed': object_list})
Please note - the querysets mentioned above using .all() should be understood as placeholder. As with a lot of entries this could be a performance issue. The example code would evaluate the querysets first and then sort them. Up to some hundreds of records it likely will not have a (measurable) impact on performance - but in a situation with millions/billions of entries it is worth looking at.
To take a slice before sorting use something like:
Tender.objects.all()[:20]
or use a custom Manager for your models to off-load the logic.
class JobManager(models.Manager):
def featured(self):
return self.get_query_set().filter(featured=True)
Then you can use something like:
Job.objects.featured()
Template
If you need additional logic depending the object class, create a simple template tag:
#templatetags/ctype_tags.py
from django import template
register = template.Library()
#register.filter
def ctype(value):
return value.__class__.__name__.lower()
and
#templates/feed.html
{% load ctype_tags %}
<div>
{% for item in feed reversed %}
<p>{{ item|ctype }} - {{ item.title }} - {{ item.pubdat }}</p>
{% endfor %}
</div>
Bonus - combine objects with different field names
Sometimes it can be required to create these kind of feeds with existing/3rd party models. In that case you don't have the same fieldname for all models to sort by.
DATE_FIELD_MAPPING = {
Tender: 'pubdat',
Job: 'publish_date',
News: 'created',
}
def date_key_mapping(obj):
return getattr(obj, DATE_FIELD_MAPPING[type(obj)])
def feed(request):
object_list = sorted(chain(
Tender.objects.all(),
Job.objects.all(),
News.objects.all()
), key=date_key_mapping)
Do I make a separate model e.g. class Post and then use signal to
create a new post whenever a new object is created from Tender, or
Job, or News? I really hope there is a better way to achieve this. Or
do I use multi-table inheritance?
I don't want to show each of the model objects separately at the same
page. But like feeds of facebook or any other social media.
I personally don't see anything wrong using another model, IMHO its even preferable to use another model, specially when there is an app for that.
Why? Because I would never want to rewrite code for something which can be achieved by extending my current code. You are over-engineering this problem, and if not now, you are gonna suffer later.
An alternative solution would be to use Django haystack:
http://haystacksearch.org/
http://django-haystack.readthedocs.io/en/v2.4.1/
It allows you to search through unrelated models. It's more work than the other solutions but it's efficient (1 fast query) and you'll be able to easily filter your listing too.
In your case, you will want to define pubdate in all the search indexes.
I cannot test it right now, but you should create a model like:
class Post(models.Model):
pubdat = models.DateTimeField(default=timezone.now)
tender = models.ForeignKey('Tender')
job = models.ForeignKey('Job')
news = models.ForeignKey('News')
Then, each time a new model is created, you create a Post as well and relate it to the Tender/Job/News. You should relate each post to only one of the three models.
Create a serializer for Post with indented serializers for Tender, Job and News.
Sorry for the short answer. If you think it can work for your problem, i'll write more later.