this is my views.py
def sms(request):
obj = Sms.objects.all()
return render(request, 'advisory.html', {'sms': obj})
and this is on my html.
{% for i in sms %}
<tr>
<td>{{ i.description }}</td>
<td>{{ i.timestamp }}</td>
</tr>
{% endfor %}
this is the model
class Sms(models.Model):
description = models.CharField(max_length=100, blank=True)
timestamp = models.DateTimeField(auto_now_add=True)
And i don't really know why its not returning any data from my model. please help! thanks
add to you Sms model function like this
def __str__(self):
return self.description
Related
I am using slug to query the model, and render result in HTML.
The code is unable to render actual name of region, it just return None
Model
class Region(models.Model):
name = models.CharField(blank=False, unique=True)
def __str__(self):
return self.name
class Theme(models.Model):
name = models.CharField(blank=False, unique=True)
slug = models.SlugField(default="", null=False)
def __str__(self):
return self.name
class ETF(models.Model):
ticker = models.CharField(max_length=6, blank=False, db_index=True, unique=True)
full_name = models.CharField(max_length=200, blank=False)
# many to many
region = models.ManyToManyField(Region)
theme = models.ManyToManyField(Theme)
views.py
def theme_etf(request, slug): # render ETFs with theme filter
filtered_results = ETF.objects.filter(theme__slug=slug)
return render(request, "etf/list_etf.html", {
"ETFs": filtered_results
})
Part of list_etf.html
{% for ETF in ETFs %}
<tr>
<td>{{ ETF.ticker }}</td>
<td>{{ ETF.full_name }}</td>
<td>{{ ETF.region.name }}</td> # What should I use in this line
</tr>
{% endfor %}
The code is unable to render actual name of region, it just return None
Result
Ticker, Name, Region
ARKF, ARK Fintech Innovation ETF, None
ARKK, ARK Innovation ETF, None
KEJI, Global X China Innovation, None
I would like to have this:
Ticker, Name, Region
ARKF, ARK Fintech Innovation ETF, Global
ARKK, ARK Innovation ETF, Global
KEJI, Global X China Innovation, China
I have the information in the database. I have checked it in admin.
Can an ETF have multiple regions as implied by your database design? If it does not I would suggest you use ForeignKey instead.
You are accessing the region field as if it were a ForeignKey.
In your database design you need to iterate over the objects saved in the ManyToManyField using .all.
{% for ETF in ETFs %}
<tr>
<td>{{ ETF.ticker }}</td>
<td>{{ ETF.full_name }}</td>
<td>{% for region in ETF.region.all %}{{ region.name }}{%endfor%}</td>
</tr>
{% endfor %}
Because you have many-to-many relationship, you cannot simply have single values. So, you have to list values.
{% for ETF in ETFs %}
<tr>
<td>{{ ETF.ticker }}</td>
<td>{{ ETF.full_name }}</td>
<td>
<ol>
{% for region in ETF.region %}
<li>{{region.name}}</li>
{% endfor %}
</ol>
</td>
</tr>
{% endfor %}
My models:
class Sell(models.Model):
item = models.OneToOneField(Buy, related_name='sell', on_delete=models.CASCADE)
date = models.DateField(default=timezone.now)
code = models.ForeignKey(Order, related_name='order', on_delete=models.CASCADE, null=True, blank=True)
class Order(models.Model):
status_choice = (
("W", "Aguardando aprovação do pagamento"),
("A", "Pagamento aprovado - produto em separação"),
)
code = models.CharField(max_length=100)
status = models.CharField(max_length=1, choices=status_choice, default='W')
My views:
def order(request):
orders = Sell.objects.values('code__code', 'date', 'code__status') \
.annotate(total_paid=Sum('total_paid')). \
filter(buyer__username=request.user.username).order_by('-date')
return render(request, 'orders/orders.html',
{'orders': orders})
My template:
{% for order in orders %}
<tr>
<td>{{ order.code__code }}</td>
<td>{{ order.date }}</td>
<td>{{ order.get_code__status_display }}</td>
</tr>
{% endfor %}
The output I was expecting: "Aguardando aprovação do pagamento" but it's not printing this.
Any help to display the full text instead the only word "W"?
Thank you!
You should use a period/full-stop/. to access objects related by a ForeignKey
{% for order in orders %}
<tr>
<td>{{ order.code.code }}</td>
<td>{{ order.date }}</td>
<td>{{ order.code.get_status_display }}</td>
</tr>
{% endfor %}
I am working with my first Django project
**model.py**
class product(models.Model):
product_code = models.CharField(max_length=15, unique=True)
product_name = models.CharField(max_length=100)
class stock_product(models.Model):
product_code = models.CharField(max_length=15)
branch_code = models.CharField(max_length=5)
quantity = models.IntegerField(default=0)
price = models.DecimalField(default=0)
**views.py**
class productList(ListView):
model = product
template_name = 'product/product_list.html'
def get_queryset(self):
queryset = super(productList, self).get_queryset()
self.filterset = productFilter(self.request.GET, queryset=queryset)
return self.filterset.qs
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['filter'] = self.filterset
return context
**product_list.html**
{% for alist in product_list %}
<tr>
<td>{{ alist.product_code }}</td>
<td>{{ alist.product_name }}</td>
<td>{{ alist.price }}</td>
<td>{{ alist.quantity }}</td>
</tr>
{% endfor %}
Sample Data in tables
**product**
['11111','paper'
'22222','Wood']
**stock_product**
['11111','BR1',150, 10
'11111','BR2',120, 10
'11111','BR3',100, 15
'22222','BR1',50, 200
'22222','BR2',70, 200
'22222','BR3',40, 250]
I want to get price and quantity from stock_product model, we can change branch_code by user
how can we do Plese help.
Thanks, But I want display only user branch (if user branch 'BR1' display only 'BR1')
**views.py**
class productList(ListView):
model = product
template_name = 'product/product_list.html'
def get_queryset(self):
queryset = super(productList, self).get_queryset()
self.filterset = productFilter(self.request.GET, queryset=queryset)
return self.filterset.qs
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
stock = stock_product.objects.all(). # this line added
context['filter'] = self.filterset
context['stock'] = stock # this line added
return context
Now having this you can access the stock from your template:
**product_list.html**
{% for alist in product_list %}
<tr>
<td>{{ alist.product_code }}</td>
<td>{{ alist.product_name }}</td>
<td>{{ alist.price }}</td>
<td>{{ alist.quantity }}</td>
</tr>
{% endfor %}
{% for s in stock %}
<tr>
<td>{{ s.product_code }}</td>
<td>{{ s.product_branch }}</td>
</tr>
{% endfor %}
BUT I have to just do not recommend you do this. Why? well, I suppose you want to make the match of the product_code. Except of that you should use ForeignKey on the models and so you will have a much simple code and logic:
Model:
class stock_product(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE) # this
branch_code = models.CharField(max_length=5)
quantity = models.IntegerField(default=0)
price = models.DecimalField(default=0)
And so now without modifying your view you could do this on the template to access the data:
template:
{% for alist in product_list %}
<tr>
<td>{{ alist.product_code }}</td>
<td>{{ alist.product_name }}</td>
<td>{{ alist.stock_product.branch_code }}</td>
<td>{{ alist.stock_product.quantity }}</td>
<td>{{ alist.stock_product.price }}</td>
</tr>
{% endfor %}
how about change the model with using foreign keys.
and use the django_tables2.
# **model.py**
from django.db import models
class product(models.Model):
product_code = models.CharField(max_length=15, unique=True)
product_name = models.CharField(max_length=100)
class stock_product(models.Model):
# product_code = models.CharField(max_length=15)
product = models.ForeignKey(product, on_delete=models.CASCADE)
branch_code = models.CharField(max_length=5)
quantity = models.IntegerField(default=0)
price = models.DecimalField(default=0)
this is table code for django_tables2.
class DetailedDataTable(tables.Table):
product_code = tables.Column(verbose_name='product_code', accessor='product_id')
product_name = tables.Column(verbose_name='product_name', accessor='product_id')
class Meta:
model = stock_product
template_name = "django_tables2/bootstrap.html"
fields = ('product_code', 'product_name', 'branch_code', 'quantity', 'price')
def render_product_code(self,value, record):
return product.objects.get(id=value).product_code
def render_product_name(self,value, record):
return product.objects.get(id=value).product_name
and this is view
def view(request):
template_name = 'template.html'
query_set = stock_product.objects.all()
table = DetailedDataTable(qs)
context={
'table':table,
}
return render(request, template_name, context)
and this is for template page uses.
{# tutorial/templates/tutorial/people.html #}
{% load render_table from django_tables2 %}
<!doctype html>
<html>
<head>
<title>List</title>
</head>
<body>
{% render_table table %}
</body>
</html>
:)
i want to display number of views in a table for a specific post. I already have the data stored in db. it seems that print statement print('count', context['count_view']) is working inside get_context_data method but it is not working as expected in the template. Don't worry about the data inside the image, its actually dummy data. Anyone helpenter image description here
models.py
class ObjectViewed(models.Model):
user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE)
ip_address = models.CharField(max_length=220, blank=True, null=True)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # User, Blog, or any other models
object_id = models.PositiveIntegerField() # User id, Blog id, or any other models id
content_object = GenericForeignKey('content_type', 'object_id')
timestamp = models.DateTimeField(auto_now_add=True)
views.py
class PostListView(ListView):
model = Post
template_name = 'edmin/post/postList.html'
context_object_name = 'posts'
ordering_by = ['-created']
def get_queryset(self):
post=Post.objects.filter(author=self.request.user)
return post
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
post=Post.objects.filter(author=self.request.user)
c_type = ContentType.objects.get_for_model(Post)
for p in post:
context['count_view'] = ObjectViewed.objects.filter(content_type=c_type, object_id=p.id).count()
print('count',context['count_view'])
return context
postList.html
{% for post in posts %}
{% if post.status == 'Draft' %}
{% else %}
<tr>
<th scope="row">{{ forloop.counter }}</th>
<td><a style="color:blue" href="{% url 'edmin:post_detail_view' pk=post.pk %}">{{ post.title }}</a></td>
<td>{{ post.banner_title }}</td>
<td>{{ post.created }}</td>
<td>{{ count_view }}</td>
<td>{{ post.status }}</td>
<td>Edit</td>
<td>Delete</td>
</tr>
{% endif %}
{% endfor %}
Since context allows 'dict', you can pass all of your views through context.
At my work everyone has to plan until they've reached their planning target. To make this easier I'm building a planning tool to plan the activities. All the activities have standard durations which are saved in the PlanningActivity model. Now I want to show a list of all the planned activities with the standard duration and also sum up the total planned time in a week. How can I use strd_duration in my added Planning's? I've tried so much, but nothing seems to work...
models.py
class PlanningActivity(models.Model):
name = models.CharField(max_length=255)
is_billable = models.BooleanField()
is_auto_realised = models.BooleanField()
strd_duration = models.PositiveIntegerField()
def __str__(self):
return self.name
class Planning(models.Model):
added_by = models.ForeignKey(
User, related_name='planning_activity', on_delete=models.DO_NOTHING
)
activity = models.ForeignKey(
PlanningActivity, on_delete=models.DO_NOTHING
)
date = models.DateField()
note = models.CharField(max_length=255)
def __str__(self):
return str(self.id)
views.py
def home(request):
planning_form = PlanningForm(request.POST)
if request.user.is_authenticated:
planning = Planning.objects.filter(added_by=request.user).order_by('-date')
contracts = UserContract.objects.filter(assigned_user=request.user)
else:
planning = ''
contract = ''
if planning_form.is_valid():
new_planning = planning_form.save(commit=False)
new_planning.added_by = request.user
new_planning.save()
return redirect('/')
else:
planning_form = PlanningForm()
return render(request, 'home.html', {'planning_form': planning_form, 'planning':planning, 'contracts':contracts})
home.html
<table class="table table-striped mt-2">
<thead class="thead-light">
<tr>
<td>Activity</td>
<td>Date</td>
<td>Note</td>
<td>Duration</td>
</tr>
</thead>
<tbody>
{% for plan in planning %}
<tr>
<td>{{ plan.activity }}</td>
<td>{{ plan.date }}</td>
<td>{{ plan.note }}</td>
<td>{{ plan.activity_id }}</td> <== HERE I WANT TO SHOW strd_duration
</tr>
{% endfor %}
</tbody>
</table>
You can access the attribute through the foreign key:
{% for plan in planning %}
<tr>
<td>{{ plan.activity }}</td>
<td>{{ plan.date }}</td>
<td>{{ plan.note }}</td>
<td>{{ plan.activity.strd_duration }}</td>
</tr>
{% endfor %}
Note that in the view, you can optimize the number of queries to the database with a .select_related(…) clause [Django-doc]:
planning = Planning.objects.filter(
added_by=request.user
).select_related('activity').order_by('-date')